本文介绍了ChangeNotifier挂载等效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ChangeNotifier从状态小部件中提取一些逻辑到提供程序:类模型扩展了ChangeNotifier {...}

I am extract some logic from Stateful Widget to Provider with ChangeNotifier: class Model extends ChangeNotifier {...}

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

In my Stateful Widget I have:

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

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

How I can check if Widget is mounted in Model?

例如我怎么打电话:

 if (mounted) {
notifyListeners();
}

推荐答案

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

A simple way is pass 'State' of your Stateful Widget as a parameter to your 'Model'.

赞:

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 是否已安装.您只需要检查模型是否已经处置.您可以在 ChangeNotifier 中覆盖 dispose()方法:

I think you don't need to check the State is mounted or not. You just need to check the Model has been already disposed. You can override dispose() method in 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;
  }
}

并且不要忘记在处理 State 时处理 Model :

And don't forget dispose Model when the State is disposed:

class YourState extends State {
  Model model;

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

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

}

或者您可以在包提供程序中使用 ChangeNotifierProvider 您可以自动处理 Model .

Or you can use ChangeNotifierProvider in package Provider, it will help you to dispose Model automatically.

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"),
        ),
      ),
    );
  }

}

这篇关于ChangeNotifier挂载等效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 06:27