PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 14, 2022

[FIXED] how to avoid crash when data is missing and throw exeption in flutter

 November 14, 2022     error-handling, flutter     No comments   

Issue

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();
                                                }),

Solution

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.



Answered By - Gwhyyy
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing