The function call is not returning null but still giving "null" to be returned error

Issue

I’m migrating my old version flutter code to latest version with null safety feature.

In a function call I am getting the error "The body might complete normally, causing ‘null’ to be returned, but the return type is a potentially non-nullable type". I have enclosed my code in try catch block and in catch block I added rethrow statement to prevent null exception.

This is my code.

    Future<Map<String, dynamic>> fetchTimeline(http.Client client) async {
        try {
          print('INVOICE URL: ${globals.ursl.getURL(URLS.GETINVOICEURL)}');

          Response response;
          Dio dio = new Dio();

          response = await dio.get(globals.ursl.getURL(URLS.GETINVOICEURL));
          print('INVOICE GET RESPONSE: $response');
          if (response.statusCode == 200) {
            Map mapobject = (json.decode(response.toString()));
            var succes = mapobject['success'];
            if (succes == 1) {
              if (mapobject['Invoice'][0]['address'] == null ||
                  mapobject['Invoice'][0]['address'] == '') {
                address = '';
              } else {
                address = mapobject['Invoice'][0]['address'];
              }

              if (mapobject['Invoice'][0]['contact'] == null ||
                  mapobject['Invoice'][0]['contact'] == '')
                phone = '';
              else
                phone = mapobject['Invoice'][0]['contact'];

              if (mapobject['Invoice'][0]['restaurant_name'] == null ||
                  mapobject['Invoice'][0]['restaurant_name'] == '') {
                name = ' ';
              } else {
                name = mapobject['Invoice'][0]['restaurant_name'];
              }
              logo = mapobject['Invoice'][0]['logo'];
              globals.invoiceData = mapobject['Invoice'][0];
              startTime();
              return mapobject['Invoice'][0];
            } else {
              return {};
            }
          }
        } catch (error) {
          client.close();

          print("CONNECTION CLOSED: $error");
          rethrow;
        }
      }

I have added rethrow in catch block but still error is there.
Anyone there to help me out.

Thanks

Solution

It’s a little hard to see with all the nested if statements, but you aren’t returning a Map<String, dynamic> in every branch. This condition if (response.statusCode == 200) { ... } does not have a corresponding else branch, and so if the statusCode is some value other than 200 you are not returning anything (which means you are implicitly returning null in that case).

Answered By – mmcdon20

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

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