http - 从 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>'
有时生成了令牌,在某些情况下未生成令牌并显示错误消息
解决方案
是的,您只是在创建一个共享偏好的实例,而不是向其中插入价值。只需添加_prefs.setString('BearerToken', token);
推荐阅读
- laravel - Jenkins 流水线 - Laravel 单元测试
- youtube-api - 用于 MP4 网址的 YouTube API
- c - 使用函数初始化结构会产生编译器错误
- wpf - 为什么此 DropdownMenu 在 WPF 中不起作用
- html - 将 div 粘贴到另一个 div 的边界,以便它们在调整大小时保持在一起
- c - 在内存块之前而不是之后在 C 中使用 realloc 添加空间
- javascript - caret-equals ^= 运算符有什么作用?
- regex - 什么是匹配行的 grep 模式?
- javascript - 设置函数默认值
- javascript - 设置值后如何从 Kendo UI MultiColumnComboBox 中获取选定的数据项?