我遇到了這個奇怪的問題,除非我在 VScode(熱多載)中點擊 ctrl s,否則應用程式不會加載頁面內容。
以下代碼從資料庫中獲取情緒名稱串列并將它們加載到螢屏上。
class EmotionListView extends StatefulWidget {
const EmotionListView({Key? key}) : super(key: key);
@override
_EmotionListViewState createState() => _EmotionListViewState();
}
class _EmotionListViewState extends State<EmotionListView> {
List<String> emotionNames = [];
@override
void initState() {
getPrimaries().then((value) => value.forEach((element) {
emotionNames.add(element.name);
}));
super.initState();
}
@override
Widget build(BuildContext context) {
ListTile makeListTile(String emotion) => ListTile(
contentPadding:
const EdgeInsets.symmetric(horizontal: 20.0, vertical: 15.0),
title: Text(
emotion,
style: const TextStyle(
color: Colors.white, fontWeight: FontWeight.bold),
),
trailing: const Icon(Icons.keyboard_arrow_right,
color: Colors.white, size: 30.0),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: ((context) => PhraseListView(emotion: emotion))),
);
},
);
Card makeCard(String emotion) => Card(
elevation: 8.0,
margin: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 6.0),
child: Container(
decoration:
const BoxDecoration(color: Color.fromRGBO(64, 75, 96, .9)),
child: makeListTile(emotion),
),
);
final makeBody = Container(
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: emotionNames.length,
itemBuilder: (BuildContext context, int index) {
return makeCard(emotionNames[index]);
},
),
);
return Scaffold(
appBar: AppBar(
backgroundColor: const Color.fromRGBO(58, 66, 86, 1.0),
title: const Text('Emotions'),
),
body: makeBody,
);
}
}
這是我點擊 ctrl s 之前和之后

我猜這是因為我沒有使用 setState()。如果 setState() 是原因,我不確定如何使用它以及為什么要在這里使用它。
uj5u.com熱心網友回復:
您需要使用的猜測setState是正確的。需要的原因setState是從資料庫收集資料需要時間,在這段時間內,頁面的其余部分會呈現。當您實際收到資料時,您需要通知重新呈現新資料。
您可以通過添加fetchEmotionData如下所示的函式來實作這一點。
@override
void initState() {
fetchEmotionData(); //Takes time to grab data and will leave your page empty
super.initState();
}
Future fetchEmotionData() async {
await getPrimaries().then((value) => value.forEach((element) {
emotionNames.add(element.name);
}));
setState(() {});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/442447.html
上一篇:雙打圓名單
下一篇:限制按鈕寬度
