如何解决如何修复Shared Preferences在Flutter中返回空字符串?
我正在使用共享的首选项在Flutter中存储和加载地图的值,但出现错误
The following assertion was thrown building UserPro(dirty):
A non-null String must be provided to a Text widget.
'package:Flutter/src/widgets/text.dart':
Failed assertion: line 360 pos 10: 'data != null'
我当然知道 Shared Preferences返回一个空字符串值,但是我不知道为什么,因为我正在等待该值。以及如何解决。我附有此问题的代码供您参考
----存储------
void setUserValues() async{
SharedPreferences sharedPrefs = await SharedPreferences.getInstance();
currentUser.forEach((k,v)=>sharedPrefs.setString(k,v));
}
此处 currentUser 包含包含用户数据(例如“名称”,“电子邮件”等)的地图。
----加载------
import 'package:Flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
SharedPreferences localStorage;
class UserPro extends StatelessWidget{
final currentUser;
String name;
UserPro({this.currentUser}){
name=localStorage.getString("Name");;
}
static Future init() async{
localStorage = await SharedPreferences.getInstance();
}
@override
Widget build(BuildContext context) {
// Todo: implement build
return Scaffold(
body: Center(
child: Text(
name,style: TextStyle(
fontSize: 15,fontFamily: 'Berlin Sans FB',fontWeight: FontWeight.bold,),);
}
}
解决方法
使用FutureBuilder
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
//SharedPreferences localStorage;
class UserPro extends StatelessWidget{
final currentUser;
//String name;
UserPro({this.currentUser});
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
body: Center(
child: FutureBuilder<SharedPreferences>(
future: SharedPreferences.getInstance(),builder: (context,snapshot){
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
return Text(
snapshot.data.getString("name"),style: TextStyle(
fontSize: 15,fontFamily: 'Berlin Sans FB',fontWeight: FontWeight.bold,),},);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。