Mudasir Habib
Mudasir Habib

Reputation: 848

List.add wont works flutter

Code for EventDetails class

class EventDetails {
EventDetails(
      {
      required this.description,
      required this.date,
      required this.startTime,
      required this.endTime,
      required this.speaker,
      required this.isFavorite});

  String description;
  String date;
  String startTime;
  String endTime;
  String speaker;
  String isFavorite;}

Code for network class

class Network {
  static Future<List<EventDetails>> getEvents() async {
    Firebase.initializeApp();
    FirebaseFirestore instance = FirebaseFirestore.instance;
    var data = await instance.collection('event_details').get();
    return makeEvents(data.docs);
  }

  static List<EventDetails> makeEvents(List<dynamic> collection) {
    List<EventDetails> events = [];
    collection.forEach((event) {
      print('++++++++++++++==========');
      print(event['description']);
      print(event['date']);
      print(event['start_time']);
      print(event['end_time']);
      print(event['speaker']);
      print(event['is_favorite']);

  events.add(
    EventDetails(
      description: event['description'],
      date: event['date'],
      startTime: event['start_time'],
      endTime: event['end_time'],
      speaker: event['speaker'],
      isFavorite: event['is_favorite'],
    ),
  );
});
print('--------');
print(events.length);
return events;
  }
}

In the above code Iam trying to fetch data from cloud firestore in getEvents function and return data by converting to EventDetails by makeEvents function. Problem is in my makeEvents function where I set forEach on whole data, first I print whole data and then add into a list of Event details, but in first iteration Data is printed but after this nothing happens, and list or list length is not update

My build Method

@override
  Widget build(BuildContext context) {
    return FutureBuilder<List<EventDetails>>(
      future: Network.getEvents(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return ListView.builder(
              itemCount: snapshot.data!.length,
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text(snapshot.data![index].description),
                );
              });
        }
        return const Center(
          child: CircularProgressIndicator(),
        );
      },
    );
  }

My collection Structure

enter image description here

Upvotes: 0

Views: 52

Answers (1)

Peter Obiechina
Peter Obiechina

Reputation: 2835

First, Firebase.initializeApp(); is an async function. You should wait for it. So change to await Firebase.initializeApp();

Secondly, you should put the await Firebase.initializeApp(); in your main(), not in Network class.

Try this.

class Network {
  static Future<List<EventDetails>> getEvents() async {
    // await Firebase.initializeApp();
    // move above to main() in main.dart
    FirebaseFirestore instance = FirebaseFirestore.instance;
    QuerySnapshot<EventDetails> query = await instance
        .collection('event_details')
        .withConverter<EventDetails>(
          fromFirestore: (snapshot, _) => EventDetails.fromFirestore(snapshot),
          toFirestore: (data, _) => data.toJson(),
        )
        .get();
    List<EventDetails> events = query.docs.map((e) => e.data()).toList();
    print(events);
    return events;
  }
}

Add this to your event model

factory EventDetails.fromFirestore(DocumentSnapshot<Map<String, dynamic>> snapshot) {
  Map<String, dynamic> json = snapshot.data();
  return EventDetails(
    id: snapshot.id,
    // The above gives you the document id in the model
    // you should add id to your model
    description: json['description'] as String,
    date: json['date'] as String,
    // startTime and endTime should be dateTime;
    startTime: json['start_time'],
    endTime: json['end_time'],
    // speaker should be map
    speaker: json['speaker'],
    isFavorite: json['is_favorite'] as bool,
  );
}
Map<String, dynamic> toJson() => <String, dynamic>{
  'description': this.description,
  'date': this.date,
  'start_time': this.startTime,
  'end_time': this.endTime,
  'speaker': this.speaker,
  'is_favorite': this.isFavorite,
};

Upvotes: 1

Related Questions