【问题标题】:how to set the model class to get all data of a json array from api如何设置模型类从api获取json数组的所有数据
【发布时间】:2021-07-01 19:07:11
【问题描述】:

我是flutter的初学者,我使用足球的api来获取球员转会的一些信息,所以我创建了一个模型类,其中只包含我需要的信息,但是当我执行时我遇到了这个问题 我只得到我想从 json url 获取的数组的第一个索引

,我需要的是所有结果,如何用某种索引或其他东西替换[0]?如何取所有元素?

这里是我试图访问的 json:

{
  
  "response": [
    {
      "player": {
        "id": 35845,
        "name": "Hernán Darío Burbano"
      },
      "update": "2020-02-06T00:08:15+00:00",
      "transfers": [
        {
          "date": "2019-07-15",
          "type": "Free",
          "teams": {
            "in": {
              "id": 2283,
              "name": "Atlas",
              "logo": "https://media.api-sports.io/football/teams/2283.png"
            }
          }
        },
        {
          "date": "2019-01-01",
          "type": "N/A",
          "teams": {
            "in": {
              "id": 1937,
              "name": "Atletico Atlas",
              "logo": "https://media.api-sports.io/football/teams/1937.png"
            }
          }
        }
      ]
    }
  ]
}

这里是我的模型类 tranfert_json:

   class Transferts {

  String date;
  String club;
  String image;


  Transferts(this.date, this.club, this.image);

  factory Transferts.fromJson(Map<String, dynamic> json) {
    return Transferts(
        json['transfers'][0]['date'],
        json['transfers'][0]['teams']['in']['name'],
        json['transfers'][0]['teams']['in']['logo']
    );
  }

}

这是我的 player_details 类:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:tl_fantasy/models/transfert_json.dart';

class PlayerDetails extends StatefulWidget {

  int id;
  String name;
  String lastname;
  String image;
  String club;
  String position;
  String nationality;
  String age;
  int matches;
  String goals;
  String assists;
  String saves;


  PlayerDetails({this.id,this.name, this.lastname,this.image, this.club, this.position,
      this.nationality, this.age, this.matches, this.goals, this.assists, this.saves});

  @override
  _PlayerDetailsState createState() => _PlayerDetailsState();
}

class _PlayerDetailsState extends State<PlayerDetails> {

  List<Transferts> teams = [];

  Future<void>  getTeams(int id) async {
    http.Response response = await http.get(
        'https://v3.football.api-sports.io/transfers?player=$id',
        headers: {'x-rapidapi-key': 'c52370f8295e1525b7f7ba38655e243f',
          'x-rapidapi-host':'v3.football.api-sports.io'});
    String body = response.body;
    var data = jsonDecode(body);
    List<dynamic> clubList = data['response'];

    setState(() {
      teams = clubList
          .map((dynamic item) => Transferts.fromJson(item))
          .toList();
    });

  }

  @override
  void initState() {
    super.initState();
    getTeams(widget.id);
  }

  @override
  Widget build(BuildContext context) {

    if(widget.matches == null ){
      widget.matches == 0;
    }
    if(widget.goals == null ){
      widget.goals == "0";
    }
    if(widget.assists == null ){
      widget.assists == "0";
    }
    if(widget.saves == null ){
      widget.saves == "0";
    }

    List<Stats> stats = [
      Stats("Matches", widget.matches.toString() ),
      Stats("Goals", widget.goals ),
      Stats("Assists", widget.assists ),
      Stats("Saves", widget.saves ),
    ];



    return Scaffold(
      appBar: AppBar(
        title: Text("Player Details"),
        backgroundColor: Colors.blue[300],
        elevation: 0.0,
      ),
      body: Container(
        decoration: BoxDecoration(
            gradient: LinearGradient(
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
                colors: [Colors.purple, Colors.blue])
        ),
        child: Container(
          decoration: BoxDecoration(
              gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [Colors.purple, Colors.black38])),
          child: ListView(
            children: [
              SizedBox(
                height: 20,
              ),
              Container(
                margin: EdgeInsets.fromLTRB(8.0,0,8.0,0),
                width: double.infinity,
                child:    Card(
                  elevation: 4.0,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child:
                    Row(
                      children: <Widget>[
                        Container(
                          height: 60,
                          width: 60,
                          child:
                          Image.network(this.widget.image,
                          ),
                        ),
                        const SizedBox(width:10.0),
                        Spacer(),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: <Widget> [
                            Text(widget.name, style: TextStyle( fontWeight:FontWeight.bold,
                              fontSize: 18.0,
                            )),
                            Text(widget.lastname, style: TextStyle( fontWeight:FontWeight.bold,
                              fontSize: 18.0,
                            )),
                            const SizedBox(height: 5.0, ),
                            Text(widget.club, style: TextStyle( fontWeight:FontWeight.bold,
                              fontSize: 18.0,
                            )),
                            const SizedBox(height: 5.0, ),
                            Text("Role : "+widget.position, style: TextStyle( fontWeight:FontWeight.bold,
                              fontSize: 18.0, color: Colors.grey[600],
                            )),
                            const SizedBox(height: 5.0, ),
                            Text("Age : "+widget.age, style: TextStyle( fontWeight:FontWeight.bold,
                              fontSize: 18.0, color: Colors.grey[600],
                            )),
                            const SizedBox(height: 5.0, ),
                            Text("Nationality : "+widget.nationality, style: TextStyle( fontWeight:FontWeight.bold,
                              fontSize: 18.0, color: Colors.grey[600],
                            )),

                          ],
                        ),

                      ],
                    ),
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.fromLTRB(10, 15, 0, 0),
                child:  Text(
                  "Season Stats",
                  style: TextStyle(fontSize: 17, fontWeight: FontWeight.w900, color: Colors.white),
                ),
              ),

              SizedBox(
                height: 10,
              ),
              Container(
                  padding: EdgeInsets.all(12.0),
                  child: GridView.builder(
                    shrinkWrap: true,
                    itemCount: stats.length,
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 2,
                        crossAxisSpacing: 4.0,
                        mainAxisSpacing: 4.0
                    ),
                    itemBuilder: (BuildContext context, int index){
                      return Card(
                        child: Center(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                              children: <Widget>[
                                Container(
                                  alignment: Alignment.topCenter,
                                  padding: EdgeInsets.fromLTRB(0, 5, 0, 0),
                                  child:  Text(stats[index].result,style: TextStyle(fontSize: 20.0)),
                                ),
                                Container(
                                  alignment: Alignment.bottomCenter,
                                  child: Text(stats[index].title,style: TextStyle(fontSize: 25.0)),),

                              ]
                          ),
                        ),
                      );
                    },
                  )
              ),
              SizedBox(
                height: 10,
              ),
              Container(
                margin: EdgeInsets.fromLTRB(10, 0, 0, 10),
                child:  Text(
                  "Teams",
                  style: TextStyle(fontSize: 17, fontWeight: FontWeight.w900, color: Colors.white),
                ),
              ),

              SizedBox(
                height: 10,
              ),
              Container(
                margin: EdgeInsets.fromLTRB(5, 0, 5, 0),
                child: ListView.builder(
                  shrinkWrap: true,
                  physics : NeverScrollableScrollPhysics(),
                  itemBuilder: (context, index){
                    return Card(
                      elevation: 4.0,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10.0),
                      ),
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child:
                        Row(
                          children: <Widget>[
                            CircleAvatar(
                              backgroundImage: NetworkImage(teams[index].image),
                            ),
                            const SizedBox(width:10.0),
                            Spacer(),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: <Widget> [
                                Text(teams[index].club, style: TextStyle( fontWeight:FontWeight.bold,
                                  fontSize: 18.0,
                                )),
                                const SizedBox(height: 5.0, ),
                                Text("joined : "+teams[index].date, style: TextStyle( fontWeight:FontWeight.bold,
                                  fontSize: 18.0, color: Colors.grey[600],
                                )),
                              ],
                            ),

                          ],
                        ),
                      ),
                    );
                  },
                  itemCount: teams.length,
                ),
              ),

              SizedBox(
                height: 70,
              ),
            ],
          ),

        )
      ),
    );
  }
}


class Stats{

  String title;
  String result;

  Stats(this.title,this.result);

}

class Team {

  String name;
  String image;
  String date;

  Team(this.name,this.image,this.date);

}

我正在尝试找到一种方法来获取所有结果,而不仅仅是我的 api json 的第一个索引

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    试试这个..

    class Response {
        Player player;
        String update;
        List<Transfers> transfers;
    
        Response({this.player, this.update, this.transfers});
    
        Response.fromJson(Map<String, dynamic> json) {
            player = json['player'] != null ? new Player.fromJson(json['player']) : null;
            update = json['update'];
            if (json['transfers'] != null) {
                transfers = new List<Transfers>();
                json['transfers'].forEach((v) { transfers.add(new Transfers.fromJson(v)); });
            }
        }
    
        Map<String, dynamic> toJson() {
            final Map<String, dynamic> data = new Map<String, dynamic>();
            if (this.player != null) {
          data['player'] = this.player.toJson();
        }
            data['update'] = this.update;
            if (this.transfers != null) {
          data['transfers'] = this.transfers.map((v) => v.toJson()).toList();
        }
            return data;
        }
    }
    
    class Player {
        int id;
        String name;
    
        Player({this.id, this.name});
    
        Player.fromJson(Map<String, dynamic> json) {
            id = json['id'];
            name = json['name'];
        }
    
        Map<String, dynamic> toJson() {
            final Map<String, dynamic> data = new Map<String, dynamic>();
            data['id'] = this.id;
            data['name'] = this.name;
            return data;
        }
    }
    
    class Transfers {
        String date;
        String type;
        Teams teams;
    
        Transfers({this.date, this.type, this.teams});
    
        Transfers.fromJson(Map<String, dynamic> json) {
            date = json['date'];
            type = json['type'];
            teams = json['teams'] != null ? new Teams.fromJson(json['teams']) : null;
        }
    
        Map<String, dynamic> toJson() {
            final Map<String, dynamic> data = new Map<String, dynamic>();
            data['date'] = this.date;
            data['type'] = this.type;
            if (this.teams != null) {
          data['teams'] = this.teams.toJson();
        }
            return data;
        }
    }
    
    class Teams {
        In in;
    
        Teams({this.in});
    
        Teams.fromJson(Map<String, dynamic> json) {
            in = json['in'] != null ? new In.fromJson(json['in']) : null;
        }
    
        Map<String, dynamic> toJson() {
            final Map<String, dynamic> data = new Map<String, dynamic>();
            if (this.in != null) {
          data['in'] = this.in.toJson();
        }
            return data;
        }
    }
    
    class In {
        int id;
        String name;
        String logo;
    
        In({this.id, this.name, this.logo});
    
        In.fromJson(Map<String, dynamic> json) {
            id = json['id'];
            name = json['name'];
            logo = json['logo'];
        }
    
        Map<String, dynamic> toJson() {
            final Map<String, dynamic> data = new Map<String, dynamic>();
            data['id'] = this.id;
            data['name'] = this.name;
            data['logo'] = this.logo;
            return data;
        }
    }
    

    【讨论】:

    • 我做了这样的事情,但有一件事没有奏效,如何访问或在我的 getTeams 方法中更改什么?有些东西肯定要改变
    • teams[index].transfers[index].teams.teamIn.name ,当我使用它访问数据时,我仍然得到一个结果
    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 2019-03-30
    • 2021-05-02
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    • 2020-08-13
    相关资源
    最近更新 更多