【发布时间】:2020-08-25 13:20:47
【问题描述】:
我正在尝试在 FutureBuilder 小部件中制作动态 ListView.builder,但无法获得来自 AsyncSnapshot 快照的列表长度。我试过itemCount: snapshot.data.lenght 但没有用。这是我的代码
class FlutterDemo extends StatelessWidget {
final QuoteStorage storage;
FlutterDemo({Key key, @required this.storage}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Scrapy on flutter')),
body: Center(
child: FutureBuilder(
future: storage.getQuotes(),
builder: (context, AsyncSnapshot<Quotes> snapshot) {
return snapshot.hasData ? ListView.builder(
itemCount: snapshot.data.lenght,
itemBuilder: (context, index) {
final quotes = snapshot.data;
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(quotes.items[index].quote),
));
},
)
: const CircularProgressIndicator();
}),
),
);
}
}
数据来自 Quotes 类:
class Quotes extends Items {
@override
final List<Quote> items;
Quotes({
this.items,
});
factory Quotes.fromJson(String str) => Quotes.fromMap(json.decode(str));
factory Quotes.fromMap(Map<String, dynamic> json) => Quotes(
items: json["items"] == null
? null
: List<Quote>.from(json["items"].map((x) => Quote.fromMap(x))),
);
}
并引用用于构建未来的存储类:
class QuoteStorage {
// ...
// ...
Future<Quotes> getQuotes() async {
final file = await _localFile;
final contents = await file.readAsString();
return Quotes.fromJson(contents);
}
}
如果我不提供动态的 itemCount(从 url 获取),应用程序就会崩溃。 有什么想法吗?
【问题讨论】: