flutter - 颤动中的共享首选项实例空错误
问题描述
在我的班级的 initstate 中,我正在尝试实例化 Shared 首选项,但似乎它没有这样做,因为在运行时,它返回错误
The method 'getString' was called on null.
Receiver: null
Tried calling: getString("name")
其中“名称”是关键之一。我无法理解如何启动和获取共享首选项的正确实例,因为在构建课程之前我必须拥有它。而且我也不想在这么小的事情上使用 FutureBuilder。
class _ProfilePageState extends State<ProfilePage> {
SharedPreferences prof;
@override
initState() {
super.initState();
SharedPreferences.getInstance().then((SharedPreferences sp) => prof = sp);
setState(() {});
}
...........
............
Widget build(BuildContext context) {
...........
................
MyListItem(
icons: Icons.alternate_email,
title: "username",
subtitle: prof.getString('name'), // This is where it is showing error
),
........
}
}
这里显示 prof 为 null 请提出任何解决此错误的方法。
解决方案
class _ProfilePageState extends State<ProfilePage> {
SharedPreferences prof;
bool isPreferenceLoaded = false; // to check if the PreferenceLoaded
@override
initState() {
super.initState();
SharedPreferences.getInstance().then((SharedPreferences sp){
prof = sp; isPreferenceLoaded = true;
});
setState(() {});
}
...........
............
Widget build(BuildContext context) {
//ifLoaded return you widget
isPreferenceLoaded ?
...........
................
MyListItem(
icons: Icons.alternate_email,
title: "username",
subtitle: prof.getString('name'), // This is where it is showing error
),
........
:
Center(child: CircularProgressIndicator())
}
}
推荐阅读
- data-warehouse - 如何将透视列结构转换为维度表
- r - 从 readr::read_csv 中读取的数据中删除属性
- kubernetes - 是否有可能,如果总是失败,如何限制 kubernetes 作业以创建最大数量的 pod?
- javascript - 如何在 R 中的 networkD3 图中悬停时删除淡入淡出
- angular - Angular 7对自定义数据源进行排序
- ubuntu - 无法使用 ssh 从 gitlab 克隆
- sql - 在 SQL 中找出字符串位置(列)
- java - JButtons Overlap Components When Hovered On
- pandas - rolling_corr 返回值 > 1
- javascript - 使用 AngularJS 发送带有附件的邮件时出现问题