gpt4 book ai didi

flutter - 小部件停用后如何在 ChangeNotifier 中捕获错误?

转载 作者:行者123 更新时间:2023-12-03 02:49:27 25 4
gpt4 key购买 nike

我在 Model 中有要执行的代码。我使用 Provider 提供 Model。但是如果 Model 在完成执行之前被释放,我会得到错误:

E/flutter (26180): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: A Model was used after being disposed. E/flutter (26180): Once you have called dispose() on a Model, it can no longer be used.

例如,如果用户按下返回按钮,Navigator.pop() 就会释放 Model。这是因为 Model 仅适用于此 Widget。

但这意味着我无法捕获 Model 中的错误?

我的代码:

class Model extends ChangeNotifier {

bool error = false;

func() {

try {

await execute();
error = false

} catch {
error = true;
print(e.toString());
}

}

}



class ExampleWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {

return ChangeNotifierProvider(
builder: (context) => Model(),
child: Consumer<Model>(builder: (context, model, _) {
return FloatingActionButton(
child: model.error ? Icon(Icons.error) : Icon(Icons.check),
onPressed: () {
model.func();
}
);


如何在处理后捕获模型中的错误?

最佳答案

我刚遇到同样的问题。

错误的发生是因为您使用了 ChangeNotifier 方法之一,通常是 notifyListeners()(我假设您正在调用,但未粘贴code) 在调用 dispose() 之后。顺便说一句,这是一个断言错误,所以只在调试版本中。

要消除错误,您可以在使用自己的标志调用 notifyListeners() 之前检查对象是否已被释放:

class Model extends ChangeNotifier {
bool error = false;
bool isDisposed = false;

func() {
try {
await execute();
error = false
} catch {
error = true;
print(e.toString());
}

if (!isDisposed) {
notifyListeners();
}
}

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

关于flutter - 小部件停用后如何在 ChangeNotifier 中捕获错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58578135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com