I'm trying to create a ListView with some data received from Firebase, but I keep getting this message. I have tried with FutureBuilder but nothing was useful
The argument type 'Future' can't be assigned to the parameter type 'Widget?'
Code is here:
class CityScreen extends StatelessWidget {
const CityScreen({Key? key}) : super(key: key);
Future<ListView> CreateList() async {
List<CityButton>? listButtons;
final FirebaseAuth auth = FirebaseAuth.instance;
final User? user = auth.currentUser;
final uid = user!.uid;
CollectionReference trips = FirebaseFirestore.instance.collection('events');
QuerySnapshot eventsQuery =
await trips.where("uid", isEqualTo: uid).orderBy('initDate').get();
// ignore: avoid_function_literals_in_foreach_calls
eventsQuery.docs.forEach((element) {
listButtons!.add(CityButton(
element['city'],
DateTime.parse(element['initDate']),
DateTime.parse(element['endDate'])));
});
return ListView(
children: listButtons!,
);
}
@override
Widget build(BuildContext context) {
Future<ListView> lista = CreateList();
return Scaffold(
backgroundColor: const Color(0xFFF5F5F5),
body: lista,
CodePudding user response:
CreateList()
method is a future
, use FutureBuilder
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFF5F5F5),
body: FutureBuilder<ListView>(
future: CreateList(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done &&
snapshot.hasData) {
return snapshot.data!;
} else {
/// you handle others state like error while it will a widget no matter what, you can skip it
return const CircularProgressIndicator();
}
},
),
CodePudding user response:
When you want to render widget after async then use FutureBuilder()
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<ListView>(
future: CreateList(), // async work
builder: (BuildContext context, AsyncSnapshot<ListView> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Text('Loading....');
default:
if (snapshot.hasError)
return Text('Error: ${snapshot.error}');
else
return snapshot.data;
}
},
),
);
}