I am using FutureBuilder to show values from Database in GUI. The problem is that I am getting a null error before the values are shown. I tried to solve this with calling the ConnectionState but its not working.
Here is my code so far:
return FutureBuilder<TerminList>(
future: mainTermine,
builder: (context, snapshot) {
print(snapshot.data.termine[0].postTitle);
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('No Connection');
case ConnectionState.active:
case ConnectionState.waiting:
return AppProgressIndicator();
case ConnectionState.done:
return ListView.builder(
itemCount: snapshot.data.termine.length,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return Container(
margin: EdgeInsets.all(10),
decoration: BoxDecoration(),
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
elevation: 5,
color: Colors.white,
child: GroovinExpansionTile(
boxDecoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
),
backgroundColor: Colors.white,
leading: Text(
snapshot.data.termine[index].metaValue,
style: TextStyles.placeholder,
),
title: Text(
snapshot.data.termine[index].postTitle,
style: TextStyles.body,
),
children: [
Column(
children: [
Padding(
padding: EdgeInsets.all(10),
child: AppDivider(),
),
],
)
],
),
),
);
});
return null;
default:
return Text('none');
}
});
CodePudding user response:
First of all, you don't need below lines, because by using switch-case, you have covered all scenarios.
return null;
default:
return Text('none');
and remove the below line, because you trying to get data before the future processes finishes.
print(snapshot.data.termine[0].postTitle);
CodePudding user response:
I would use snapshot.hasError
and snapshot.hasData
instead of snapshot.connectionState
. It could look something like this. (Not sure if I got all the brackets right.)
return FutureBuilder<TerminList>(
future: mainTermine,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text('error while fetching data');
}
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.termine.length,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return Container(
margin: EdgeInsets.all(10),
decoration: BoxDecoration(),
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
elevation: 5,
color: Colors.white,
child: GroovinExpansionTile(
boxDecoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
),
backgroundColor: Colors.white,
leading: Text(
snapshot.data.termine[index].metaValue,
style: TextStyles.placeholder,
),
title: Text(
snapshot.data.termine[index].postTitle,
style: TextStyles.body,
),
children: [
Column(
children: [
Padding(
padding: EdgeInsets.all(10),
child: AppDivider(),
),
],
)
],
),
),
);
}
);
}
return AppProgressIndicator();
}
);