![](/img/trans.png)
[英]Using flutter HookWidget and didChangeAppLifecycleState
[英]How to have access Context in didChangeAppLifecycleState lifecycle hook using flutter HookWidget?
我正在嘗試訪問上下文,以便我可以讀取我的提供程序,但由於此生命周期掛鈎位於小部件樹之外。 它無法訪問。 有沒有辦法訪問上下文?
我研究了一下,最后與來自 flutter bloc 社區的 narcodico 進行了討論,所以學分是給他的。
Therefore, mixin WidgetsBindingObserver
on a state class, the context
is available even in the overrides like didChangeAppLifecycleState
since they are part of the state class.
此外,請考慮移動到 state 小部件上方的 BlocProvider。
例子
class HomePageProvider extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => getIt<InAppPurchasesBloc>(),
child: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _HomePageState();
}
}
class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
...
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
context
.read<InAppPurchasesBloc>()
.add(const InAppPurchasesEvent.getPurchaserInfo());
}
}
...
}
恐怕您無法訪問 didChangeAppLifecycleState 中的上下文。
對於任何感興趣的人,您可以將腳手架 state 保存在全局密鑰中,並從其當前 state 訪問上下文。
您可以考慮使用Riverpod package 代替 Provider。 Riverpod 與 Provider 出自同一作者,被認為是“更好的 Provider”,但有許多改進,包括 Flutter 獨立性,這意味着它不依賴於上下文來工作,您可以使用幾乎與 provider 相同的方式使用它。
使用 Riverpod 以及 Flutter Hooks,您可以執行以下操作:
// create a provider in a global context
final myProvider = Provider((ref) => myClass());
// access the provider inside your class
class MyWidget extends HookWidget{
//access the provider using a hook
final myClassProvider = useProvider(myProvider);
//... your logic
@override
Widget build (BuildContext context){/* ... build widget tree... */}
}
考慮這個非常有用且簡潔的教程,其中介紹了如何將 Riverpod 與 Flutter Hooks 和 StateNotifier、ChangeNotifier 等一起使用...
您可以使用useEffect
function,閱讀更多: https://pub.dev/documentation/flutter_hooks/latest/flutter_hooks/useEffect.ZFC35FDC70D5FC69D269883A82
Widget build(BuildContext context) {
useEffect(() {
//what would you write in initState
},
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.