Firebase 如何使用bloc从fire store检索数据收集列表
我正在尝试从fire store检索数据收集列表,如下所示: 这是我下面的课程:Firebase 如何使用bloc从fire store检索数据收集列表,firebase,flutter,dart,google-cloud-firestore,Firebase,Flutter,Dart,Google Cloud Firestore,我正在尝试从fire store检索数据收集列表,如下所示: 这是我下面的课程: abstract class AppStates {} class AppInitialState extends AppStates {} class AppGetCategoriesLoadingState extends AppStates {} class AppGetCategoriesSuccessState extends AppStates {} class AppGetCategorie
abstract class AppStates {}
class AppInitialState extends AppStates {}
class AppGetCategoriesLoadingState extends AppStates {}
class AppGetCategoriesSuccessState extends AppStates {}
class AppGetCategoriesErrorState extends AppStates {
final String error;
AppGetCategoriesErrorState(this.error);
}
这是我的下一个cubit等级:
class AppCubit extends Cubit<AppStates> {
AppCubit() : super(AppInitialState());
static AppCubit get(context) => BlocProvider.of(context);
List<CategoryModel> categoryModel;
final CollectionReference _categoryCollectionRef =
FirebaseFirestore.instance.collection('PetsCategories');
Future<List<QueryDocumentSnapshot>> getCategory() async {
var value = await _categoryCollectionRef.get();
return value.docs;
}
void getCategoriesData() {
emit(AppGetCategoriesLoadingState());
getCategory().then((value) {
// print(value.data());
for (int i = 0; i < value.length; i++) {
categoryModel.add(CategoryModel.fromJson(value[i].data()));
}
emit(
AppGetCategoriesSuccessState(),
);
}).catchError((error) {
print(error.toString());
emit(
AppGetCategoriesErrorState(
error.toString(),
),
);
});
}
}
类AppCubit扩展了Cubit{
AppCubit():super(AppInitialState());
静态AppCubit get(context)=>BlocProvider.of(context);
列表分类模型;
最终收集参考_categoryCollectionRef=
FirebaseFirestore.instance.collection('PetsCategories');
Future getCategory()异步{
var value=await _categoryCollectionRef.get();
返回值.docs;
}
void getCategoriesData(){
emit(AppGetCategoriesLoadingState());
getCategory()。然后((值){
//打印(value.data());
for(int i=0;i
下面是我的屏幕:
return BlocConsumer<AppCubit, AppStates>(
listener: (context, state) {},
builder: (context, state) {
var cubit = AppCubit.get(context);
return Column(
children: [
SizedBox(
height: 30,
),
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: CustomText(
text: "Categories",
),
),
SizedBox(
height: 30,
),
Container(
height: 100,
child: ListView.separated(
shrinkWrap: true,
physics: BouncingScrollPhysics(),
itemCount: cubit.categoryModel.length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return Column(
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50),
color: Colors.grey.shade100,
),
height: 60,
width: 60,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Image.network(cubit.categoryModel[index].image),
),
),
// SizedBox(
// height: 20,
// ),
CustomText(
text: cubit.categoryModel[index].name,
),
],
);
},
separatorBuilder: (context, index) => SizedBox(
width: 20,
),
),
),
],
);
},
);
返回BlocConsumer(
侦听器:(上下文,状态){},
生成器:(上下文、状态){
var cubit=AppCubit.get(上下文);
返回列(
儿童:[
大小盒子(
身高:30,
),
填充物(
填充:仅限常量边集(左:20.0),
子项:自定义文本(
文本:“类别”,
),
),
大小盒子(
身高:30,
),
容器(
身高:100,
子项:ListView.separated(
收缩膜:对,
物理:弹跳CrollPhysics(),
itemCount:cubit.categoryModel.length,
滚动方向:轴水平,
itemBuilder:(上下文,索引){
返回列(
儿童:[
容器(
装饰:盒子装饰(
边界半径:边界半径。圆形(50),
颜色:Colors.grey.shade100,
),
身高:60,
宽度:60,
孩子:填充(
填充:常数边集全部(8.0),
子项:Image.network(cubit.categoryModel[index].Image),
),
),
//大小盒子(
//身高:20,
// ),
自定义文本(
text:cubit.categoryModel[index]。名称,
),
],
);
},
separatorBuilder:(上下文,索引)=>SizedBox(
宽度:20,
),
),
),
],
);
},
);
这就是我的错误:
The following NoSuchMethodError was thrown building BlocBuilder<AppCubit, AppStates>(dirty, state: _BlocBuilderBaseState<AppCubit, AppStates>#fe322):
The getter 'length' was called on null.
Receiver: null
Tried calling: length
The relevant error-causing widget was:
BlocConsumer<AppCubit, AppStates> file:///Users/mahmoudalharoon/Desktop/IPetApp/IPet%20FlutterProject/ipet/lib/modules/discover/discover_screen.dart:17:12
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 DiscoverScreen.build.<anonymous closure> (package:ipet/modules/discover/discover_screen.dart:40:48)
#2 BlocBuilder.build (package:flutter_bloc/src/bloc_builder.dart:90:57)
#3 _BlocBuilderBaseState.build (package:flutter_bloc/src/bloc_builder.dart:151:21)
#4 StatefulElement.build (package:flutter/src/widgets/framework.dart:4612:27)
...
在生成BlocBuilder时引发了以下NoSuchMethodError(脏,状态:_BlocBuilderBaseState#fe322):
对null调用了getter“length”。
收件人:空
尝试呼叫:长度
导致错误的相关小部件是:
衬衫消费者file:///Users/mahmoudalharoon/Desktop/IPetApp/IPet%20FlutterProject/ipet/lib/modules/discover/discover_screen.dart:17:12
引发异常时,这是堆栈:
#0 Object.noSuchMethod(省道:核心补片/对象补片。省道:54:5)
#1.DiscoverScreen.build。(软件包:ipet/modules/discover/discover_屏幕。dart:40:48)
#2 BlocBuilder.build(包:flatter\u bloc/src/bloc\u builder.dart:90:57)
#3\u BlocBuilderBaseState.build(包:flatter\u bloc/src/bloc\u builder.dart:151:21)
#4 StatefulElement.build(包:flatter/src/widgets/framework.dart:4612:27)
...
您正在发出加载状态,该状态将触发BlocConsumer生成器。为了避免此错误,您需要检查cubit的状态,以确保它是AppGetCategoriesSuccessState
。这样,cubit将定义categoryModel
变量,并且可以使用
我建议避免在Cubit中使用类变量。最好是使用要显示的值发出状态
class AppGetCategoriesSuccessState扩展了AppState{
const AppGetCategoriesSuccessState({required this.values});
最终列表值;
}
那么在你的消费群体中
//在BlocConsumer生成器中
if(状态为AppGetCategoriesSuccessState){
最终_值=状态值;
//在这里使用你的价值观
}
这是我想的最正确的代码
下面是CategoryModel类:
class CategoryModel {
String image;
String type;
CategoryModel({
this.image,
this.type,
});
CategoryModel.fromJson(Map<String, dynamic> map) {
// if (map == null) {
// return;
// }
image = map['image'];
type = map['type'];
}
Map<String, dynamic> toMap() {
return {
'type': type,
'image': image,
};
}
}
这是下面的屏幕:
class DiscoverScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocConsumer<AppCubit, AppStates>(
listener: (context, state) {},
builder: (context, state) {
return Column(
children: [
SizedBox(
height: 30,
),
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: CustomText(
text: "Categories",
),
),
SizedBox(
height: 30,
),
buildCategoryItem(context),
],
);
},
);
}
Widget buildCategoryItem(context) {
return Container(
height: 100,
child: ListView.separated(
shrinkWrap: true,
physics: BouncingScrollPhysics(),
itemCount: AppCubit.get(context).categories.length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return Column(
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50),
color: Colors.grey.shade100,
),
height: 60,
width: 60,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Image.network(
AppCubit.get(context).categories[index].image),
),
),
// SizedBox(
// height: 20,
// ),
CustomText(
text: AppCubit.get(context).categories[index].type,
),
],
);
},
separatorBuilder: (context, index) => SizedBox(
width: 20,
),
),
);
}
}
class DiscoverScreen扩展了小部件{
@凌驾
小部件构建(构建上下文){
返回BlocConsumer(
侦听器:(上下文,状态){},
生成器:(上下文、状态){
返回列(
儿童:[
大小盒子(
身高:30,
),
填充物(
填充:仅限常量边集(左:20.0),
子项:自定义文本(
文本:“类别”,
),
),
大小盒子(
身高:30,
),
buildCategoryItem(上下文),
],
);
},
);
}
Widget buildCategoryItem(上下文){
返回容器(
身高:100,
子项:ListView.separated(
收缩膜:对,
物理:弹跳CrollPhysics(),
itemCount:AppCubit.get(上下文).categories.length,
滚动方向:轴水平,
itemBuilder:(上下文,索引){
返回列(
儿童:[
容器(
装饰:盒子装饰(
博尔德
class DiscoverScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocConsumer<AppCubit, AppStates>(
listener: (context, state) {},
builder: (context, state) {
return Column(
children: [
SizedBox(
height: 30,
),
Padding(
padding: const EdgeInsets.only(left: 20.0),
child: CustomText(
text: "Categories",
),
),
SizedBox(
height: 30,
),
buildCategoryItem(context),
],
);
},
);
}
Widget buildCategoryItem(context) {
return Container(
height: 100,
child: ListView.separated(
shrinkWrap: true,
physics: BouncingScrollPhysics(),
itemCount: AppCubit.get(context).categories.length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return Column(
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50),
color: Colors.grey.shade100,
),
height: 60,
width: 60,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Image.network(
AppCubit.get(context).categories[index].image),
),
),
// SizedBox(
// height: 20,
// ),
CustomText(
text: AppCubit.get(context).categories[index].type,
),
],
);
},
separatorBuilder: (context, index) => SizedBox(
width: 20,
),
),
);
}
}