我想在 flutter 中的容器的子項中顯示文本,但首先我必須使用共享首選項來獲取我的值,我嘗試在不同的函式中使用 sharedprefernce 但它顯示錯誤并說Future cant be分配給 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;
}
uj5u.com熱心網友回復:
為了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)),
],
),
),
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/325193.html
