Search code examples
firebaseflutterdartgoogle-cloud-firestoreflutter-provider

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


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!


Solution

  • 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.