Parsing Json in flutter - Does not show data

Viewed 34

I am developing an android application with flutter, what I am doing is displaying a json in an application page. When I run the application it doesn't give me an error but it doesn't show me the data, the json I want to read is the following:

[
  {
    "deviceid": 27,
    "f2cuid": "Estacion1_A",
    "devicedata": {
      "isRunning": 0,
      "color": "w3-red",
      "colorNoW3": "red",
      "device_name": "Estacion1_A"
    }
  },
  {
    "deviceid": 20,
    "f2cuid": "B19",
    "devicedata": {
      "isRunning": 1,
      "color": "w3-green",
      "colorNoW3": "green",
      "device_name": "B19"
    }
  }
]

It's in my model class:

class Stations {
  Int? isRunning;
  String? color;
  String? colorNoW3;
  String? devicename;

  Stations(
      {this.isRunning,
        this.color,
        this.colorNoW3,
        this.devicename,
  });

  factory Stations.fromJson(Map<String, dynamic> json) {
    return Stations(
      isRunning: json['isRunning'],
      color: json['color'],
      colorNoW3: json['colorNoW3'],
      devicename: json['device_name'],
    );
  } 
}

This is my service:

Future<List<Stations>> getStations() async {
Uri url = Uri.parse('URL');

final response = await http.get(url);

var data = jsonDecode(response.body);

print('data: $data');
List<Stations> stations = data.map((e) => Stations.fromJson(e)).toList();
return stations;
}

and this is the way I display it:

return Scaffold(
      appBar: AppBar(
        title: const Text('Sistema Escolar Administrativo'),
      ),
      drawer: DrawerWidgetMenu(),
      body: Container(
        child: FutureBuilder(
            future: stationSvc.getStations(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (!snapshot.hasData) {
                return Container(
                  child: Center(
                    child: Text('No hay datos que mostrar'),
                  ),
                );
              }
              return snapshot.data.length > 0
                  ? ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (BuildContext context, int index) {
                    return Card(
                        child: InkWell(
                          onTap: () {
                            Navigator.of(context).pushReplacement(
                              MaterialPageRoute(
                                builder: (context) => HomePage(),
                              ),
                            );
                          },
                          child: ListTile(
                            leading: Text(snapshot.data[index].devicename!),
                            title: Text(snapshot.data[index].color!),
                            subtitle: Text(snapshot.data[index].colorNoW3!),
                          ),
                        ));
                  })
                  : Center(
                  child: Text('No hay datos, registra un grupo primero'));
            }),
      ),
    );
3 Answers

You forgot to specify nested map:

factory Stations.fromJson(Map<String, dynamic> json) {
    return Stations(
      isRunning: json['devicedata']?['isRunning'],
      color: json['devicedata']?['color'],
      colorNoW3: json['devicedata']?['colorNoW3'],
      devicename: json['devicedata']?['device_name'],
    );
  } 

I am sharing a complete class named SampleModel below which can help to parse JSON in flutter:

class SampleModel {
  String? _myName;
  bool? _isActive;
  SampleModel({String? myName, bool? isActive}) {
    if (myName != null) {
      _myName = myName;
    }
    if (isActive != null) {
      _isActive = isActive;
    }
  }
  String? get myName => _myName;
  set myName(String? myName) => _myName = myName;
  bool? get isActive => _isActive;
  set isActive(bool? isActive) => _isActive = isActive;
  SampleModel.fromJson(Map<String, dynamic> json) {
    _myName = json['myName'];
    _isActive = json['isActive'];
  }
  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['myName'] = _myName;
    data['isActive'] = _isActive;
    return data;
  }
}

Sample JSON for the same class:

{
   "myName" : "Your Name",
   "isActive" : true
}

Check if this can help in your case.

your json type is an array, not a map. look at [ ] syntax on json file.

to deal with an Array, you should make it to a list first:

List<Map<String,dynamic>> mylistofMapformJson = json.decode(receivedJson);

    //you should get your list stations like this:
    List<Stations> listStationsFromJson = List.generate(
        mylistofMapformJson.length,
            (index) => Stations.fromJson(mylistofMapformJson));
Related