【问题标题】:Flutter How to convert map to a list from internet API?Flutter 如何将地图从互联网 API 转换为列表?
【发布时间】:2021-06-16 07:04:09
【问题描述】:

我在尝试从 API 获取数据时遇到了问题,我仍然收到此错误“未处理的异常:InternalLinkedHashMap”不是“列表”类型的子类型 我尝试了许多其他 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();
            },
          ),
        ),
      ),
    );
  }
}

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

【问题讨论】:

    标签: json api flutter get fluttermap


    【解决方案1】:

    我预计问题出在以下行:

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

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

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

    【讨论】:

    • 成功了!太感谢了!但现在,在应用程序上我收到了这个错误:'type 'double' is not a subtype of type int."
    • 这可能是因为像 550000 这样的值,因为它们是 int 类型。只需使用as double 进行投射,例如json['2020'] as double.
    • 我认为问题出在一个对象上,年份是整数 { "2020": 500000, "2021": 550000, "cuenta": "Banco Unión" },但在另一个对象中是数据具有双值:{“2020”:350000.5,“2021”:400000,“cuenta”:“Banco Nacional de Bolivia”},我尝试将 2020 和 2021 转换为双倍,但我得到相同的错误,但现在说双倍不是int 的子类型
    • 不确定,但我已经在 DartPad 中尝试过您的示例,即使没有任何转换,它对我来说也能正常工作。
    • 我将值更改为 num 值,它工作,非常感谢您的帮助
    猜你喜欢
    • 2022-11-12
    • 2023-01-13
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多