我正在使用ChangeNotifier从状态小部件中提取一些逻辑到提供程序:class Model extends ChangeNotifier {...}
在我的有状态小组件中,我有:

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

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

例如我如何打电话:
 if (mounted) {
notifyListeners();
}

最佳答案

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

像这样:

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

}

09-04 00:07