-1

I have been struggling with this problem for like two days. My social media app should save its state, when signed in so that when you leave the app and come back again it should start from the home page, not the sign in page. I have found that it is possible to do this with StreamBuilder and FutureBuilder. I have tried some things with FutureBuilder and I have some errors.

Below is how my main page looks like:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (BuildContext context) => UserData(),
      child: MaterialApp(
        title: 'Curtain App',
        debugShowCheckedModeBanner: false,
        home: FutureBuilder(          
          future: SharedPreferencesHelper.getPrefs(),
          builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return CircularProgressIndicator();
            }
            
            if (snapshot.hasData) {
              Provider.of<UserData>(context).currentUserId =
                  snapshot.data.token;
              return HomeScreen();
            } else {
              return LoginScreen();
            }
          },
        ),
      ),
    );
  }
}

class SharedPreferencesHelper {
  static final String _tokenCode = "token";

  static Future<String> getPrefs() async {
    final SharedPreferences preferences = await SharedPreferences.getInstance();

    return preferences.getString(_tokenCode) ?? "empty";
  }
}

And this is my LoginPage submit btn code:

 _submit() async {
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save();
      // logging in the user w/ Firebase
      //AuthService.login(_email, _password);

      var user = await DatabaseService.loginUser(_username, _password);
      final data = json.decode(user);

      SharedPreferences sharedPreferences =
          await SharedPreferences.getInstance();

      print("Hi ${data['username']}");
      print("Status ${data['status']}");
      print("Token ${data['token']}");

      if (data['username'] != null) {
        setState(() {
          _message = "Hi ${data['username']}";
          sharedPreferences.setString('token', data['token']);
        });
        Navigator.of(context).pushAndRemoveUntil(
            CupertinoPageRoute(
              builder: (context) => HomeScreen(),
            ),
            (Route<dynamic> route) => false);
      }
    }
  }

Any ideas on how to solve this ?

Davrick
  • 301
  • 1
  • 4
  • 13

1 Answers1

1

Just remove the .token from the line where the error occurs. snapshot.data already is the token.

nvoigt
  • 75,013
  • 26
  • 93
  • 142