首页 > 解决方案 > 如何在颤动的文本小部件中显示 SharedPreferences 值?

问题描述

任务是从 SharedPrefrences 中获取值并将其显示在 Text 小部件中。

这里我尝试将值存储在变量_userCurrency 中并在ListTile 中显示。问题似乎是 ListTile 以“null”值快速加载。

甚至 getUserCurrencySymbol() 也没有返回任何值。我已经尝试过 return MySharedPreferences.instance.getUserCurrencyValue('userCurrency'); 和其他可能的解决方案。

菜单.dart

late String _userCurrency;
getUserCurrencySymbol().then((value) {_userCurrency = value.toString();});

return StatefulBuilder(
    builder: (BuildContext context, void Function(void Function()) setState) {
      return ListView(
        children: [
          ListTile(title: Text(_userCurrency)),
        ]
      ) //ListView
    },
); //Stateful builder
          

控制器.dart

Future<String> getUserCurrencySymbol() async {
   return MySharedPreferences.instance.getUserCurrencyValue('userCurrency').then((value) {return value.toString();});
}


class MySharedPreferences {
  MySharedPreferences._privateConstructor();

  static final MySharedPreferences instance = MySharedPreferences._privateConstructor();

  setUserCurrencyValue(String key, String value) async {
    SharedPreferences instance = await SharedPreferences.getInstance();
    instance.setString(key, value);
  }

  getUserCurrencyValue(String key) async {
    SharedPreferences instance = await SharedPreferences.getInstance();
    return instance.getString(key) ?? "Bitcoin";
  }

标签: flutterdart

解决方案


您可以使用FutureBuilder加载数据并处理加载/错误状态

FutureBuilder<String>(
    future: getUserCurrencySymbol(),
    builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
        if(snapshot.hasError) {
            //fixme just to check an error
            print("Error: ${snapshot.error}");
            return Text("Error");//or what you want
        }

        if (!snapshot.hasData) {
            return CircularProgressIndicator();//or what you want
        }
   
        return ListView(
        children: [
          ListTile(title: Text(snapshot.data)),
        ]
        );
    },
)

并尝试更改 getUserCurrencySymbol();

Future<String> getUserCurrencySymbol() {
   return MySharedPreferences.instance.getUserCurrencyValue('userCurrency');
}

推荐阅读