Flutter ChangeNotifier安装的等价物?
我正在使用ChangeNotifier将一些逻辑从有状态小部件提取到提供者:Flutter ChangeNotifier安装的等价物?,flutter,dart,flutter-provider,Flutter,Dart,Flutter Provider,我正在使用ChangeNotifier将一些逻辑从有状态小部件提取到提供者:类模型扩展ChangeNotifier{…} 在我的有状态小部件中,我有: if (mounted) { setState(() {}); } 如何检查小部件是否安装在模型中 例如,我如何呼叫: if (mounted) { notifyListeners(); } 一种简单的方法是将有状态小部件的“状态”作为参数传递给“模型” 像这样: 类模型扩展了ChangeNotifier{ 模型(this.yourSt
类模型扩展ChangeNotifier{…}
在我的有状态小部件中,我有:
if (mounted) {
setState(() {});
}
如何检查小部件是否安装在模型中
例如,我如何呼叫:
if (mounted) {
notifyListeners();
}
一种简单的方法是将有状态小部件的“状态”作为参数传递给“模型” 像这样:
类模型扩展了ChangeNotifier{
模型(this.yourState);
你的状态你的状态;
bool get _isMounted=>yourState.mounted;
}
类YourState扩展State{
模型;
@凌驾
void initState(){
super.initState();
模型=模型(本);
}
@凌驾
小部件构建(构建上下文){
//你的代码。。
}
}
我认为您不需要检查状态
是否已装入。您只需检查模型是否已被处置。您可以覆盖ChangeNotifier
中的dispose()
方法:
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;
}
}
当处置状态
时,不要忘记处置模型
:
class YourState extends State {
Model model;
@override
void initState() {
super.initState();
model = Model();
}
@override
void dispose() {
model?.dispose();
super.dispose();
}
/// Your build code...
}
或者您可以在软件包中使用ChangeNotifierProvider
,它将帮助您自动处理模型
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"),
),
),
);
}
}
类YourState扩展State{
模型;
@凌驾
void initState(){
super.initState();
模型=模型();
}
@凌驾
小部件构建(构建上下文){
返回ChangeNotifierProvider(
生成器:(build)=>模型,
子:容器(
儿童:消费者(
生成器:(上下文、模型、小部件)=>文本(“$model”),
),
),
);
}
}
只要你用提供者模型状态包装你的小部件
众所周知,一旦你的小部件被处理掉
默认情况下,包装它的提供程序模型已被释放
因此,您所要做的就是定义一个变量isDisposed并修改notifyListeners
如下
谢谢,我在使用
TabController
并从选项卡1切换到选项卡3时遇到了类似的问题。执行此操作时,选项卡2也已初始化,并且调用notifyListeners()
导致异常,因为小部件已被释放。请尝试选中ChangeNotify Disposted而不是State mounted。我已经为你编辑了答案@安卡
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;
}
}