[英]Flutter with Firebase-Firestore (listview)
I try to show a collection with the listview.builder in my flutter app, but I always encountered an error and I really don't know how to make it works.我尝试在我的 flutter 应用程序中使用 listview.builder 显示一个集合,但我总是遇到错误,我真的不知道如何让它工作。
Here is my code:这是我的代码:
class _MessagesPageState extends State<MessagesPage> {
@override
void initState() {
WidgetsFlutterBinding.ensureInitialized();
Firebase.initializeApp();
super.initState();
}
_MessagesPageState();
final db = FirebaseFirestore.instance;
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: null,
body: StreamBuilder<QuerySnapshot<Map<String, dynamic>>>( // inside the <> you enter the type of your stream
stream: FirebaseFirestore.instance.collection('messages').snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
snapshot.data!.docs[index].get('title'),
),
);
},
);
}
if (snapshot.hasError) {
return const Text('Error');
} else {
return const CircularProgressIndicator();
}
},
),
);
}
}
cloud_firestore: 2.5.2
firebase_core: ^1.23.0
You should Initialize Firebase here:您应该在此处初始化 Firebase:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
After doing the above, I don't know if this will work but try something like this:完成上述操作后,我不知道这是否可行,但请尝试以下操作:
class _MessagesPageState extends State<MessagesPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: null,
body: StreamBuilder<QuerySnapshot<Map<String, dynamic>>>( // inside the <> you enter the type of your stream
stream: FirebaseFirestore.instance.collection('messages').snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData && snapshot.data != null) {
return ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
snapshot.data.docs[index].get('title'),
),
);
},
);
}else if (snapshot.hasError) {
return const Text('Error');
} else {
return const CircularProgressIndicator();
}
},
),
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.