Search code examples
firebaseflutterdartdart-null-safety

A value of type 'Object?' can't be assigned to a variable of type 'Tasker?'


Recently updated an existing and working flutter project to null safety but I cannot get my sign-in logic with firebase to work. It fails with the below error

A value of type 'Object?' can't be assigned to a variable of type 'Tasker?'. Try changing the type of the variable, or casting the right-hand type to 'Tasker?'.

Widget _getScreenId() {
    print('screen id');
    return StreamBuilder<User?>(
      stream: FirebaseAuth.instance.authStateChanges(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          Provider.of<UserData>(context, listen: false).currentUserId =
              snapshot.data!.uid;
          return FutureBuilder(
              future: DatabaseService.getUserWithId(snapshot.data!.uid),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  print(snapshot.data);
                  Tasker? user = snapshot.data;
                  print("home");
                  return HomeScreen(user: user, currentUserId: '',);
                }
                return const SizedBox.shrink();
              });
        } else {
          return const LoginScreen();
        }
      },
    );
  }

Solution

  • ended up with this which seems to work

     Widget _getScreenId() {
        // print('screen id');
        return StreamBuilder<User>(
          stream: FirebaseAuth.instance.authStateChanges(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              Provider.of<UserData>(context, listen: false).currentUserId =
                  snapshot.data.uid;
              return FutureBuilder(
                  future: DatabaseService.getUserWithId(snapshot.data.uid),
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      Tasker user = snapshot.data;
                      // print("home");
                      return HomeScreen(currentUserId: user.id, user: user);
                    }
                    return const SizedBox.shrink();
                  });
            } else {
              return const LoginScreen();
            }
          },
        );
      }