6

我使用 ChangeNotifier 从 Stateful Widget 提取一些逻辑到 Provider:class Model extends ChangeNotifier {...}

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

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

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

例如我如何调用:

 if (mounted) {
notifyListeners();
}
4

3 回答 3

7

一种简单的方法是将 Stateful Widget 的“State”作为参数传递给“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已安装。您只需要检查模型是否已被处理。您可以覆盖以下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;
  }
}

并且不要忘记在处置ModelState处置:

class YourState extends State {
  Model model;

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

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

}

或者你可以ChangeNotifierProvider在包Provider中使用,它会帮助你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"),
        ),
      ),
    );
  }

}
于 2019-10-26T15:01:11.017 回答
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;
  }

}
于 2020-10-21T12:18:56.230 回答
0

只需使用自定义 ChangeNotifier 类。

import 'package:flutter/cupertino.dart';

class CustomChangeNotifier extends ChangeNotifier {
  bool isDisposed = false;

  @override
  void notifyListeners() {
    if (!isDisposed) {
      super.notifyListeners();
    }
  }

  @override
  void dispose() {
    isDisposed = true;
    super.dispose();
  }
}
于 2022-02-17T08:20:59.160 回答