Flutter null-safety migration – top_snackbar_flutter

Issue

I did a dart migrate to update my project to null-safety. I have several issues to sort as it was an old project.
However, one thing is stumping me a lot and unable to figure out a way.

I am using top_snackbar_flutter package and updated the same to nullsafe version (latest v1.0.2).

I had the following code:

Widget showTopBarErrorWidget({required context, String? messageArg}) {
  showTopSnackBar(
      context,
      CustomSnackBar.error(
        message: messageArg ??
            "Error while starting the session Plans. Please try again",
      ),
      displayDuration: Duration(seconds: 5));
}

Widget showTopBarSuccessWidget({required context, String? messageArg}) {
  showTopSnackBar(
    context,
    CustomSnackBar.success(
      message: messageArg ?? "Success",
    ),
  );
}

This code is referenced in various places for errors and success.So hoping to fix this and see all my errors go away related to this snackbar.

One of the examples of the reference:

Future verifyIapPurchase({BuildContext? context, Map? body}) async {
    var _data = {"valid": false};
    try {
      final _res = await sl<ISubscriptionService>().verifyPurchase(body: body);
      return (_res != null && _res.data != null) ? _res.data : _data;
    } catch (err) {
      showTopBarErrorWidget(
          context: context,
          messageArg: err.message ?? "Failed to verify the subscription");
      return _data;
    }
  }

The errors I get are:
VSCode Error

I realised that the function is actually void,
enter image description here
but I need to return a Widget. I have tried adding try and a catch block but did nothing.

Widget showTopBarErrorWidget({required context, String? messageArg}) {
  try {
    showTopSnackBar(
        context,
        CustomSnackBar.error(
          message: messageArg ??
              "Error while starting the session Plans. Please try again",
        ),
        displayDuration: Duration(seconds: 5));
  } on Exception catch (e) {
    print(e);
    rethrow;
  }
}

Solution

As h8moss said
you don’t have anything to return from showTopBarErrorWidget so remove the Widget return type and make it void

void showTopBarErrorWidget({required context, String? messageArg}) {

The showTopSnackBar will execute anyway, no need to return it or something.

Answered By – omar hatem

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *