首页 > 解决方案 > 在我的文本中像变量一样使用 sharedPreferences

问题描述

如何在我的Text小部件中使用 sharedPreferences 数据?

节省SP:

sharedPreferences.setString("firstName", jsonResponse['firstName']);
sharedPreferences.setString("lastName", jsonResponse['lastName']);

阅读SP:

  getUserDetails(String key) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    final firstName = sharedPreferences.getString('firstName') ?? '';
    final lastName = sharedPreferences.getString('lastName') ?? '';
    print(firstName);
    print(lastName);
  }

但是如何使用我的firstNamelastName喜欢的文本变量?

我以这种方式尝试:

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Code Land", style: TextStyle(color: Colors.white)),
        actions: <Widget>[
          FlatButton(
            onPressed: () {
              sharedPreferences.clear();
              // sharedPreferences.commit();
              Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context) => LoginPage()), (Route<dynamic> route) => false);
            },
            child: Text("Log Out", style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
      body: Center(child: Text(getUserDetails('firstName'))), <=== HERE
      drawer: Drawer(),
    );
  }

标签: flutterdart

解决方案


您实际上不能直接这样做,因为 sharedPreferences 实例需要awaited用于。但是有一个使用该小部件调用的FutureBuilder小部件,您可以执行以下操作:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<SharedPreferences>(
      future: SharedPreferences.getInstance(),
      builder: (context, snapshot) {
        if (!snapshot.hasData)
          return Scaffold(
            body: CircularProgressIndicator(),
          ); //Just some placeholder loading widget
        return Scaffold(
          appBar: AppBar(
            title: Text("Code Land", style: TextStyle(color: Colors.white)),
            actions: <Widget>[
              FlatButton(
                onPressed: () {
                  snapshot.data.clear(); //Note instead of sharedPreferences we now use snapshot.data
                  Navigator.of(context).pushAndRemoveUntil(
                      MaterialPageRoute(
                          builder: (BuildContext context) => LoginPage()),
                      (Route<dynamic> route) => false);
                },
                child: Text("Log Out", style: TextStyle(color: Colors.white)),
              ),
            ],
          ),
          body: Center(child: Text(getUserDetails('firstName', snapshot.data))), 
//Here you just pass the already loaded sharedPreferences to your method and make the method return your result immediately instead of a Future 
          drawer: Drawer(),
        );
      },
    );
  }
}

我希望这回答了你的问题。


推荐阅读