简体   繁体   中英

Flutter snapshot data is empty

I'm new in flutter, I try parse data from rest api. Api return:

http://www.json-generator.com/api/json/get/cqwVqdOFrC?indent=2

Eg. Here get data from json api eg. length is 3231

class ApiService {
  static Future<dynamic> _get(String url) async {
    try {
    final response = await http.get(url);

    var jsonData = json.decode(response.body);

    if (response.statusCode == 200) {
        print(response.body.length);  //3231
        return jsonData;

    } else {
            return null;
    }
    }
  }

but here is snapshot.hasData = False, Why?

return Scaffold(
   appBar: AppBar(title: Text('Posts'),),
      body: FutureBuilder(
        future: ApiService.getUserList(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          print(snapshot.hasData.toString());  //False no data





static Future<List<dynamic>> getUserList() async {
    return await _get('${Urls.BASE_API_URL}');
  }

Without items at the beginning of json all work fine. My web server return items at the beginning. Any solutions?

api returns Map<String, dynamic> not <List<dynamic>>

class ListaAbitudini extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new _ListaAbitudiniState();
  }
}

class _ListaAbitudiniState extends State<ListaAbitudini> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Posts'),
        ),
        body: FutureBuilder(
            future: ApiService.getUserList(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if(snapshot.hasData)
              print("True");

              return Container();
            }));
  }
}

class ApiService {
  static Future<Map<String, dynamic>> getUserList() async {
    return await _get('http://www.json-generator.com/api/json/get/cqwVqdOFrC?indent=2');
  }

  static Future<dynamic> _get(String url) async {
    try {
      final response = await http.get(url);

      var jsonData = json.decode(response.body);

      if (response.statusCode == 200) {
        print(response.body.length); //3231
        return jsonData;
      } else {
        return null;
      }
    } catch (e) {
      print(e);
    }
  }
}

Have to try calling,

future: ApiService.getUserList().then((onValue) {
                      return onValue;
                    }

Usually you get hasData = false when hasError = true . Try to look for a snapahot error ( snapshot.error )

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