简体   繁体   中英

FutureBuilder freeze when decoding json

I have this large json string that I would like to decode. My problem is FutureBuilder freeze while decoding the json string and the snapshot.connectionState == ConnectionState.waiting was not triggered while decoding. I'm expecting to show circular loading bar while it still parsing the json string. Below is the same script.

Future<LocationList> _location;

  Future<LocationList> getLocation() async {
    final result = json.decode(LocationJson);
    LocationList locList = LocationList.fromJson(result);
    return locList;
  }

@override
  void initState() {
    _location = getLocation();
    super.initState();
  }

My FutureBuilder:

      body: FutureBuilder(
        future: _location,
        builder:
            (BuildContext context, AsyncSnapshot<locList> snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
             CircularProgressIndicator()
          ...................
          }

Sorry to answer my own question. I've fixed it using compute . Also _decodeLocation must be a global method or a static method, not a closure or an instance method as for this link

Here is the code:

  Map<String, dynamic> _decodeLocation(String jsonString) {
  return json.decode(jsonString);
  }

  Future<LocationList> getLocation() async {
    Map<String, dynamic> result = await compute(_decodeLocation, LocationJson);

    LocationList locList = LocationList.fromJson(result);
    return locList;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM