Ghanshyam Savaliya
Ghanshyam Savaliya

Reputation: 345

How to stop execution until async function completes it's task in dart

I am developing a flutter app,in which Build method calls fetchCitiesList method for list of cities,which sets cities variable to list of cities.And Build method use it for making a list of listtiles.

var cities;
    void fetchCitiesList () async {
    var url = 'https://gnsyms.000webhostapp.com/cities.php';
    var json;
    var httpClient = new HttpClient();
    try {
      var req = await httpClient.getUrl(Uri.parse(url));
      var res = await req.close();
      if (res.statusCode == HttpStatus.OK) {
        json = await res.transform(UTF8.decoder).join();
        cities = JSON.decode(json);
      }
    } catch (exception) {
      print(exception);
    }
  }


    @override
    Widget build(BuildContext context) {
    final double systemTopPadding = MediaQuery.of(context).padding.top;
    fetchCitiesList();
        return new Scaffold(
        appBar: new AppBar(
          title: new Center( child: new Text(widget.title,textScaleFactor: 1.3,), ),
        ),

        body: new Center(
          child: new Column(
            children: <Widget>[
              new Padding(padding: new EdgeInsets.fromLTRB(0.0, 228.0, 0.0, 15.0) , child: new Text('Select A City',style:_biggerFont)),
              new DropdownButton(
                  items: new List.generate(cities.length, (int index){
                    return new DropdownMenuItem(child: new Container(
                      child: new Center(
                          child:new Text(cities[index],textScaleFactor: 1.4,))
                      ,width: 250.0,),value: cities[index],);
                  }),
                  value: city,
                  onChanged: (arg){
                    setState((){
                      city = arg;
                      print(arg);
                    });
                  }),
              new Padding(padding: new EdgeInsets.fromLTRB(0.0, 15.0, 15.0, 0.0),
                  child : new IconButton(icon: new Icon(Icons.arrow_forward,color: Colors.blue,size: 60.0,),
                      onPressed: _produceHospitalCards)),

            ],
          ),
        )
    );
  }

But it causes following exception.So,how to stop execution until async function completes it's task.

The following NoSuchMethodError was thrown building MyHomePage(dirty, state:
I/flutter ( 7695): _MyHomePageState#ec54c):
I/flutter ( 7695): The getter 'length' was called on null.
I/flutter ( 7695): Receiver: null
I/flutter ( 7695): Tried calling: length

Upvotes: 2

Views: 4880

Answers (1)

Mans
Mans

Reputation: 3261

You should use the FutureBuilder widget. Here is the example from the docs:

new FutureBuilder<String>(
  future: _calculation, // a Future<String> or null
  builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none: return new Text('Press button to start');
      case ConnectionState.waiting: return new Text('Awaiting result...');
      default:
        if (snapshot.hasError)
          return new Text('Error: ${snapshot.error}');
        else
          return new Text('Result: ${snapshot.data}');
    }
  },
)

Regarding your case: if you make fetchCitiesList() return the list of cities, then you can call fetchCitiesList() instead of _calculation from the example, and then get the data by doing snapshot.data.

Hope this helps.

Upvotes: 3

Related Questions