ChangeNotifier挂载等效吗?

时间:2019-10-26 10:54:11

标签: flutter dart flutter-provider

我正在使用ChangeNotifier:var myArray = https://user.github.io/arrays/dr.suess

从状态小部件中提取一些逻辑到提供程序:

在我的有状态小组件中,我有:

class Model extends ChangeNotifier {...}

如何检查Widget是否安装在模型中?

例如我怎么打电话:

  if (mounted) {
setState(() {});
}

2 个答案:

答案 0 :(得分:1)

一种简单的方法是将有状态窗口小部件的“状态”作为参数传递给“模型”。

赞:

class Model extends ChangeNotifier {

  Model(this.yourState);

  YourState yourState;

  bool get _isMounted => yourState.mounted;
}

class YourState extends State<YourStatefulWidget> {
  Model model;

  @override
  void initState() {
    super.initState();
    model = Model(this);
  }

  @override
  Widget build(BuildContext context) {
    // your code..
  }
}

我认为您不需要检查State是否已安装。您只需要检查模型是否已经处置。您可以在dispose()中覆盖ChangeNotifier方法:

class Model extends ChangeNotifier {
  bool _isDisposed = false;

  void run() async {
    await Future.delayed(Duration(seconds: 10));
    if (!_isDisposed) {
      notifyListeners();
    }  
  }

  @override
  void dispose() {
    super.dispose();
    _isDisposed = true;
  }
}

别忘了在处置Model时处置State

class YourState extends State {
  Model model;

  @override
  void initState() {
    super.initState();
    model = Model();
  }

  @override
  void dispose() {
    model?.dispose();
    super.dispose();
  }
  /// Your build code...

}

或者您可以在软件包Provider中使用ChangeNotifierProvider,它将帮助您自动处理Model

class YourState extends State {
  Model model;

  @override
  void initState() {
    super.initState();
    model = Model();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<Model>(
      builder: (build) => model,
      child: Container(
        child: Consumer<Model>(
          builder: (context, model, widget) => Text("$model"),
        ),
      ),
    );
  }

}

答案 1 :(得分:0)

只要您用提供程序模型状态包装小部件 并且众所周知,一旦您的小部件被处置 默认情况下,包装了它的提供程序模型已经被废弃

所以您要做的就是定义一个变量isDisposed并修改notifyListeners 如下

MyState with ChangeNotifier{

// to indicate whether the state provider is disposed or not
 bool _isDisposed = false;


   // use the notifyListeners as below
   customNotifyListeners(){
    if(!_isDisposed){
       notifyListeners()
    }
   }




 @override
  void dispose() {
    super.dispose();
    _isDisposed = true;
  }

}