'Flutter state management with firestore

I am currently working on my first App with flutter+firestore as a backend. The issue that I currently have is that most of the state management solutions seem to work fine for small examples, but don't scale very well once you need to watch multiple collections for changes it becomes complicated.

My current solution looks like this:

import 'package:activilit/model/activity.dart';
import 'package:flutter/cupertino.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';

class ActivityProvider extends ChangeNotifier {
  ActivityProvider() {
    _activities_sub = _activities_collection
        .where("users", arrayContains: FirebaseAuth.instance.currentUser!.uid)
        .orderBy('from', descending: true)
        .snapshots()
        .listen((event) {
      set_activities(event.docs.map((e) => e.data()).toList());
    });
  }

  final _activities_collection = FirebaseFirestore.instance
      .collection('activities')
      .withConverter<Activity>(
        fromFirestore: (snapshot, _) =>
            Activity.fromJson(snapshot.data()!, snapshot.id),
        toFirestore: (activity, _) => activity.toJson(),
      );

  var _activities_sub;
  List<Activity> _activities = [];

  void set_activities(activities) {
    _activities = activities;
    notifyListeners();
  }

  List<Activity> get activities => _activities;

  CollectionReference<Activity> get activities_collection =>
      _activities_collection;

  void deleteActivity(Activity activity) {
    activities_collection.doc(activity.doc_id).delete();
  }
}

It uses a ChangeNotifier to wrap the collection with a listener. Note that I am also getting the ids of all documents so that I can update documents later. This approach works and I can use this with Multiprovider to watch as many collections as I want but it kind of feels like I am reimplementing something and that there should be a "better" solution.

I had a look at Streambuilder but I couldn't figure out how to nest them properly so that I can access and update data of multiple different collections.

Is there a best practice for how to do something like this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source