這是我在 Swift/Android 之后第一次嘗試 Flutter 應用程式,并且在應用程式首次運行時無法獲取資料以顯示。
在我的串列螢屏中,我使用 GroupedListView 構建了一個串列,如果我將本地 json 檔案加載為資料源,一切正常,但如果我從 Hive 中提取完全相同的資料,則串列在第一次運行時顯示為空,僅在之后顯示熱重啟。看不到我哪里出錯了。在下面的代碼中 readJson() 有效,但 getData() 無效。
class venueList extends StatefulWidget {
const venueList({Key? key}) : super(key: key);
@override
State<venueList> createState() => _venueList();
}
class _venueList extends State<venueList> {
List<Venue> _venues = [];
@override
void initState() {
super.initState();
//readJson();
getData();
}
// This works
// Future<void> readJson() async {
// final String response = await rootBundle.loadString('assets/venues.json');
// final data = await json.decode(response);
// setState(() {
// _venues = data["items"];
// });
// }
// This doesn't
Future<void> getData() async {
final venueBox = await Hive.openBox('venuesBox');
setState(() {
_venues = List<Venue>.from(venuesBox.values.toList());
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: GroupedListView<Venue, String>(
elements: _venues,
groupBy: (Venue v) => v.venueGroup,
groupComparator: (value1, value2) => value2.compareTo(value1),
order: GroupedListOrder.DESC,
useStickyGroupSeparators: true,
separator: Divider(
height: 1.0,
color: Colors.grey,
),
groupSeparatorBuilder: (String value) => Padding(
padding: const EdgeInsets.all(0.0),
child: Container(
padding: const EdgeInsets.fromLTRB(10.0, 15.0, 10.0, 15.0),
color: kMidBlueColour,
child: Text(
value.toUpperCase(),
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 26,
fontWeight: FontWeight.normal,
fontFamily: 'SanFranciscoDisplay',
color: Colors.white),
),
),
),
itemBuilder: (c, Venue v) {
return ListTile(
contentPadding:
const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
leading: Hero(
tag: v.venueName,
child: Container(
child: Image.asset(
'images/venue1440/' v.venueImage,
fit: BoxFit.contain,
),
),
),
title: Text(
v.venueTitle.toString().toUpperCase(),
style: TextStyle(
color: kMidBlueColour,
fontFamily: 'SanFranciscoDisplay',
fontSize: 20.0,
),
),
subtitle: Text(
v.venueAddress,
style: TextStyle(
color: Color(0xFF4A4A49),
fontFamily: 'SanFranciscoDisplay',
fontSize: 18.0,
),
),
trailing: const Icon(
Icons.circle,
color: Colors.grey,
size: 50.0,
),
visualDensity: const VisualDensity(horizontal: 4, vertical: 0),
onTap: () {
},
);
},
),
);
}
}
uj5u.com熱心網友回復:
您必須使用 FutureBuilder。參考這篇文章。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/495047.html
上一篇:_MapStream<QuerySnapshot<Map<String,dynamic>>,List<UserModel>?>引發例外
