Home > Blockchain >  How to list values ​from documents in Flutter Firestore?
How to list values ​from documents in Flutter Firestore?

Time:04-14

I have a Firebase Firestore build like this:

enter image description here

I want to pull the title value from all documents in the collection and display this incoming data with ListTile.

I was able to access all the title values ​​with the code I wrote:

FirebaseFirestore.instance.collection(user.uid).get().then((value) {
  value.docs.forEach((element) {
    print(element.data()["title"]);
  });
});

But I don't know how to dump the incoming values ​​to ListTile. How can I dump these incoming title values ​​to ListTile?

CodePudding user response:

If you don't use any state management solution (Riverpod, Provider, Bloc, etc.) you can just use a FutureBuilder or if you want to get a live data Stream you can use a StreamBuilder like this

Streambuilder Sample:

StreamBuilder<QuerySnapshot<Map<String, dynamic>>>( // inside the <> you enter the type of your stream
      stream: FirebaseFirestore.instance.collection(user.uid).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();
        }
      },
    );

I recommend you to use Data classes instead of data.docs.get('xxx').

So for instance:

class MyDataClass {
  final String title;
  final String content;

  MyDataClass({
    required this.title,
    required this.content,
  });

  Map<String, dynamic> toMap() {
    final result = <String, dynamic>{};
  
    result.addAll({'title': title});
    result.addAll({'content': content});
  
    return result;
  }

  factory MyDataClass.fromMap(Map<String, dynamic> map) {
    return MyDataClass(
      title: map['title'] ?? '',
      content: map['content'] ?? '',
    );
  }

  String toJson() => json.encode(toMap());

  factory MyDataClass.fromJson(String source) => MyDataClass.fromMap(json.decode(source));
}

To generate the toJson/fromJson or toMap/fromMap functions you can use the Dart Data class generation extension in VSCode or various websites.

Now you can display the data just like this:

if (snapshot.hasData) {
          final List<MyDataClass> myList = snapshot.data!.docs
              .map(
                (doc) => MyDataClass.fromMap(doc.data()),
              )
              .toList();
          return ListView.builder(
            itemCount: myList.length,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(
                  myList[index].title,
                ),
              );
            },
          );
        }
  • Related