首页 > 解决方案 > 颤动中的共享首选项实例空错误

问题描述

在我的班级的 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 请提出任何解决此错误的方法。

标签: fluttersharedpreferences

解决方案


     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())
        
          }
    
    }

推荐阅读