Hrushikesh Vaidya
Hrushikesh Vaidya

Reputation: 17

Flutter FutureBuilder's future never seems to complete

I'm new to Flutter and Dart, and I'm trying to build an app that allows users to sign in with Google and allows them to choose a Google Sheet to use with the app from the Google Sheets they have in their Drive. When the app starts, I perform the following asynchronous tasks for which I am using a FutureBuilder -

  1. If a user had signed in to the app previously, I retrieve their authentication again using GoogleSignIn.signInSilently()
  2. If the silent sign in was successful, I retrieve the saved Google Sheet stored using SharedPreferences

After these tasks complete, I show users the homepage, and while they are running, I show them a splash screen.

However, the Future I have written never seems to complete and I keep seeing my splash screen.

This is my future -

Future<Map<String, dynamic>> initializeAuth() async {
  Map<String, dynamic> data = {};
  GoogleSignInAccount? previousUser = await googleSignIn.signInSilently();
  final prefs = await SharedPreferences.getInstance();
  String? spreadsheetId = prefs.getString('spreadsheetId');
  String? spreadsheetName = prefs.getString('spreadsheetName');
  data['user'] = previousUser;
  data['spreadsheetId'] = spreadsheetId;
  data['spreadsheetName'] = spreadsheetName;
  return data;
}

This is my main.dart -

class _MyAppState extends State<MyApp> {
  Future<Map<String, dynamic>>? _previousAuth;

  void initState() {
    super.initState();
    _previousAuth = initializeAuth();
  }

  Widget build(BuildContext context) {
    return MaterialApp(
      home: FutureBuilder(
        future: _previousAuth,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            if (snapshot.data.previousUser != null) {
              return HomePage();
            }
            return LoginPage();
          }
          else {
            return SplashScreen();
          }
        }
    );
  }
}

I tried printing the snapshot.connectionState, and it is ConnectionState.none, and snapshot.hasData is always false and snapshot.data is always null. I keep seeing my splash screen, and I never get the previous authentication data. How can I make the Future complete?

Upvotes: 0

Views: 50

Answers (0)

Related Questions