英文:
Flutter: Access BlocProvider with a GlobalKey
问题
以下是翻译好的部分:
这是我的BlocProvider(在MainApp内部):
final keyBlocProvider =
GlobalKey<NavigatorState>(debugLabel: "BlocProvider Navigator");
class MainApp extends StatelessWidget {
const MainApp({super.key});
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
key: keyBlocProvider, // 我试图使用这个键来访问BlocProvider
providers: [
BlocProvider<ClockBloc>(
create: (_) => ClockBloc(),
),
],
child: MaterialApp(home: const App(),)
)
}
}
在MainApp
中,我有一个名为App
的小部件,在其中我试图在我的构建函数之外访问BlocProvider:
class _AppState extends State<App> {
@override
Widget build(BuildContext context) {}
/// 当应用程序加载时处理通知
void onNotificationListener(String? payload) {
var context = Navigator.of(keyBlocProvider.currentContext!).context; // 在这里我的应用程序会冻结
}
}
我这样做的原因是,当用户按下通知时,我希望在我的应用程序启动时导航到某个页面,但为了做到这一点,我首先必须调用某个Bloc事件。
英文:
Here's my BlocProvider (inside MainApp):
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
final keyBlocProvider =
GlobalKey<NavigatorState>(debugLabel: "BlocProvider Navigator");
class MainApp extends StatelessWidget {
const MainApp({super.key});
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
key: keyBlocProvider, // I'm trying to access BlocProvider with this key
providers: [
BlocProvider<ClockBloc>(
create: (_) => ClockBloc(),
),
],
child: MaterialApp(home: const App(),)
)
}
}
<!-- end snippet -->
Inside MainApp
, I have a widget called App
, where I try to access BlocProvider outside of my build function:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
class _AppState extends State<App> {
@override
Widget build(BuildContext context) {}
/// Process notification when loading the app
void onNotificationListener(String? payload) {
var context = Navigator.of(keyBlocProvider.currentContext!).context; // my app freezes here
}
}
<!-- end snippet -->
The reason I do this is because when my app launches when users press a notification, I want to navigate to a certain page, but to do that I first have to call a certain Bloc event.
答案1
得分: 1
我认为你只需要在AppState类内部使用BlocProvider.of()
来获取Bloc并调用其事件,以下是代码示例:
_clockBloc = BlocProvider.of<ClockBloc>(context);
_clockBloc.add(YourEvent());
请告诉我是否解决了你的问题。
英文:
as you have mentioned you want to get the bloc and call its events,I think you just needs to simply find it by BlocProvider.of() inside Appstate class, here is the code:
_clockBloc = BlocProvider.of<ClockBloc>(context);
_clockBloc.add(YourEvent());
pls let me know if it solved your problem
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论