Convert Firestore DocumentSnapshot to Map in Flutter

Christopher Armstrong

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, and then store the data back into the document.

I'm however unfamiliar how I can get the data of the snapshot (DocumentSnapshot) into a Map.

Below an example that doesn't work of what I try to achieve:

final Map<String, dynamic> doc = snapshot.data as Map<String, dynamic>;

"snapshot.data" contains the values of the document. The structure of the document looks like this:

{
  name: "Course 1"
  sections: [
    {name: "Section 1"},
    {name: "Section 2"}
  ]
}

Once the Maps in the sections array have been re-ordered, I need to save the data back into the document.

  • Question 1: How can I read the contents of snapshot.data into a Map?
  • Question 2: Would I delete the document, and add it again? Or can I just update all the contents?

Here the full function. Relevant code is in "onDragFinish".

 // Build editable list with draggable list tiles and swipe to delete
  List<Widget> buildListViewEdit() {
    final course = db.collection("school").document("3kRHuyk20UggHwm4wrUI")
      .collection("course").document("74UsE9x7Bsgnjz8zKozv").snapshots();

    return [
      StreamBuilder(
        stream: course,
        builder: (context, snapshot) {
          if (!snapshot.hasData) return const Text("Loading...");

          return Expanded(
            child: DragAndDropList(
              snapshot.data["sections"].length,
              itemBuilder: (context, index) {
                return Card(
                  child: ListTile(
                    title: Text(snapshot.data["sections"][index]["name"]),
                    onTap: () {
                      print("hello");
                    }                    
                  )
                );
              },
              onDragFinish: (before, after) {
                print('on drag finish $before $after');

                //final docString = snapshot.data.toString();

                final Map <String, dynamic> doc = snapshot.data;

                //final tempSections = List.castFrom(snapshot.data["sections"]).toList();

                //Map data = tempSections[before];

                //tempSections.removeAt(before);
                //tempSections.insert(after,data);

                //snapshot.data["sections"] = tempSections;

                //db.collection("school").document("3kRHuyk20UggHwm4wrUI")
                  //.collection("course").document("74UsE9x7Bsgnjz8zKozv").updateData(snapshot.data);

                //var line = snapshot.data["sections"][before];

                //snapshot.data["sections"].removeAt(before);
                //snapshot.data["sections"].insert(after,line);

                /*
                List<Map> sections = docCopy["sections"];

                Map data = docCopy["sections"][before];
                sections.removeAt(before);
                sections.insert(after, data);
                print(sections);   
                */         
              },
              canDrag: (index) {
                print('can drag $index');
                return index != 3;
              },
              canBeDraggedTo: (one, two) => true,
              dragElevation: 8.0,
            )
          );
        }
      )
    ];   
  }

Error when trying to copy snapshot.data into another variable:

flutter: ══╡ EXCEPTION CAUGHT BY GESTURE LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown while routing a pointer event:
flutter: type 'DocumentSnapshot' is not a subtype of type 'Map<String, dynamic>'
flutter:
flutter: Either the assertion indicates an error in the framework itself, or we should provide substantially
flutter: more information in this error message to help you determine and fix the underlying cause.
flutter: In either case, please report this assertion by filing a bug on GitHub:
flutter:   https://github.com/flutter/flutter/issues/new?template=BUG.md
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0      _SectionScreenState.buildListViewEdit.<anonymous closure>.<anonymous closure> (package:teach_mob/screens/section_screen.dart:150:45)

Working example

Thanks all for your assistance. Here a full example that worked for me:

  // Build editable list with draggable list tiles and swipe to delete
  List<Widget> buildListViewEdit() {
    final course = db.collection("school").document("3kRHuyk20UggHwm4wrUI")
      .collection("course").document("74UsE9x7Bsgnjz8zKozv").snapshots();

    return [
      StreamBuilder(
        stream: course,
        builder: (context, snapshot) {
          if (!snapshot.hasData) return const Text("Loading...");

          return Expanded(
            child: DragAndDropList(
              snapshot.data["sections"].length,
              itemBuilder: (context, index) {
                return Card(
                  child: ListTile(
                    title: Text(snapshot.data["sections"][index]["name"]),
                    onTap: () {
                      print("hello");
                    }                    
                  )
                );
              },
              onDragFinish: (before, after) {
                print('on drag finish $before $after');

                // Convert AsyncSnapshot to DocumentSnapshot and then
                // create a map that can be changed and updated.
                final Map <String, dynamic> doc = snapshot.data.data;

                // Convert fixed length list to dynamic list, because items in
                // fixed length lists can't be added / removed.
                final tempSections = List.castFrom(doc["sections"]).toList();

                // Get the data of the list item to be dragged
                // Remove the data from the current position
                // Add the data to the new position of the list
                Map data = tempSections[before];

                tempSections.removeAt(before);
                tempSections.insert(after,data);

                // Overwrite sections with new list array
                doc["sections"] = tempSections;

                // Store the data back into the firestore document
                db.collection("school")
                  .document("3kRHuyk20UggHwm4wrUI")
                  .collection("course")
                  .document("74UsE9x7Bsgnjz8zKozv")
                  .updateData(doc);
              },
              canDrag: (index) {
                print('can drag $index');
                return index != 3;
              },
              canBeDraggedTo: (one, two) => true,
              dragElevation: 8.0,
            )
          );
        }
      )
    ];   
  }
Saed Nabil

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

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How to convert Firestore DocumentSnapshot to dart object instance

分類Dev

Firestore iOS DocumentSnapshot `createTime`

分類Dev

Flutter firestore fetch documents with a condition on a map field

分類Dev

FireStore fromSnapshot vs fromMap for reading DocumentSnapshot?

分類Dev

Flutter Cloud Firestore Map <String、dynamic>エラー

分類Dev

How to add map inside document in firestore using flutter?

分類Dev

Flutter FireStore

分類Dev

documentSnapshotからCloud Firestoreドキュメント参照を取得する

分類Dev

FirestoreはDocumentSnapshotのフィールドの値を取得します

分類Dev

未定義のdocumentSnapshot.createTimeを返すFirestore(javascriptでwebprojectを使用)

分類Dev

未定義のdocumentSnapshot.createTimeを返すFirestore(javascriptでwebprojectを使用)

分類Dev

Flutter firestore compound query

分類Dev

Flutter Firestore cache stream

分類Dev

Flutter&Cloud Firestore

分類Dev

Flutter:Firestoreに保存

分類Dev

documentSnapshot.data()はビルダーに渡されません:Flutter

分類Dev

DocumentSnapshotイベントのリスナーを削除する方法(Google Cloud FireStore)

分類Dev

Firestoreクエリデータドキュメント、特にDocumentSnapshotについて

分類Dev

Is there a converter method for the object in firestore in flutter?

分類Dev

Firebase cloud firestore not working in flutter

分類Dev

Firestore的Flutter StreamBuilder connectionState问题

分類Dev

scala convert List of map to map

分類Dev

How to convert a map to a map kotlin

分類Dev

rearrange the list map in Flutter

分類Dev

Firestore collection querying on map field

分類Dev

Flutter convert currency format

分類Dev

FlutterのDocumentSnapshotからDocumentReferenceを取得する方法はありますか?

分類Dev

Google Map APIキーをFirestoreに保存しても大丈夫ですか?(Flutterアプリからの呼び出し)

分類Dev

Is there a map of Material design colors for Flutter?

Related 関連記事

  1. 1

    How to convert Firestore DocumentSnapshot to dart object instance

  2. 2

    Firestore iOS DocumentSnapshot `createTime`

  3. 3

    Flutter firestore fetch documents with a condition on a map field

  4. 4

    FireStore fromSnapshot vs fromMap for reading DocumentSnapshot?

  5. 5

    Flutter Cloud Firestore Map <String、dynamic>エラー

  6. 6

    How to add map inside document in firestore using flutter?

  7. 7

    Flutter FireStore

  8. 8

    documentSnapshotからCloud Firestoreドキュメント参照を取得する

  9. 9

    FirestoreはDocumentSnapshotのフィールドの値を取得します

  10. 10

    未定義のdocumentSnapshot.createTimeを返すFirestore(javascriptでwebprojectを使用)

  11. 11

    未定義のdocumentSnapshot.createTimeを返すFirestore(javascriptでwebprojectを使用)

  12. 12

    Flutter firestore compound query

  13. 13

    Flutter Firestore cache stream

  14. 14

    Flutter&Cloud Firestore

  15. 15

    Flutter:Firestoreに保存

  16. 16

    documentSnapshot.data()はビルダーに渡されません:Flutter

  17. 17

    DocumentSnapshotイベントのリスナーを削除する方法(Google Cloud FireStore)

  18. 18

    Firestoreクエリデータドキュメント、特にDocumentSnapshotについて

  19. 19

    Is there a converter method for the object in firestore in flutter?

  20. 20

    Firebase cloud firestore not working in flutter

  21. 21

    Firestore的Flutter StreamBuilder connectionState问题

  22. 22

    scala convert List of map to map

  23. 23

    How to convert a map to a map kotlin

  24. 24

    rearrange the list map in Flutter

  25. 25

    Firestore collection querying on map field

  26. 26

    Flutter convert currency format

  27. 27

    FlutterのDocumentSnapshotからDocumentReferenceを取得する方法はありますか?

  28. 28

    Google Map APIキーをFirestoreに保存しても大丈夫ですか?(Flutterアプリからの呼び出し)

  29. 29

    Is there a map of Material design colors for Flutter?

ホットタグ

アーカイブ