繁体   English   中英

在 flutter 中解析 Json - 不显示数据

[英]Parsing Json in flutter - Does not show data

我正在使用 flutter 开发 android 应用程序,我正在做的是在应用程序页面中显示 json。 当我运行应用程序时,它没有给我错误,但没有显示数据,我想阅读的 json 如下:

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

它在我的 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'],
    );
  } 
}

这是我的服务:

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

这就是我展示它的方式:

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

您忘记指定嵌套的 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'],
    );
  } 

我在下面共享一个名为SampleModel的完整 class,它可以帮助解析 flutter 中的 JSON:

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

样品 JSON 用于相同的 class:

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

检查这是否对您的情况有所帮助。

您的 json 类型是数组,而不是map 查看 json 文件上的[ ]语法。

要处理一个数组,你应该先把它放到一个列表中:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM