adi*_*adi 2 flutter-provider flutter-bloc
由于代码太大,我会尝试用文字总结一下。
这是最新的异常:
Error: Could not find the correct Provider<ProdEntriesSearchCubit> above this BlocListener<ProdEntriesSearchCubit, ProdEntriesSearchState> Widget
This likely happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:
- The provider you are trying to read is in a different route.
Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.
- You used a `BuildContext` that is an ancestor of the provider you are trying to read.
Make sure that BlocListener<ProdEntriesSearchCubit, ProdEntriesSearchState> is under your MultiProvider/Provider<ProdEntriesSearchCubit>.
This usually happens when you are creating a provider and trying to read it immediately.
Run Code Online (Sandbox Code Playgroud)
在屏幕 1 中,我有以下构建方法:
Widget build(BuildContext context) {
final entriesState = context.watch<ProdEntriesCubit>().state;
return BlocProvider(
create: (context) => ProdEntriesSearchCubit(
productsRepository: context.watch<ProductsRepository>(),
),
child: Builder(
builder: (context) => SafeScreen(
child: Scaffold(
body: _buildBody(context, entriesState: entriesState),
floatingActionButton: _buildFab(context),
),
),
),
);
}
_buildFab(BuildContext context) {
return FloatingActionButton(
child: Icon(
Icons.add,
color: Colors.white,
),
onPressed: () async {
await navigatorPush(context, screen: AdminProdEntryScreen());
},
);
}
Run Code Online (Sandbox Code Playgroud)
在 AdminProdEntryScreen 中我再次执行:
navigatorPush(
context,
screen: EntryProdSearchScreen(),
);
Run Code Online (Sandbox Code Playgroud)
在 EntryProdSearchScreen 中,我收到上面的错误。
为什么在小部件树中找不到 BloC/Cubit?
我什至使用了多个构建器小部件,但我总是受到此异常的影响。
当您提供 BLoC 时,它可以访问当前的小部件树,当您导航到另一个屏幕时,它将无法访问该 BLoC。您可以通过以下两种方法之一解决此问题。
1
您使用块(多)提供程序包装整个应用程序,无论导航如何,您都可以访问该块。
这样做的原因是因为您将导航包含在MaterialApp块提供程序中。
runApp(
MultiBlocProvider(
providers: [
BlocProvider<ProdEntriesSearchCubit>(
create: (context) => ProdEntriesSearchCubit(),
),
],
child: MyApp(),
),
);
Run Code Online (Sandbox Code Playgroud)
2
您可以通过导航路线传递块的实例,并用于BlocProvider.value提供块的相同实例。
//nav method
Navigator.of(context).pushNamed(
'/entry_prod_search_screen',
arguments: context.read< ProdEntriesSearchCubit >(),
);
//in the navigated route screen
final bloc = ModalRoute.of(context).settings.arguments;
return MultiBlocProvider(
providers: [
BlocProvider.value(
value: bloc,
),
],
child: ...,
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1734 次 |
| 最近记录: |