Flutter快照数据为空

时间:2019-11-23 17:55:32

标签: json flutter

我是新手,我尝试解析来自rest api的数据。 api返回:

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

例如。这里从json api获取数据。长度是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;
    }
    }
  }

但这是快照。hasData= False,为什么?

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}');
  }
json开头的

没有项目都可以正常工作。我的Web服务器在开始时返回项目。有解决方案吗?

3 个答案:

答案 0 :(得分:1)

api返回Map<String, dynamic>而不是<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);
    }
  }
}

答案 1 :(得分:0)

必须尝试致电

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

答案 2 :(得分:0)

通常,您在hasData = false时得到hasError = true。尝试查找快照错误(snapshot.error