I am trying to make dynamic ListView.builder in FutureBuilder widget but can't get lenght of list which comes from AsyncSnapshot snapshot. I've tried itemCount: snapshot.data.lenght
but it did not work. Here is my code
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();
}),
),
);
}
}
Data comes from class 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))),
);
}
And quotes storage class used to build future:
class QuoteStorage {
// ...
// ...
Future<Quotes> getQuotes() async {
final file = await _localFile;
final contents = await file.readAsString();
return Quotes.fromJson(contents);
}
}
App is crashing if I don't provide itemCount which is dynamic (fetch from url). Any ideas?
You are getting the error because you spelt length
wrong.
You can fix this by correcting the spelling of length
.
Replace your FlutterDemo
class with the code below
It works perfectly fine.
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();
}),
),
);
}
}
I hope this helps.