当我尝试在State内调用方法时,请像下面这样处理方法。
@override
void dispose() {
Provider.of<AppProvider>(context, listen: false).close();
super.dispose();
}
我懂了。
The following assertion was thrown while finalizing the widget tree:
Looking up a deactivated widget's ancestor is unsafe.
At this point the state of the widget's element tree is no longer stable.
To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.
When the exception was thrown, this was the stack
#0 Element._debugCheckStateIsActiveForAncestorLookup.<anonymous closure>
package:flutter/…/widgets/framework.dart:3508
#1 Element._debugCheckStateIsActiveForAncestorLookup
package:flutter/…/widgets/framework.dart:3522
#2 Element.getElementForInheritedWidgetOfExactType
package:flutter/…/widgets/framework.dart:3588
#3 Provider.of
package:provider/src/provider.dart:219
#4 _MySecondPageState.dispose
package:test_space/main.dart:138
...
这是我的示例AppProvider
class AppProvider {
close() {}
}
我用AppProvider包装了MaterialApp
return Provider<AppProvider>(
create: (_) => AppProvider(),
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomeScreen(),
},
),
);
我不确定该如何做
To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.
我目前正在使用provider: ^4.0.2
。我曾经在dispose()内使用Provider.of(context)来做同样的操作,,之前没有这个异常(exception)。这是因为新的flutter版本吗?
另外,我意识到这里有deactivate()方法,我应该使用deactivate()方法而不是dispose()方法吗?
[更新]
AppProvider _appProvider;
@override
void didChangeDependencies() {
_appProvider = Provider.of<AppProvider>(context, listen: false);
super.didChangeDependencies();
}
@override
void dispose() {
_appProvider.close();
super.dispose();
}
I could also use deactivate in a certain case
@override
void deactivate() {
Provider.of<AppProvider>(context, listen: false)
.close();
super.deactivate();
}
最佳答案
似乎您正在尝试关闭AppProvider类中定义的内容。如果AppProvider类正在扩展ChangeNotifier,则更改通知程序类提供dispose方法,您可以重写它,然后仅在AppProvider类内调用close函数。
关于flutter - 在dispose()方法内部使用Provider.of(context)调用方法会导致 "Looking up a deactivated widget'的祖先不安全。”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60038200/