从Firestore获取文档快照并将其映射到dart对象

时间:2020-08-12 10:24:13

标签: flutter dart

尝试使用类型为List的streambuilder从Firestore中的嵌套集合中获取文档列表。从数据库服务调用文档后,将在null.Kindly Assist上调用该长度。

   //mapping firestore data to a dart object
     Trip.fromFirestore(Map<String, dynamic> doc)
  : title = doc['title'],
    tripId = doc['tripId'],
    budget = doc['budget'],
    tripType = doc['tripType'],
    location = doc['location'],
    timestamp = doc['timestamp'],
    tripDescription = doc['tripDescription'],
    tripDates = doc['tripDates'];

 //Database code:
Stream<List<Trip>> getUserTrips(String userID) {
return _db
    .collection('trips')
    .document(userID)
    .collection('usertrips')
    .snapshots()`enter code here`
    .map((query) => query.documents)
    .map((snapshot) => snapshot
    .map((document) => Trip.fromFirestore(document.data))
    .toList());

}

//Homepage:
SliverToBoxAdapter(
        child: StreamBuilder<List<Trip>>(
          stream: Database().getUserTrips(user.userId),
          builder: (context, snapshot) {
            if (!snapshot.hasData) {
              return Loader();
            }

            final trips = snapshot.data;

            return ListView.builder(
              shrinkWrap: true,
              itemCount: trips.length,
              itemBuilder: (context, index) {
                //print(snapshot.data[index].title);
                return Text(trips[index].title);
                //TripCard();
              },
            );
          },
        ),
      ),

//The Error:
 The getter 'length' was called on null.
 Receiver: null
 Tried calling: length
 The relevant error-causing widget was
 StreamBuilder<List<Trip>> 

1 个答案:

答案 0 :(得分:0)

这不应该是最终的,您正在使用流,并且流会发生变化。

  final trips = snapshot.data;

据我所见,快照的类型为列表。流应该看起来像这样。

SliverToBoxAdapter(
        child: StreamBuilder(
          stream: _db
                    .collection('trips')
                    .document(userID)
                    .collection('usertrips')
                    .snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) {
              return Loader();
            }

            var trips = snapshot.data.documents; //edit

            return ListView.builder(
              shrinkWrap: true,
              itemCount: trips.length,
              itemBuilder: (context, index) {
                //print(snapshot.data[index].title);
                return Text(trips[index].title);
                //TripCard();
              },
            );
          },
        ),
      ),