Home > Net >  How to show success message and catch error during flutter firestore data update
How to show success message and catch error during flutter firestore data update

Time:08-18

I have this function

Future updateMember(Member member) async {
  final User? user = Auth().currentUser;
  final docMember =
      FirebaseFirestore.instance.collection('users').doc(user?.uid);
  member.id = docMember.id;

  final json = member.toJson();
  final response = await docMember
      .update(json)
      .then((value) => {print("done")})
      .catchError((e) => (e));

  return response;
}

Then I want to catch the error here and success message here

  final response = updateMember(member);
              if (response.then((value) => 'done') == true) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('success'),
                    backgroundColor: Colors.green,
                  ),
                );
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text(catchError(onError)),
                    backgroundColor: Colors.red,
                  ),
                );
              }

Please I need help on how I can implement this

CodePudding user response:

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.

  1. 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;

  1. 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.

  1. 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")
    );
  }
}

CodePudding user response:

This solves the problem

updateMember(member)
              .whenComplete(
                  () => ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                          content: Text('succes'),
                          backgroundColor: Colors.green,
                        ),
                      ))
              .onError((error, stackTrace) =>
                  ScaffoldMessenger.of(context).showSnackBar(
                     SnackBar(
                      content: Text(error.toString()),
                      backgroundColor: Colors.red,
                    ),
                  ));
        });
  • Related