颤振中的共享首选项实例空错误

时间:2021-05-04 14:06:49

标签: flutter sharedpreferences

在我的班级的 initstate 中,我试图实例化共享首选项,但似乎没有这样做,因为在运行时,它返回错误

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 为空 请提出任何解决此错误的方法。

1 个答案:

答案 0 :(得分:0)

     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())
        
          }
    
    }
相关问题