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.
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:
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();
}
},
),
);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.