How do you load array and object from Cloud Firestore in Flutter

后端 未结 4 600
梦谈多话
梦谈多话 2020-12-01 02:52

I have a class that has several embedded arrays as well as a couple of objects. I\'m using Flutter and can\'t figure out how to read/write to Cloud Firestore.

I can r

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 03:40

    load the list from the array and let the framework take care of type casting.

    an object is simply a map, like you wrote in your Json. I also use named constructor. ((still learning and dont know how to use the static constructor @ganapat mentioned))

    here´s the working code. I kept firebase auth out and used the StreamBuilder widget.

    import 'dart:async';
    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'package:flutter/material.dart';
    import 'model/firebase_auth_service.dart';
    
    void main() async {
      runApp(new MyApp());
    }
    
    class MyApp extends StatelessWidget {
      final firebaseAuth = new FirebaseAuthService();
    
      MyApp() {
        firebaseAuth.anonymousLogin();
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
            home: Scaffold(
                body: Center(
                    child: FlatButton(
          color: Colors.amber,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text("get Game Record"),
              StreamBuilder(
                stream: getGame(),
                builder: (BuildContext c, AsyncSnapshot data) {
                  if (data?.data == null) return Text("Error");
    
                  GameRecord r = data.data;
    
                  return Text("${r.creationTimestamp} + ${r.name}");
                },
              ),
            ],
          ),
          onPressed: () {
            getGame();
          },
        ))));
      }
    }
    
    Stream getGame() {
      return Firestore.instance
          .collection("games")
          .document("zZJKQOuuoYVgsyhJJAgc")
          .get()
          .then((snapshot) {
        try {
          return GameRecord.fromSnapshot(snapshot);
        } catch (e) {
          print(e);
          return null;
        }
      }).asStream();
    }
    
    class GameReview {
      String name;
      int howPopular;
      List reviewers;
    
      GameReview.fromMap(Map data)
          : name = data["name"],
            howPopular = data["howPopular"],
            reviewers = List.from(data['reviewers']);
    }
    
    class GameRecord {
      // Header members
      String documentID;
      String name;
      int creationTimestamp;
      List ratings = new List();
      List players = new List();
      GameReview gameReview;
    
      GameRecord.fromSnapshot(DocumentSnapshot snapshot)
          : documentID = snapshot.documentID,
            name = snapshot['name'],
            creationTimestamp = snapshot['creationTimestamp'],
            ratings = List.from(snapshot['ratings']),
            players = List.from(snapshot['players']),
            gameReview = GameReview.fromMap(snapshot['gameReview']);
    }
    

    snapshot['itemCount'] is an array of objects. map each item in that array to an ItemCount object and return as a List:

        itemCounts = snapshot['itemCount'].map((item) {
          return ItemCount.fromMap(item);
        }).toList();
    

提交回复
热议问题