Search code examples
firebasefluttergoogle-cloud-firestoreflutter-provider

How does Firestore count reads as it relates to the Provider package in Flutter?


When I call:

final user = Provider.of<CustomUser?>(context);

downstream of My Provider and then call for example user.email... Does that count as a 'Read'?

For further Context when I log in I call ('Read' 1?):

Future signIn(String email, String password) async {
    await _authService.signInWithEmailAndPassword(
        email: email, password: password);
    print('Sign In');
    User? user = _authService.currentUser;

And then I call ('Read' 2?):

CustomUser loggedInUser = CustomUser();
    await FirebaseFirestore.instance
        .collection("users")
        .doc(user!.uid)
        .get()
        .then((value) {
      loggedInUser = CustomUser.fromMap(value.data());
    });

where I map the user info from my firestore collection to my CustomUser object. I then pass the CustomUser through a stream provider (which I think I'm going to change to Change Notifier Provider, but that should be irrelevant for this question...):

Widget build(BuildContext context) {
    return StreamProvider<CustomUser?>.value(
      value: AuthService().user,
      initialData: null,
      child: MaterialApp(
        home: Home()

I then call inside of Home:

final user = Provider.of<CustomUser?>(context);

and populate some text widgets with user.email, user.name, etc... Does that count as a read as well? In other words, does the above logic count as 2 or 3 reads to firebase?


Solution

  • Every time you call get() the Firestore SDK will have to connect to the server to at the very least check if there's a newer version of the document. This is a charged document read.

    I recommend looking into onSnapshot, which keeps an active listener on the document, so will only have to check with the server once when you create the listener, and then only gets an updated document (and thus a charged document read) when there is an update.