0

好吧,我在尝试从 API 获取数据时遇到了问题,我仍然收到此错误“未处理的异常:InternalLinkedHashMap<String, dynamic>'不是'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();
            },
          ),
        ),
      ),
    );
  }
}

如果有人可以帮助我解决这个问题,我将非常感激。

4

1 回答 1

1

我预计问题出在以下行:

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

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

final jsonResponse = json.decode(response.body);
final paymentList = jsonResponse['datos'] as List;
return paymentList.map((data) => Payments.fromJson(data)).toList();
于 2021-03-18T20:37:16.230 回答