Flutter 如何将地图从 Internet API 转换为列表?

问题描述

好吧,我在尝试从 API 获取数据时遇到了一个问题,我仍然收到此错误“未处理的异常:InternalLinkedHashMap' 不是'List”类型的子类型 我尝试了其他类似 stackoverflow 的线程的许多解决方案,但没有解决问题。

这是我用于 API 获取数据的实际代码

 Future<List<Payments>> fetchData() async {
  final response = await http
      .get(Uri.http(here it is the url for the API ));
  if (response.statusCode == 200) {
    List jsonResponse = json.decode(response.body);
    return jsonResponse.map((data) => new Payments.fromJson(data)).toList();
  } else {
    throw Exception('Ocurrio un error al intentar conseguir los datos');
  }
 }

这里是支付模型:

class Payments {
  final double year1;
  final double year2;
  final String account;

  Payments({this.year1,this.year2,this.account});
  factory Payments.fromJson(Map<String,dynamic> json) {
    return Payments(
      year1: json['2020'],year2: json['2021'],account: json['cuenta'],);
  }
}

JSON 数据:

{
  "datos": [
    {
      "2020": 500000,"2021": 550000,"cuenta": "Banco Unión"
    },{
      "2020": 350000.5,"2021": 400000,"cuenta": "Banco Nacional de Bolivia"
    },{
      "2020": 600000.5,"2021": 300000,"cuenta": "Banco de Crédito"
    }
  ]
}

最后是其余的代码

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Future<List<Payments>> futureData;

  @override
  void initState() {
    super.initState();
    futureData = fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter API and ListView Example',home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter ListView'),),body: Center(
          child: FutureBuilder<List<Payments>>(
            future: futureData,builder: (context,snapshot) {
              if (snapshot.hasData) {
                List<Payments> data = snapshot.data;
                return ListView.builder(
                    itemCount: data.length,itemBuilder: (BuildContext context,int index) {
                      return Container(
                        height: 75,color: Colors.white,child: Center(
                          child: Text(data[index].account),);
                    });
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }
              // By default show a loading spinner.
              return CircularProgressIndicator();
            },);
  }
}

如果有人能帮我解决这个问题,我将不胜感激。

解决方法

我希望问题出在以下行:

List jsonResponse = json.decode(response.body);

根据提供的 JSON 数据示例,从 json.decode 返回 Map<String,dynamic> 而不是列表。您的解析逻辑应如下所示:

final jsonResponse = json.decode(response.body);
final paymentList = jsonResponse['datos'] as List;
return paymentList.map((data) => Payments.fromJson(data)).toList();