UserService.dart:
class UserSevices{
static getUserInfo() async{
List userInfo;
try{
List userInfoData = json.decode(await Storage.getString('userInfo'));
print('用户信息: $userInfoData');
userInfo = userInfoData;
}catch(e){
print(e);
userInfo = [];
}
return userInfo;
}
static getUserLoginState() async{
var userInfo = await UserServices.getUserInfo();
if(userInfo.length > 0 && userInfo[0]['username'] == ''){
return true;
}
return false;
}
}
login.dart
var res = await Dio().post(api, data: formData);
Map<String, dynamic> resData = jsonDecode(res.toString());
if(resData['code'] == 200){
// 登录成功后将接口返回的数据存储到本地
Storage.setString('userInfo', '123');
Navigator.pop(context);
}else{
Fluttertoast.showToast(
msg: '${resData["message"]}',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER
);
}
User.dart
bool isLogin = false;
List userInfo = [];
@override
void initState(){
super.initState();
this._getUserInfo();
// 监听登录
eventBus.on<UserEvent>().listen((event){
print(event.str);
this._getUserInfo();
});
}
_getUserInfo() async{
var isLogin = await UserServices.getUserLoginState();
var userInfo = await UserServices.getUserInfo();
if(mounted){
setState(() {
this.userInfo = userInfo;
this.isLogin = isLogin;
});
}
}
storage.dart
class Storage{
static Future<void> setString(key, value) async{
SharedPreferences sp = await SharedPreferences.getInstance();
sp.setString(key, value);
}
static Future<String> getString(key) async{
SharedPreferences sp = await SharedPreferences.getInstance();
sp.getString(key);
}
}
进入用户中心的时候从本地获取用户信息.
我试着在登录成功的时候将数据存储的本地, 但是回到用户中心获取本地数据的时候发现程序走进了catch(e),然后控制台输出了下面的错:
不知道为什么没存到本地?
经过长时间调试发现接口返回的类型是Map类型, 而我上面声明的是List导致获取不到