[英]Flutter / BLoC - BlocProvider.of() called with a context that does not contain a Bloc of type ArticlesBloc
I'm developing a new Flutter Mobile app using the BLoC pattern.我正在使用 BLoC 模式开发一个新的 Flutter 移动应用程序。 But I've got a problem and I don't find the solution yet.但我有一个问题,我还没有找到解决方案。 I've got three widgets:我有三个小部件:
My problem is between the second and the third.我的问题在第二个和第三个之间。 When I tap on an article, I've an error: BlocProvider.of() called with a context that does not contain a Bloc of type ArticlesBloc.
当我点击一篇文章时,出现错误: BlocProvider.of() called with a context that does not contain a Bloc of type ArticlesBloc.
I've got this in my MaterialApp routes attribute我的 MaterialApp 路由属性中有这个
MyRoutes.articleList: (context) => BlocProvider<ArticlesBloc>(
create: (context) => ArticlesBloc()..add(ArticlesLoaded()),
child: ArticlesScreen(),
),
This is my article list body:这是我的文章列表正文:
body: BlocBuilder<ArticlesBloc, ArticlesState>(
builder: (BuildContext buildContext, state) {
if (state is ArticlesLoadSuccess) {
final articles = state.articles;
return ListView.builder(
itemCount: articles.length,
itemBuilder: (BuildContext context, int index) {
final article = articles[index];
return ArticleItem(
onTap: () {
Navigator.of(buildContext).push(
MaterialPageRoute(builder: (_) {
return ArticleDetailScreen(id: article.id);
}),
);
},
article: article);
},
);
}
},
),
And my article details page:还有我的文章详情页:
@override
Widget build(BuildContext context) {
return BlocBuilder<ArticlesBloc, ArticlesState>(builder: (context, state) {
final Article article = (state as ArticlesLoadSuccess)
.articles
.firstWhere((article) => article.id == id, orElse: () => null);
return Scaffold(
appBar: AppBar(
title: Text(article.reference + ' - Article details'),
),
body: id == null
? Container()
: Padding(
padding: EdgeInsets.all(16.0),
child: ListView(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Hero(
tag: '${article.id}__heroTag',
child: Container(
width: MediaQuery.of(context).size.width,
child: Text(
article.designation,
),
),
),
],
),
),
],
),
],
),
),
);
});
}
Please heeeelp ^^请帮帮忙^^
Edit 1: I find a solution but I don't know if it's the right way.编辑1:我找到了解决方案,但我不知道它是否正确。 Instead of only pass the id to the details screen, I pass the complete article so I can directly return the Scaffold without the BlocBuilder我不只是将 id 传递给详细信息屏幕,而是传递了完整的文章,因此我可以直接返回 Scaffold 而无需 BlocBuilder
You need to provide your bloc to your new route with ArticleDetailScreen
.您需要使用ArticleDetailScreen
将您的集团提供给您的新路线。 Like this:像这样:
MaterialPageRoute(builder: (_) {
return BlocProvider.value(
value: BlocProvider.of<ArticlesBloc>(context),
child: ArticleDetailScreen(id: article.id),
);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.