I am new to Flutter and REST API, so take it easy on me. My app is supposed to save its state according to YouTube videos that I have learnt. However, when I login and exit the app, the next time I open the app it doesn't start from a HomePage, it starts from a Login page. It is supposed to save user's state and start from HomePage if the user didn't logout the previous time.

Here is my code for the main page:

void main() => runApp(MyApp());

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: AuthService.getToken(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return CircularProgressIndicator();
            }
            if (snapshot.hasData) {
              Provider.of<UserData>(context).currentUserId = snapshot.data.uid;
              return HomeScreen();
            } else {
              return LoginScreen();
            }
          },
        ),
      ),
    );
  }
}

And this is the code where I used Session to save state:

static setToken(String token, String refreshToken) async {
    _AuthData data = _AuthData(token, refreshToken);
    await SESSION.set('tokens', data);
  }

  static Future<String> getToken() async {
    return await SESSION.get('tokens');
  }

  static removeToken() async {
    await SESSION.prefs.clear();
  }
class _AuthData {
  String token, refreshToken;
  _AuthData(this.token, this.refreshToken);

  // toJson
  // required by Session lib
  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = Map<String, dynamic>();

    data['token'] = token;
    data['refreshToken'] = refreshToken;

    return data;
  }

Lastly, this is my login page logic:

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

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


      if (data['username'] != null) {
        AuthService.setToken(data['token'], data['refreshToken']);
        Navigator.push(//code);
      }

If you have any ideas on how to fix it, please let me know. Peace...

1

There are 1 best solutions below

7
On

you have to check that your user id must not null.

if (snapshot.hasData) {
  Provider.of<UserData>(context).currentUserId =snapshot.data.uid;
  if(snapshot.data.uid!=null){
    return HomeScreen();
  } else {
    return LoginScreen();
  }
}