复选框不会改变它们在 MobX 中的状态

Checkbox are not changing their status with MobX

我在 Flutter 上使用 MobX 来控制状态。 单击 FloatingActionButton 会生成包含 CheckboxListTileListView。 然而复选框并没有改变它们的状态

你能帮我解决这个问题吗?

下面是代码和图片:

home_controller.dart

import 'package:flutter/material.dart';
import 'package:mobx/mobx.dart';
import 'package:flutter_modular/flutter_modular.dart';

part 'home_controller.g.dart';

@Injectable()
class HomeController = _HomeControllerBase with _$HomeController;

abstract class _HomeControllerBase with Store {
  @observable
  ObservableList<CheckBoxModel> mapValues = <CheckBoxModel>[].asObservable();

  @observable
  ListView listViewCheckbox;

  @action
  void listViewChekbox(value) {
    for (var i in value) {
      mapValues.add(CheckBoxModel(key: i));
    }
  }
}

class CheckBoxModel{
  
  CheckBoxModel({this.key, this.checked = false});
  
  String key;
  bool checked;
}

home_page.dart

import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'home_controller.dart';

class HomePage extends StatefulWidget {
  final String title;
  const HomePage({Key key, this.title = "Home"}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends ModularState<HomePage, HomeController> {
  HomeController controller = HomeController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Observer(builder: (_) {
        return controller.mapValues == null ? Container() : ListView.builder(
          itemCount: controller.mapValues.length,
          itemBuilder: (_, int index){
            return CheckboxListTile(
              title: Text(controller.mapValues[index].key),
              value: controller.mapValues[index].checked,
              onChanged: (bool value) {
                controller.mapValues[index].checked = value;
              },
            );
          },
        );
      }),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          List listValues = ['foo', 'bar'];
          controller.listViewChekbox(listValues);
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

根据图像,CheckboxListTileListView 已创建,但复选框未更改其状态。

找到的解决方案是插入 setState

onChanged: (bool value) {
    setState(() {
        controller.mapValues[index].checked = value;
    });
},

你不必使用 setState() 或者 mobX 为你做的任何其他事情,你只需要编辑你的抽象 class 来告诉 mobX 主变量值改变了,比如 next

abstract class _HomeControllerBase with Store {
  @observable
  ObservableList<CheckBoxModel> mapValues = <CheckBoxModel>[].asObservable();

  @observable
  ListView listViewCheckbox;

  @action
  void listViewChekbox(value) {
    for (var i in value) {
      mapValues.add(CheckBoxModel(key: i));
    }
    mapValues = mapValues;
  }
}

这就是你可以解决的方法。