Home > Software design >  Instance of 'Future<dynamic>' . I am getting this error and unable to load informati
Instance of 'Future<dynamic>' . I am getting this error and unable to load informati

Time:01-29

 final String apiUrl = 'https://api.covid19api.com/summary';
       Future globaldata()  async{

     var res = await http.get(Uri.parse(apiUrl));
     Map s = await jsonDecode(res.body);
        return s['Global']['NewConfirmed'];
}
//....

Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("global cases"),
        centerTitle: true,
      ),
      body:Container(

        child: FutureBuilder(
          future: globaldata(),
          builder: (context, snapshot){

            if(snapshot.data != null){
              print(globaldata());
              return Text(globaldata().toString());
            }else{
              return Text("loading ...");
            }
          },
        ),


      ),
    );
  }
}

I am getting error of Instance of 'future'

CodePudding user response:

Try doing these

       child: FutureBuilder(
      future: globaldata(),
      builder: (context, snapshot) {

        if(snapshot.data != null){
          print(snapshot.data);
          return Text(snapshot.data);
        }else{
          return Text("loading ...");
        }
      },
    ),


  ),
);

Check Print and return Text statement

CodePudding user response:

You get this error because you are printing and returning Futures without await:

print(globaldata());
return Text(globaldata().toString());

Your FutureBuilder provides you the values you are trying to access in snapshot:

print(snapshot.data);
return Text(snapshot.data.toString());

CodePudding user response:

Change your function to this.

Future globaldata() async {
   http.Response response = await http.get(Uri.parse(apiUrl));
   if (response.statusCode == 200) {
     return jsonDecode(response.body)['Global']['NewConfirmed'];
   } else {
     throw Exception('Failed to load post');
   }
}

and change your body to this.

body: FutureBuilder(
      future: globaldata(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Center(
            child: Text(snapshot.data.toString()),
          );
        } else if (snapshot.hasError) {
          return Center(
            child: Text("${snapshot.error}"),
          );
        }
        return const Center(
          child: CircularProgressIndicator(),
        );
      },
    ),

This works perfectly.

  •  Tags:  
  • Related