Home > Enterprise >  how to avoid crash when data is missing and throw exeption in flutter
how to avoid crash when data is missing and throw exeption in flutter

Time:10-01

here is my code to catch data from web:

it crashes with multiple kind of exeptions each time, i want to show the error on screen but do not crash the app and terminate it

Future<SCoin> fetchCoinData(int giveMeIndex) async {
  final response = await http.get(Uri.parse(url));
  final jsonresponse = json.decode(response.body);

if (response.statusCode == 200) {
for (var i in jsonresponse) {
  var coinItem = SCoin(
      name: i['name'],
      image: i['image'],
      current_price: i['current_price']);
  coins.add(coinItem);
}
return SCoin.fromJson(jsonresponse[giveMeIndex]);
} else {
throw Exception(response.statusCode);
 }
}

and this my widget to show data:

FutureBuilder<SCoin>(
                                                future: fetchCoinData(2),
                                                builder:
                                                    (context, snapshot) {
                                                  if (snapshot.hasData) {
                                                    return Column(
                                                      children: [
                                                        Container(
                                                          width: 45,
                                                          height: 45,
                                                          child: Image.network(
                                                              snapshot.data!
                                                                  .coinImage),
                                                        ),
                                                        Text(snapshot
                                                            .data!.name),
                                                        Text(snapshot.data!
                                                            .current_price
                                                            .toString())
                                                      ],
                                                    );
                                                  } else if (snapshot
                                                      .hasError) {
                                                    return Text(
                                                        '${snapshot.error}');
                                                  }

                                                  // By default, show a loading spinner.
                                                  return const CircularProgressIndicator();
                                                }),

CodePudding user response:

this is done with the try and catch to try running a code, if there is any error you can evaluate and catch it, and the future you set to the FutureBuilder should be wrapped inside another function that tries it and then catch on error like :

Future tryCatchMethod(int number) async {

try {
await fetchCoinData(number);
} on Exception catch(error) {
// Here throw you exceptions and take actions based on your needs
}}

and assigning that new method to the FutureBuilder

future: tryCatchMethod;

this will try running your Future method, if it succeeds, then nothing will happen, normally, but if something wrong happened and an error threw it will execute the catch block code.

CodePudding user response:

Try the following code:

Future<SCoin> fetchCoinData(int giveMeIndex) async {
  try {
    final response = await http.get(Uri.parse(url));
    final jsonresponse = json.decode(response.body);

    if (response.statusCode == 200) {
      for (var i in jsonresponse) {
      var coinItem = SCoin(
        name: i['name'],
        image: i['image'],
        current_price: i['current_price'],
      );
      coins.add(coinItem);
      }
      return SCoin.fromJson(jsonresponse[giveMeIndex]);
    } else {
      throw Exception(response.statusCode);
    }
  } catch (e) {
    throw Exception(e);
  }
}
  • Related