I am trying to use snackbar on my future builder to shows error.So after making my future method instance on initState method:
Future<DetailModel> futureDetail;
...
@override
void initState() {
futureDetail =
DetailProvider().detailProvider(widget.id);
super.initState();
}
In futureBuilder i use like below:
Center(
child: SingleChildScrollView(
child: FutureBuilder(
future: futureDetail,
builder:
(context, AsyncSnapshot<DetailProductModel> snapshot) {
if (!snapshot.hasError ||
snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
if (snapshot.hasData && snapshot.data.data != null) {
return Container();
}
if (snapshot.hasError &&
snapshot.error != null &&
snapshot.data == null) {
WidgetsBinding.instance.addPostFrameCallback((_) =>
showSnackbar(snapshot.error.toString(), context));
return Container();
} else {
return Center(
child: Text('failed to load'),
);
}
},
),
),
),
detailProvider
method calls http service and in my example i throw SocketException
to get error on builder and show snackbar.
I know future builder is for showing a widget per state but i want to show snakbar.
But builder is called twice and snackbar shows twice an error?
I checked that this three conditions are the same snapshot.hasError and snapshot.error != null and snapshot.data == null
in twice build . How could i prevent showing twice snakbar?
print(snapshot);
as the first line in your builder? – pskink