scoped_model-setState重置整个扩展的Model类

时间:2018-07-11 02:49:36

标签: dart flutter

当我按下AppBar中的按钮以更改其名称时, 但是,为什么在使用带有setState的Button后,类Hui中的所有值都将扩展模型类重置?

例如... setState((){tmp = 1;});

我该如何避免呢?

enter image description here

class Hui extends Model {
  String name = "Hi";

  void changeName() {
    name = "Hello World";
    notifyListeners();
  }
}





class _MyAppState extends State<MyApp> {
      int tmp = 0;
      @override
      Widget build(BuildContext context) {
        return new ScopedModel<Hui>(
          model: Hui(),
          child: Scaffold(
            appBar: AppBar(
              title: Text('State Test'),
              actions: <Widget>[
                ScopedModelDescendant<Hui>(
                  builder: (context, child, model) => IconButton(
                        icon: Icon(Icons.perm_phone_msg),
                        onPressed: () {
                          model.changeName();
                        },
                      ),
                ),
              ],
            ),
            body: Column(
              children: <Widget>[
                ScopedModelDescendant<Hui>(
                    builder: (context, child, model) => Text(model.name)),
                IconButton(
                  icon: Icon(Icons.perm_phone_msg),
                  onPressed: () {
                    setState(() {
                      tmp = 1;
                    });
                  },
                ),
              ],
            ),
          ),
        );
      }
    }

1 个答案:

答案 0 :(得分:3)

您可以将模型保存为小部件状态,这样就不会每次都在build方法中重新创建模型。

类似这样的东西:

class _MyAppState extends State<MyApp> {
    Hui _hui = Hui();

    ....
    @override
    Widget build(BuildContext context) {
      return new ScopedModel<Hui>(
        model: _hui,
        ...