0

I have landing Flutter page (main.dart). I have JSON data and I am using Future to get it. My question is that if the data is null or if the JSON link is dead how can I show the app with empty data.

My problem is my Flutter app Strats with a white screen then it turns black with showing CircularProgressIndicator. If the above error exists its keeps running a black screen with CircularProgressIndicator.

When my App starts from the second I need to show the CircularProgressIndicator and do the rest. And if the JSON data is null or link is dead I still need to show my app with empty data and show some warning.

// TODO: 4) _MyHomePageState Class
class _MyHomePageState extends State<MyHomePage> {

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.getCurrencyJsonData();
  }

  Future<String> getCurrencyJsonData() async {
    var response = await http.get(
        Uri.encodeFull("https://secure.*****************fx.jsp"),
        headers: {'Accept': 'application/json'});

    setState(() {
      var resBody = json.decode(response.body);
      currencyData = resBody["currency"];
      stgBuy = currencyData["sterling"]["buy"];
      print("STG: $stgBuy");
    });

    return "Success!";
  }


// TODO: BUILD WIDGET
  @override
  Widget build(BuildContext context) {
    if (currencyData == null){
      return new Center(
          child: new CircularProgressIndicator(
            backgroundColor: lightMainGreen,
          )
      );
    } else {

      return new Scaffold(
        // APPBAR
        appBar: new AppBar(
          title: new Text(
    …… 
    ……
    ……

2 Answers 2

1

Okay, based on @günter-zöchbauer suggestion, I use a FutureBuilder and solved my problem. Here is the full code part:

// TODO: 4) _MyHomePageState Class
class _MyHomePageState extends State<MyHomePage> {


// TODO: BUILD WIDGET
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        // APPBAR
        appBar: new AppBar(
          title: new Text("main.appTitle"),
            style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.w500),
          ),
          backgroundColor: midMainGreen,
        ),
        drawer: new DrawerMenu(),

        // BODY
        body: new Center(
          child: new FutureBuilder(
              future: getCurrencyJsonData(),
              builder: (context, snaphot) {
                if (snaphot.hasData) {
                  return new ListView(
                    padding: const EdgeInsets.all(0.0),
                    children: <Widget>[
                      new MainHeader(),
                      new Padding(
                          padding: EdgeInsets.fromLTRB(3.0, 4.0, 3.0, 4.0)),
                      new CurrencyCard(),
                      new LandingListMenu(),
                    ],
                  );
                }
                return new CircularProgressIndicator();
              }),
        ));
  } // build Widget
} // 4) _MyHomePageState Class


    Future<String> getCurrencyJsonData() async {

  var response = await http.get(
      Uri.encodeFull("https://secure.*****************fx.jsp"),
      headers: {'Accept': 'application/json'});

  if (response.statusCode == 200) {
     var resBody = json.decode(response.body);
     currencyData = resBody["currency"];
     if (currencyData != null) {
        stgBuy = currencyData["sterling”][“alis"];

     } else {
        stgBuy = "0.0000";
     }
  } else {
    stgBuy = "0.0000";
  }


  return "Success!";
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could handle errors in getCurrencyData(). Then in build() you could check if you have received an error.

Future<Map<String, dynamic>> getCurrencyJsonData() async (
  try {
    http.Response response = await http.get(url);
    if (response.statusCode == 200) {
      return {"success": json.decode(response.body)};
    }
    // Bad Request
    else if (response.statusCode == 400) {
      return {"error": "Bad request"};
    } else if (response.statusCode == 401) {
      return {"error": "Unauthorized"};
    }
  } on Exception {
    return {"error": "Some exception"};
  }
  setState(() {});
}

@override
Widget build(BuildContext context) {
if (currencyData == null){
  return new Center(
      child: new CircularProgressIndicator(
        backgroundColor: lightMainGreen,
      )
  );
} else if (currencyData.containsKey("error")){
  return new ErrorScaffold(
  ...)
} else {

  return new Scaffold(
  .....

1 Comment

@chemamolis, I use FutureBuilder and solved my problem. I will use your response status code and update my answer. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.