Flutter How to convert map to a list from internet API?

Viewed 1308

Well I just had a problem while I was trying to get data from an API, I just still getting this error "Unhandled Exception: InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List" I tried many solutions of other stackoverflow similar threads but nothing fixed the problem.

This is my actual code for the API fetch data:

 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');
  }
 }

Here the model for the payments:

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'],
    );
  }
}

The JSON Data:

{
  "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"
    }
  ]
}

and finally the rest of the code:

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();
            },
          ),
        ),
      ),
    );
  }
}

If anyone could help me solving this issue I would be really grateful.

1 Answers

I expect the problem is with the following line:

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

Based on the provided JSON data example, a Map<String, dynamic> is returned from json.decode and not a list. Your parsing logic should look like this:

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