我试图在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();
}),
),
);
}
}
数据来自类引号:
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(从网址获取),则应用程序将崩溃。 有什么想法吗?
答案 0 :(得分:1)
由于拼写错误length
而导致错误。
您可以通过更正length
的拼写来解决此问题。
将您的FlutterDemo
类替换为下面的代码
效果很好。
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(
// current the spelling of length here
itemCount: snapshot.data.length,
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();
}),
),
);
}
}
我希望这会有所帮助。