anonymous-dev
anonymous-dev

Reputation: 3529

Is it possible to return my Firestore stream as a List of models?

I made a group service that provides a group stream. This stream is of type Stream<List<GroupModel>> but I don't really know how I can map the Firestore stream in such a way that I get a Stream<List<GroupModel>>. This is what I have thus far.

import 'dart:async';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:wally_talk/data/models/group_model.dart';

class GroupService {

  static const groupCollectionKey = 'groups';
  final CollectionReference groupCollection =
      Firestore.instance.collection(groupCollectionKey);

  Stream<List<GroupModel>> groupStream(String userID) {
    return groupCollection
        .where('members', arrayContains: userID)
        .snapshots()
        .map((snapshot) =>
            snapshot.documents.map((document) => GroupModel.fromMap(id: document.documentID, data: document.data)));
  }

  Future postGroup(String groupName) async {
    // return await groupCollection.add(Group();
  }
}

And this is my group model

import 'package:flutter/foundation.dart';

class GroupModel
{
  final String id;
  final String name;
  final List<String> memberIDs;
  final String adminID;

  GroupModel({@required this.id, @required this.name, @required this.memberIDs, @required this.adminID}) 
  : assert(id != null),
  assert(name != null),
  assert(memberIDs != null),
  assert(adminID != null);

  factory GroupModel.fromMap({@required String id, @required Map data})
  {
    return GroupModel(
      id: id,
      name: data['name'] ?? '',
      memberIDs: data['members'] ?? List<String>(),
      adminID: data['adminID'] ?? '',
    );
  }

  Map<String, dynamic> toMap()
  {
    return Map.fromEntries([
      MapEntry<String, String>('id', id),
      MapEntry<String, String>('name', name),
      MapEntry<String, String>('adminID', adminID)
    ]);
  }
}

And currently I get the following message from the terminal

AsyncSnapshot<List<GroupModel>>(ConnectionState.active, null, type 'MappedListIterable<DocumentSnapshot, GroupModel>' is not a subtype of type 'List<GroupModel>')

When I call it from my StreamBuilder with

stream: groupService.groupStream(userProvider.user.uid),

Upvotes: 1

Views: 276

Answers (1)

Nick Wassermann
Nick Wassermann

Reputation: 182

 Stream<List<GroupModel>> groupStream(String userID) {
return groupCollection
    .where('members', arrayContains: userID)
    .snapshots()
    .map((snapshot) => snapshot.documents.map((document) =>
        GroupModel.fromMap(id: document.documentID, data: document.data)).toList());

Sorry I meant to put it there, my fault. this should work, Ihave a similar stream working like this!

Upvotes: 2

Related Questions