如何在 dart 中使用没有异步方法的共享首选项?

How to use shared preferences without an async method in dart?

我想在 flutter 容器的子项中显示文本,但首先我必须使用共享首选项来获取我的值,我尝试在不同的函数中使用 sharedpreference 但它显示错误并显示 Future 不能分配给 Widget。我该如何解决?

 Container(
               child: _show(),
              height: 40,
              width: MediaQuery.of(context).size.width - 230,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
                boxShadow: [
                  BoxShadow(
                      color: Colors.black26,
                      blurRadius: 6,
                      offset: Offset(0, 2)),
                ],
              ),
            ),

我有其他功能:

_show() async {
  final prefs = await SharedPreferences.getInstance();
  var myVar= prefs.getInt('key');
  
  return myVar;

}

为了在您的小部件中使用 async 方法,您必须使用 Future Builder,这只会让您的应用“暂停”,直到您的数据到达。

你可以这样使用它:

 Container(
              child: FutureBuilder(
              future: _show(),
              builder: (context, snapshot) { // snapshot is just the data returned from the method, to access it's data you use .data  
                if (snapshot.hasData) { // this is for null safety, since you are accessing saved data the first time you use your app you might not have anything stored, which returns null
                  return Container(Text(snapshot.data.toString())) // here I just return a simple Text widget with data
                }
                else { 
                  return Container();
                }
              }
          );,
              height: 40,
              width: MediaQuery.of(context).size.width - 230,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
                boxShadow: [
                  BoxShadow(
                      color: Colors.black26,
                      blurRadius: 6,
                      offset: Offset(0, 2)),
                ],
              ),
            ),