简体   繁体   English

我无法显示来自 json 文件的数据 Flutter

[英]I can't show data from a json file Flutter

How can I display this data in my application?如何在我的应用程序中显示这些数据? in the debug console you see the data that I want to show in the form of a list, but no matter how hard I try, I don't get it:在调试控制台中,您会看到我想以列表形式显示的数据,但无论我多么努力,我都没有得到它:

class Participantes {
String apellido;
int chip;
String nombre;
int numero;
String place;
String tiempo;

Participantes({
  this.apellido,
  this.chip,
  this.nombre,
  this.numero,
  this.place,
  this.tiempo
});

factory Participantes.fromJson(Map<String, dynamic> parsedJson){
  //print(list.runtimeType);
  return Participantes(
    apellido  : parsedJson['apellido'],
    chip      : parsedJson['chip'],
    nombre    : parsedJson['nombre'],
    numero    : parsedJson['numero'],
    place     : parsedJson['place'],
    tiempo    : parsedJson['tiempo']
  );
}

Map<String, dynamic> toJson() {
  return {
    'apellido'  : apellido,
    'chip'      : chip,
    'nombre'    : nombre,
    'numero'    : numero,
    'place'     : place,
    'tiempo'    : tiempo
  };
}

The json file is like this: [ { "Apellido":"MARTINEZ GUTIERREZ", "Chip":739, "Nombre":"JOSE", "Numero":139, "Place":"1.", "Tiempo":"00:30:12,91" }, { "Apellido":"SUAREZ MORERA", "Chip":707, "Nombre":"DANIEL", "Numero":107, "Place":"2.", "Tiempo":"02:00:17,54" } ] json 文件是这样的: [ { "Apellido":"MARTINEZ GUTIERREZ", "Chip":739, "Nombre":"JOSE", "Numero":139, "Place":"1.", "Tiempo":"00:30:12,91" }, { "Apellido":"SUAREZ MORERA", "Chip":707, "Nombre":"DANIEL", "Numero":107, "Place":"2.", "Tiempo":"02:00:17,54" } ]

The widget to display is this:要显示的小部件是这样的:

Widget _crearListadoParticipantes() {
return FutureBuilder(
  future: eventosProvider.cargarParticipantes(evento, participantes),
  builder: (BuildContext context, AsyncSnapshot<List<Participantes>> snapshot) {
    if ( snapshot.hasData ) {
      final participantes = snapshot.data;
      return ListView.builder(
        itemCount: participantes.length,
        //itemBuilder: (context, i) => _crearParticipante(context, participantes[i]),
        itemBuilder: (context, i) {
          return _crearParticipante(context, participantes[i]);
        }
      );

    } else {
      return Center( child: CircularProgressIndicator());
    }
  },
);

and the Future I use I built it this way:以及我使用的 Future 我是这样构建的:

Oddly, the page doesn't work well for me if I paste this part as a code, so that's why I upload it in a photo:奇怪的是,如果我将这部分作为代码粘贴,该页面对我来说效果不佳,所以这就是我将其上传到照片中的原因:

I am sorry if my problem is annoying, I have been stuck in this problem for a long time and I don't know what else to do, I also apologize for showing the code in this way.如果我的问题很烦人,我很抱歉,我已经被这个问题困了很长时间,我不知道还能做什么,我也为以这种方式显示代码表示歉意。

Try this,试试这个,

Future<List<Participantes>> cargarParticipantes() async {
  final url = "...."; // Your url
  final resp = await http.get(url);
  final respBody = json.decode(resp.body) as List;
  final participants = respBody.map((x) => Participantes.fromJson(x)).toList();
  return participants;
}

You have to handle snapshot.hasError part too.您还必须处理snapshot.hasError部分。 Otherwise you won't know if there is any error in the future ,不然future有没有错误你都不知道,

Widget _crearListadoParticipantes() {
  return FutureBuilder<List<Participantes>>(
    future: cargarParticipantes(),
    builder: (context, snapshot) {
      print(snapshot?.data?.length);
      if (snapshot.hasData) {
        final participantes = snapshot.data;
        return ListView.builder(
            itemCount: participantes.length,
            //itemBuilder: (context, i) => _crearParticipante(context, participantes[i]),
            itemBuilder: (context, i) {
              return Text("${participantes[i]}");
              //return _crearParticipante(context, participantes[i]);
            });
      } else if (snapshot.hasError) {
        return Center(child: Text("${snapshot.error}"));
      } else {
        return Center(child: CircularProgressIndicator());
      }
    },
  );
}

map keys are case sensitive.映射键区分大小写。 So所以

class Participantes {
  String apellido;
  int chip;
  String nombre;
  int numero;
  String place;
  String tiempo;

  Participantes({
    this.apellido,
    this.chip,
    this.nombre,
    this.numero,
    this.place,
    this.tiempo,
  });

  factory Participantes.fromJson(Map<String, dynamic> parsedJson) {
    //print(list.runtimeType);
    return Participantes(
      apellido: parsedJson['Apellido'],
      chip: parsedJson['Chip'],
      nombre: parsedJson['Nombre'],
      numero: parsedJson['Numero'],
      place: parsedJson['Place'],
      tiempo: parsedJson['Tiempo'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'Apellido': apellido,
      'Chip': chip,
      'Nombre': nombre,
      'Numero': numero,
      'Place': place,
      'Tiempo': tiempo,
    };
  }
}

Also check this online tool( Quicktype ) to generate dart classes for json.还要检查这个在线工具( Quicktype )为 json 生成 dart 类。 (Don't forget to change the language) (不要忘记更改语言)

Once you get data in JSON, you are converting that data into List<dynamic> and you are just printing that data, and returning empty List<Participants> so first of all you need to modify your function as per your need.一旦您获得 JSON 格式的数据,您就将该数据转换为List<dynamic>并且您只是打印该数据,并返回空的List<Participants>因此首先您需要根据需要修改您的函数。

I am assuming that in your other part of application you are using List<Participants> , and in Participants object you have different properties like Apellido , Chip , Nombre etc.我假设在你的应用程序的其他部分你正在使用List<Participants> ,并且在Participants对象中你有不同的属性,如ApellidoChipNombre等。

Where are you using this function you need to create list view to show that data.您在哪里使用此功能,您需要创建列表视图以显示该数据。 Here is one example of list view that you can modify and use in your application这是您可以在应用程序中修改和使用的列表视图的一个示例

final List<Participants> participants = await cargarParticipants(param1, param2);

ListView.builder(
  itemCount: participants.length,
  itemBuilder: (BuildContext context, int index) {
    return Container(
      child: Center(child: Text('${participants[index].Apellido}')),
    );
  }
);

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

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