Reputation: 568
I am getting error the snapshot data length is on null to handle this I have added condition but still showing error when I try to navigate to another page here is my code
Scaffold(
key: _scaffoldKey,
drawer: new Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: [
appBar: new AppBar(
backgroundColor: Colors.white,
elevation: 1,
title: new Text("FindTheRecipe"),
actions: [
new IconButton(
icon: Icon(Icons.search),
onPressed: () async {
Navigator.push(
context, MaterialPageRoute(builder: (context) => sample()));
})
],
),
Next page
import 'package:flutter/material.dart';
import 'package:find_recipe/responses.dart';
class sample extends StatefulWidget {
@override
_sampleState createState() => _sampleState();
}
class _sampleState extends State<sample> {
Future _future;
@override
void initState() {
_future = mylist();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(),
body: FutureBuilder(
future: _future,
builder: (context, snashot) {
return ListView.builder(
itemCount: snashot.data.length,
itemBuilder: (BuildContext context, int index) {
if (snashot.data.length == null) {
return CircularProgressIndicator();
} else {
return Text("asdasd");
}
},
);
},
),
);
}
}
I have added condition but why it is showing error please help me. It showing error instead of CircularProgressIndicator()
Upvotes: 0
Views: 46
Reputation: 2295
Async Snapshots require time to load. They have properties like .hasData and .hasError which can be checked to return Appropriate widgets. snapshot.data is null until snapshot.hasData is true and it means the data is still being loaded. So basically, you are calling snapshot.data.length when snapshot.data is null which causes the error.
To fix it, check these two things before using the snapshot:
if(!snapshot.hasData) { return LoadingWidget(); } // Loading widget is a widget you want to show while the data is being loaded. For example, a CircularProgressIndicator
if(snapshot.hasError) { return ErrorWidget(); } // Error widget can be anything you want to show if an error occurs while loading the data. You can return something like Text("Error");
Then return the normal stuff
return ListView.builder(....); // Rest of the code
Upvotes: 1