I am trying to stream a list of models using Provider and Firebase and set a field value to another model in my app
Asked Answered
V

2

3

I am building a productivity app using Flutter, Provider, and Firebase. I currently have a number of streams where I take a collection from Firestore and turn them into lists of models. I am running into an issue where when I attempt to create a list of task models, I am returned a null list. Inside Firestore, I have a collection of tasks, statuses, and projects. I would like to set the task.project value equal to the associated Project model from the project collection. main.dart:

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(ProductivityApp());
}

class ProductivityApp extends StatefulWidget {
  @override
  _ProductivityAppState createState() => _ProductivityAppState();
}

class _ProductivityAppState extends State<ProductivityApp> {
  bool _initialized = false;
  bool _error = false;

  void initializeFlutterFire() async {
    try {
      await Firebase.initializeApp();
      setState(() {
        _initialized = true;
      });
    } catch (e) {
      _error = true;
    }
  }

  @override
  void initState() {
    initializeFlutterFire();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (_error) {
      return Center(child: Text('Something went wrong'));
    }
    if (!_initialized) {
      return Center(child: Text('Loading'));
    }
    return StreamProvider<User>.value(
      value: AuthService().user,
      child: MultiProvider(   // TODO: fix the issue for user to be logged in for the first time
        providers: [
          StreamProvider<List<Project>>.value(value: ProjectService().streamProjects()),
          StreamProvider<List<Task>>.value(value: TaskService().streamTasks(context)),
          StreamProvider<List<Status>>.value(value: StatusService().streamStatuses())
        ],
          child: MaterialApp(
            title: 'ProductivityApp',
            theme: appTheme(),
            // home: Wrapper(),
            // routes: routes,
            onGenerateRoute: generateRoute,
            initialRoute: '/',
          ),
      ),

    );
  }
}

Task Stream:

// Snapshot Conversion to Task Model and Stream
  Stream<List<Task>> streamTasks(BuildContext context) {
    var ref = _getTaskReference();
    return ref.snapshots().map((querySnapshot) => querySnapshot.docs
        .map((queryDocument) => Task.fromFirestore(queryDocument, context))
        .toList());
  }

Task Model:

class Task {
  String taskID = '';
  String taskName = 'Default Name';
  Project project = Project();
  Status status = Status();
  int taskTime = 0;
  DateTime dueDate = DateTime(1);
  DateTime createDate = DateTime.now();
  // List<String> subtasks = [];

  Task(
      {this.taskID,
      this.taskName,
      this.project,
      this.status,
      this.taskTime,
      this.dueDate,
      this.createDate});



  factory Task.fromFirestore(DocumentSnapshot snapshot, BuildContext context) {
    List<Project> projects = Provider.of<List<Project>>(context);
    List<Status> statuses = Provider.of<List<Status>>(context);
    Map data = snapshot.data();
    Project associatedProject = projects
        .firstWhere((project) => project.projectName == data['pojectName']);
    print(associatedProject);
    Status status = statuses
        .firstWhere((status) => status.statusName == data['statusName']);
    return Task(
        taskID: snapshot.id ?? '',
        taskName: data['taskName'].toString() ?? '',
        project: associatedProject ?? Project(),
        status: status ?? Status(),
        taskTime: data['taskTime'] ?? 0,
        dueDate:
            DateTimeFunctions().timeStampToDateTime(date: data['dueDate']) ??
                DateTime.now(),
        createDate:
            DateTimeFunctions().timeStampToDateTime(date: data['createDate']) ??
                DateTime.now());
  }
}

Thank you for any help!

Volteface answered 29/3, 2021 at 15:48 Comment(0)
V
1

I have finally figured out a solution to my problem! I used a number of different resources and combined them together to get a working model.

First, I implemented a Auth_widget_builder that is rebuilt based on user info based on this answer. This actually solved a previous issue that was set aside to fix later. By using this approach I am able to rebuild the authentication widget above the material design based on user which I need to access the correct firestore document in my user collection.

main.dart

@override
  Widget build(BuildContext context) {
    if (_error) {
      return Center(child: Text('Something went wrong'));
    }
    if (!_initialized) {
      return Center(child: Text('Loading'));
    }
    return Provider(
      create: (context) => AuthService(),
      child: AuthWidgetBuilder(builder: (context, userSnapshot) {
        return MaterialApp(
          title: 'Productivity App',
          theme: appTheme(),
          home: AuthWidget(userSnapshot: userSnapshot),
          // onGenerateRoute: generateRoute,
          // initialRoute: '/',
        );
      }),
    );
  }
}

Second, inside the Auth_widget_builder I nested two MultiProviders. The first created Providers that would produce my Service classes. I then added the builder: function based on this answer, which returned the second MultiProvider which held my StreamProviders. This worked because the builder: function rebuilds BuildContext so then I was able to access objects in other Providers to save as a field in another object.

auth_widget_builder.dart

/// Used to create user-dependant objects that need to be accessible by all widgets.
/// This widget should live above the [MaterialApp].
/// See [AuthWidget], a descendant widget that consumes the snapshot generated by this builder.

class AuthWidgetBuilder extends StatelessWidget {
  const AuthWidgetBuilder({Key key, @required this.builder}) : super(key: key);
  final Widget Function(BuildContext, AsyncSnapshot<UserModel>) builder;

  @override
  Widget build(BuildContext context) {
    print('AuthWidgetBuilder rebuild');
    final authService = Provider.of<AuthService>(context, listen: false);
    return StreamBuilder<UserModel>(
      stream: authService.onAuthStateChanged,
      builder: (context, snapshot) {
        print('StreamBuilder: ${snapshot.connectionState}');
        final UserModel user = snapshot.data;
        if (user != null) {
          return MultiProvider(
            providers: [
              Provider<UserModel>.value(value: user),
              Provider(create: (context) => ProjectService()),
              Provider(create: (context) => StatusService()),
              Provider(create: (context) => TaskService()),
              Provider(create: (context) => TimeService()),
            ],
            builder: (context, child) {
              return MultiProvider(
                providers: [
                  StreamProvider<List<Project>>.value(
                      value: Provider.of<ProjectService>(context)
                          .streamProjects()),
                  StreamProvider<List<Status>>.value(
                      value: Provider.of<StatusService>(context)
                          .streamStatuses()),
                  StreamProvider<List<Task>>.value(
                      value: Provider.of<TaskService>(context)
                          .streamTasks(context)),
                  StreamProvider<List<TimeEntry>>.value(
                      value: Provider.of<TimeService>(context)
                          .streamTimeEntries(context))
                ],
                child: builder(context, snapshot),
              );
            },
            child: builder(context, snapshot),
          );
        }
        return builder(context, snapshot);
      },
    );
  }
}

Third, I updated my service classes to find and pass the appropriate objects to the models.

tasks_data.dart

// Snapshot Conversion to Task Model and Stream
  Stream<List<Task>> streamTasks(BuildContext context) {
    CollectionReference ref = _getTaskReference();
    List<Project> projects;
    getProjects(context).then((projectList) => projects = projectList);
    List<Status> statuses;
    getStatuses(context).then((statusList) => statuses = statusList);
    return ref.snapshots().map((QuerySnapshot querySnapshot) =>
        querySnapshot.docs.map((QueryDocumentSnapshot queryDocument) {
          Project project = projects[projects.indexWhere((project) =>
              project.projectName ==
              queryDocument.data()['projectName'].toString())];
          Status status = statuses[statuses.indexWhere((status) =>
              status.statusName == queryDocument.data()['status'].toString())];
          return Task.fromFirestore(queryDocument, project, status);
        }).toList());
  }

  Future<List<Project>> getProjects(BuildContext context) async {
    List<Project> projects =
        await Provider.of<ProjectService>(context).streamProjects().first;
    return projects;
  }

  Future<List<Status>> getStatuses(BuildContext context) async {
    List<Status> statuses =
        await Provider.of<StatusService>(context).streamStatuses().first;
    return statuses;
  }

The best part about this implementation is that it all happens above the Material Widget which means that I can access it with widgets outside of the normal scope like Navigator.push(). Hopefully this works for anyone needing a similar solution.

Volteface answered 3/4, 2021 at 16:34 Comment(0)
L
0

This is the solution I am currently using:

//main.dart
// ...
StreamProvider<Family>(
  key: ValueKey(userProfile.familyReference?.id),
  initialData: Family(),
  create: (context) => Family().streamFamily(userProfile.familyReference!),
  updateShouldNotify: (previous, current) => // add some logic here or just return true;
),
// ...

Using StreamGroup:

//family.dart
class Family {
// ...
  Stream<Family> streamFamily(DocumentReference familyRef) {
    StreamGroup<Family> streamGroup = StreamGroup();
    FirebaseFirestoreService().streamFamily(familyRef).listen(
      (family) {
        streamGroup.add(FirebaseFirestoreService()
            .streamUserProfiles(family.userProfiles)
            .map<Family>((userList) => this..users = userList));
        streamGroup.add(FirebaseFirestoreService()
            .streamChildProfiles(family.childProfiles)
            .map<Family>((childList) => this..childs = childList));
      },
    );
    return streamGroup.stream;
  }
// ...
}
class FirebaseFirestoreService {
// ...
  Stream<Family> streamFamily(DocumentReference familyRef) {
    try {
      return familyRef.snapshots().map(
        (snapshot) {
          try {
            if (snapshot.data() == null) {
              throw Exception('snapshot-null');
            }
          } on Exception catch (e) {
            return Family();
          }
          return Family.fromMap(
            snapshot.data() as Map<String, dynamic>,
            FirebaseAuthService().currentUser!.uid,
            snapshot.reference,
          );
        },
      );
    } catch (e) {
      return const Stream.empty();
    }
  }

  Stream<List<ChildProfile>> streamChildProfiles(
      List<DocumentReference> childDocRefList) {
    List<String> childUidList = childDocRefList.map((childRef) => childRef.id).toList();
    return childProfiles()
        .where(FieldPath.documentId, whereIn: childUidList)
        .snapshots()
        .map((snapshot) => snapshot.docs
            .map(
              (docSnapshot) => ChildProfile.fromMap(
                (docSnapshot.data() as Map<String, dynamic>),
                docSnapshot.reference,
              ),
            )
            .toList());
  }

  Stream<List<UserProfile>> streamUserProfiles(List<DocumentReference> userDocRefList) {
    List<String> userUidList = userDocRefList.map((userRef) => userRef.id).toList();
    return userProfiles()
        .where(FieldPath.documentId, whereIn: userUidList)
        .snapshots()
        .map((snapshot) => snapshot.docs
            .map(
              (docSnapshot) => UserProfile.fromMap(
                (docSnapshot.data() as Map<String, dynamic>),
                docSnapshot.reference,
              ),
            )
            .toList());
  }
// ...
}
Lisalisabet answered 31/10, 2021 at 4:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.