美文网首页
Flutter中shared_preferences同步使用

Flutter中shared_preferences同步使用

作者: 溪桥星雨 | 来源:发表于2020-10-28 13:32 被阅读0次
preferences = await SharedPreferences.getInstance();

这个preferences 是异步获取到的,而我需要在其他地方使用。所以,百度了很多办法都没有找到比较好的办法。最后只能想到了在启动的时候,首先获取,再执行其他程序并使用。
首先,我们将preferences 封装在一个工具类里

  static SharedPreferences preferences;

  static Future<void> getSharedPreferences() async {
    if(preferences == null){
      preferences = await SharedPreferences.getInstance();
    }else {
      return;
    }
}

然后,在根视图的init里执行初始化

  @override
  void initState() {
    Utils.initialize();
    futureUtils = Utils.getSharedPreferences();
    super.initState();
  }

最后,在根视图的视图创建里放上FutureBuilder,【数据加载中……】这个视图可以替换为开机启动图,这样比较好

@override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future:futureUtils,
      builder: (BuildContext context, AsyncSnapshot snapshot){
        if (snapshot.connectionState == ConnectionState.done) {
          return Scaffold(
            body: IndexedStack(
                index: _currentIndex,
                children: [HomePageView(), AboutMeView()]),
            bottomNavigationBar: BottomNavigationBar(
              currentIndex: _currentIndex,
              selectedFontSize: 14,
              unselectedFontSize: 14,
              items: items,
              onTap: (index){
                setState(() {
                  _currentIndex = index;
                });
              },
            ),
          );
        }else{
          return Container(
            color: Colors.white,
            child: Center(
              child: Text("数据加载中……",style: TextStyle(fontSize: 20, color: Colors.orange)),
            ),
          );
        }
      },
    );

最后,使用shared_preferences的时候,就可以直接获取或者保存了

Utils.preferences.getString("data");
Utils.preferences.setString("data", "str");

希望能给大家提供一点帮助。如果iOS开发或者flutter开发的私活,可以联系我。

相关文章

网友评论

      本文标题:Flutter中shared_preferences同步使用

      本文链接:https://www.haomeiwen.com/subject/kpiqvktx.html