首页 > 解决方案 > 从 sharedpreferences 调用令牌时的相位问题

问题描述

我有一个用于生成令牌的 url,我生成了令牌并使用共享首选项保存了令牌。但是当我在标题中调用令牌时,有时令牌没有生成或没有到达标题

    Future<Map<String, dynamic>> fetchPost0(String url, Map formData) async {
    print('feg');

    Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

    final SharedPreferences prefs = await _prefs;

    print("PRINT ====> " + prefs.getString("BearerToken"));

    var receivedToken = "Bearer " + prefs.getString("BearerToken");

    print("PRINT ::: receivedToken ====> "+receivedToken);

    print("formData  ==> "+ json.encode(formData));

    return http.post(
      'http://base url/index.php?route=rest/login/login', body: json.encode(formData)
      ,
      headers: {
        'Authorization': receivedToken

      },
    ).then((http.Response response){
      final int statusCode = response.statusCode;
      if (statusCode < 200 || statusCode > 400 || json == null) {
        throw new Exception("Error while fetching data");
      }
      print("Result: ${response.body}");
     // return Login.fromJson(json.decode(response.body));
      return json.decode(response.body);
    });

  }




 Future<Map<String, dynamic>> fetchPost() async {
  print('feg');
  final response = await http.post(
    'http://base url/index.php?route=feed/rest_api/gettoken&grant_type=client_credentials',
    headers: {HttpHeaders.authorizationHeader: "Basic token"},
  );
  final responseJson = json.decode(response.body);
  print("Result: ${response.body}");
  SharedPreferences prefs = await SharedPreferences.getInstance();
  //now set the token inside the shared_preferences
  //I assumed that the token is a field in the json response, but check it before!!
  await prefs.setString('token',responseJson['token']);
  //return Post.fromJson(responseJson);
  return responseJson;
}

这些是控制台中的错误消息

 [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: Invalid argument(s)
    E/flutter ( 1406): #0      _StringBase.+ (dart:core-patch/string_patch.dart:260:57)
type 'Future<dynamic>' is not a subtype of type 'Future<Widget>'

有时生成了令牌,在某些情况下未生成令牌并显示错误消息

标签: httpfluttersharedpreferences

解决方案


是的,您只是在创建一个共享偏好的实例,而不是向其中插入价值。只需添加_prefs.setString('BearerToken', token);


推荐阅读