For this kind of purposes you could use a BLoC pattern, that divide an ui layer and domain layer (communication with server), you can read more on official documentation of bloc library: Bloc library
It might be complicated to a novice in flutter, so, in your case, you can also implement state managment inside a single widget by your own.
- Define stream and subscribe to it.
late StreamController _controller;
late StreamSubscription _subscriber;
@override
void initState() {
_controller = StreamController<http.Response>();
_subscriber = _controller.stream.listen((event) {
});
super.initState();
}
In controller's stream we will add all server responses and work with those by _subscriber;
- Add to stream value to work with
final response = await docMember
.update(json)
.then((value) => {print("done")})
.catchError((e) => (e));
_controller.add(response);
Whenever you get response from server, you should call _controller.add(response), to add to our stream a new value.
- Handle responses in stream
@override
void initState() {
_controller = StreamController<http.Response>();
_subscriber = _controller.stream.listen((event) {
if (event.statusCode < 200 || event.statusCode > 299)
{
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('error'),
backgroundColor: Colors.red,
),
);
}
else
{
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('success'),
backgroundColor: Colors.green,
),
);
}
});
final response = await docMember
.update(json)
.then((value) => {print("done")})
.catchError((e) => (e));
_controller.add(response);
super.initState();
}
In stream you'l check if code is "OK", then show succes message, otherwise - error.
All code snipped is showed below:
class ParentWidget extends StatefulWidget {
ParentWidget({Key? key}) : super(key: key);
@override
State<ParentWidget> createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
late StreamController<http.Response> _controller;
late StreamSubscription _subscriber;
@override
void initState() {
_controller = StreamController<http.Response>();
_subscriber = _controller.stream.listen((event) {
if (event.statusCode < 200 || event.statusCode > 299)
{
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('success'),
backgroundColor: Colors.green,
),
);
}
else
{
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('error'),
backgroundColor: Colors.red,
),
);
}
});
final response = await docMember
.update(json)
.then((value) => {print("done")})
.catchError((e) => (e));
_controller.add(response);
super.initState();
}
@override
void dispose() {
_subscriber.cancel();
_controller.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Center(
child: Text("Any widget")
);
}
}