Convert Firestore DocumentSnapshot to Map in Flutter

后端 未结 5 1602
误落风尘
误落风尘 2020-12-16 07:13

I need to update a document with nested arrays in Firestore with Flutter.

So I need to get the full document into a Map, reorder the maps in the \"sections\" array,

相关标签:
5条回答
  • 2020-12-16 07:51

    Needed to simplify for purpose of example

    class ItemsList extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        // get the course document using a stream
        Stream<DocumentSnapshot> courseDocStream = Firestore.instance
            .collection('Test')
            .document('4b1Pzw9MEGVxtnAO8g4w')
            .snapshots();
    
        return StreamBuilder<DocumentSnapshot>(
            stream: courseDocStream,
            builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
              if (snapshot.connectionState == ConnectionState.active) {
    
                // get course document
                var courseDocument = snapshot.data.data;
    
                // get sections from the document
                var sections = courseDocument['sections'];
    
                // build list using names from sections
                return ListView.builder(
                  itemCount: sections != null ? sections.length : 0,
                  itemBuilder: (_, int index) {
                    print(sections[index]['name']);
                    return ListTile(title: Text(sections[index]['name']));
                  },
                );
              } else {
                return Container();
              }
            });
      }
    }
    

    The Results

    0 讨论(0)
  • 2020-12-16 07:52

    Looks like maybe because you got a stream builder, so the Snapshot is a AsyncSnapshot<dynamic>, when you grab its .data, you get a dynamic, which returns a DocumentSnapshot, which then you need to call .data on this object to get the proper Map<String, dynamic> data.

    builder: (context, snapshot) {
    final DocumentSnapshot  ds = snapshot.data;
    final Map<String, dynamic> map = ds.data;
    }
    

    You can also append to arrays using in-built functions, but looks like you wanna do some crazy sorting so all good.

    0 讨论(0)
  • 2020-12-16 08:03

    To get map from documentsnapshot use snapshot.data.data

    0 讨论(0)
  • 2020-12-16 08:05

    As per our discussion snapshot is not a DocumentSnapshot it is AsyncSnapshot

    to get the DocumentSnaphot use snapshot.data

    to get the actual map you can use snapshot.data.data

    0 讨论(0)
  • 2020-12-16 08:07

    Updated September-2020

    To get data from a snapshot document you now have to call snapshot.data() (cloud_firestore 0.14.0 or higher)

    0 讨论(0)
提交回复
热议问题