简体   繁体   中英

Flutter: What is the Correct approach to get value from Future?

I have a function that which returns user token, and saves it to shared preference, if token is present it saves it to SP. Another method awaits for the token and if token is present authenticates user Here is my code

login(username, password) async {
  final String url = "http://10.0.2.2:8080/api/auth/signin"; // iOS
  final http.Response response = await http.post(
    url,
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'username': username,
      'password': password,
    }),
  );
  LoginModel userSave = loginModelFromJson(response.body);

  print(response.body);
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  bool result = await prefs.setString('user', jsonEncode(userSave));
  print(result);
}

This piece of code works as expected, but I'm having issue getting the token value from Future. Case Scenario: User enters username and password and authenticates with server. Incase account exists a token is generated from server and sent to app and stored in shared prefs. token if available is picked from shared prefs and used to login to app, but the check of the token is done before it is generated and saved

Future<LoginModel> getUserInfo() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();

    Map<String, dynamic> userMap;
    final String userStr = prefs.getString('user');
    if (userStr != null) {
      userMap = jsonDecode(userStr) as Map<String, dynamic>;
    }

    if (userMap != null) {
      final LoginModel user = LoginModel.fromJson(userMap);
      print(user);
      return user;
    }
    return null;
  }

the token gets called way before it is saved throwing an error of null

RoundedButton(
                text: "LOGIN",
                press: () async {
                  if (_formKey.currentState.validate()) {
                    progressDialog.show();
                    await login(
                      username,
                      password,
                    );
                    SharedPreferences prefs =
                    await SharedPreferences.getInstance();
                    String token = prefs.getString("accessToken");
                    getUserInfo();

                    // ignore: null_aware_in_condition
                    if (token == null) {
                      progressDialog.hide();
                      showAlertsDialog(context);
                      // ignore: null_aware_in_condition
                    } else {
                      progressDialog.hide();
                      showAlertzDialog(context);
                    }
                  }
                },
              ),

I believe there is very small logical mistake, but unable to find it myself.

I believe you cannot directly call jsonEncode with a custom object like the way you do it in jsonEncode(userSave) . Do print(jsonEncode(userSave)); to see if the value is properly being converted into a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM