Search code examples
flutterapirestdictionaryget

Flutter getting data from a map API


hi am new to flutter and i need to get data from a map using API I m struggling at the moment and don't know what to do I always keep getting a error Error '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable' this is the class code

// To parse this JSON data, do
//
//     final aziz = azizFromJson(jsonString);

import 'dart:convert';

Demandes azizFromJson(String str) => Demandes.fromJson(json.decode(str));

String azizToJson(Demandes data) => json.encode(data.toJson());

class Demandes {
  Demandes({
    required this.srMboSet,
  });

  SrMboSet srMboSet;

  factory Demandes.fromJson(Map<String, dynamic> json) => Demandes(
        srMboSet: SrMboSet.fromJson(json["SRMboSet"]),
      );

  Map<String, dynamic> toJson() => {
        "SRMboSet": srMboSet.toJson(),
      };
}

class SrMboSet {
  SrMboSet({
    required this.rsStart,
    required this.rsCount,
    required this.sr,
  });

  int rsStart;
  int rsCount;
  List<Sr> sr;

  factory SrMboSet.fromJson(Map<String, dynamic> json) => SrMboSet(
        rsStart: json["rsStart"],
        rsCount: json["rsCount"],
        sr: List<Sr>.from(json["SR"].map((x) => Sr.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "rsStart": rsStart,
        "rsCount": rsCount,
        "SR": List<dynamic>.from(sr.map((x) => x.toJson())),
      };
}

class Sr {
  Sr({
    required this.rowstamp,
    required this.attributes,
  });

  String rowstamp;
  Attributes attributes;

  factory Sr.fromJson(Map<String, dynamic> json) => Sr(
        rowstamp: json["rowstamp"],
        attributes: Attributes.fromJson(json["Attributes"]),
      );

  Map<String, dynamic> toJson() => {
        "rowstamp": rowstamp,
        "Attributes": attributes.toJson(),
      };
}

class Attributes {
  Attributes({
    required this.ticketid,
    required this.attributesClass,
    required this.description,
    required this.status,
    required this.statusdate,
    required this.reportedby,
  });

  Class ticketid;
  Class attributesClass;
  Class description;
  Class status;
  Class statusdate;
  Class reportedby;

  factory Attributes.fromJson(Map<String, dynamic> json) => Attributes(
        ticketid: Class.fromJson(json["TICKETID"]),
        attributesClass: Class.fromJson(json["CLASS"]),
        description: Class.fromJson(json["DESCRIPTION"]),
        status: Class.fromJson(json["STATUS"]),
        statusdate: Class.fromJson(json["STATUSDATE"]),
        reportedby: Class.fromJson(json["REPORTEDBY"]),
      );

  Map<String, dynamic> toJson() => {
        "TICKETID": ticketid.toJson(),
        "CLASS": attributesClass.toJson(),
        "DESCRIPTION": description.toJson(),
        "STATUS": status.toJson(),
        "STATUSDATE": statusdate.toJson(),
        "REPORTEDBY": reportedby.toJson(),
      };
}

class Class {
  Class({
    required this.content,
  });

  String content;

  factory Class.fromJson(Map<String, dynamic> json) => Class(
        content: json["content"],
      );

  Map<String, dynamic> toJson() => {
        "content": content,
      };
}

and this is my main code I always get a error if anyone can help please

// ignore_for_file: use_key_in_widget_constructors, avoid_print, avoid_unnecessary_containers, curly_braces_in_flow_control_structures, prefer_const_constructors, non_constant_identifier_names, unnecessary_new, avoid_function_literals_in_foreach_calls
import 'dart:convert';
import './demandes.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DataFromAPI(),
    );
  }
}

class DataFromAPI extends StatefulWidget {
  @override
  _DataFromAPIState createState() => _DataFromAPIState();
}

class _DataFromAPIState extends State<DataFromAPI> {
  List<Attributes> MyAllData = [];
  @override
  void initState() {
    loadData();
  }

  loadData() async {
    var response = await http.get(Uri.parse(
        'http://192.168.1.30:9080/maxrest/rest/mbo/sr/?_lid=&_lpwd=&_format=json'));
    if (response.statusCode == 200) {
      String responseBody = response.body;
      Map<String, dynamic> jsonBody = json.decode(responseBody);
      for (var data in jsonBody) {
        MyAllData.add(Attributes(
            ticketid: data["ticketid"],
            attributesClass: data["attributesClass"],
            description: data["description"],
            status: data["status"],
            statusdate: data["statusdate"],
            reportedby: data["reportedby"]));
      }
      setState(() {
        MyAllData.forEach((somedata) => print("Name: ${somedata.ticketid}"));
      });
    } else {
      print("theres something wrong...");
    }
  }

  Widget build(BuildContext context) {
    return MaterialApp(
      home: new Scaffold(
        appBar: AppBar(
          title: Text('Liste des SR'),
        ),
        body: MyAllData.length == 0
            ? new Center(
                child: new CircularProgressIndicator(),
              )
            : showMyUI(),
      ),
    );
  }

  Widget showMyUI() {
    return new ListView.builder(
        itemCount: MyAllData.length,
        itemBuilder: ((_, index) {
          return new Container(
            child: new Card(
              child: new Container(
                child: new Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    new Text(
                      'Ticket ID : ${MyAllData[index].ticketid}',
                    ),
                  ],
                ),
              ),
            ),
          );
        }));
  }
}

Solution

  • So from your model class, what I see is that you have Attributes inside of Sr, but after your JSON decode, you went ahead to just add data to the attributes list, so that's where your error is coming from, you have not fully deserialised the data here's how you can do it and it would work

          loadData() async {
            var response = await http.get(Uri.parse(
                'http://192.168.1.30:9080/maxrest/rest/mbo/sr/?_lid=&_lpwd=&_format=json'));
            if (response.statusCode == 200) {
              final jsonBody = json.decode(response.body);
    Demandes data = Demandes.fromJson(jsonBody);
    final srAttributes = data.srMboSet.sr;
    // SR is your list attributes is just an object, So what you do is this 
              for (int attribute = 0; attribute  < srAttributes.length; attribute++) {
    MyAllData.add(srAttributes[attribute].attributes);
    
              }
              setState(() {
                MyAllData.forEach((somedata) => print("Name: ${somedata.ticketid}"));
              });
            } else {
              print("theres something wrong...");
            }
          }