Flutter 在flatter中对json对象列表进行排序
我是一个新手,我想对来自json数据的列表进行排序,我正在尝试按进球对我的团队数据进行排序,就像大多数得分的团队将是列表中的第一个,第二个。。。。。 直到最后一个 问题是,除了如何访问“目标”属性外,我没有任何想法: teamgoals=球队[球队指数]。联赛排名[0][0]。all.goals.goalsFor 下面是调用teams api的函数:Flutter 在flatter中对json对象列表进行排序,flutter,dart,Flutter,Dart,我是一个新手,我想对来自json数据的列表进行排序,我正在尝试按进球对我的团队数据进行排序,就像大多数得分的团队将是列表中的第一个,第二个。。。。。 直到最后一个 问题是,除了如何访问“目标”属性外,我没有任何想法: teamgoals=球队[球队指数]。联赛排名[0][0]。all.goals.goalsFor 下面是调用teams api的函数: Future<void> getStandings() async { http.Response response =
Future<void> getStandings() async {
http.Response response = await http.get(
'https://v3.football.api-sports.io/standings?league=39&season=2020',
headers: {'x-rapidapi-key': ApiKey.key,
'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) => TeamsJson.fromJson(item))
.toList();
teamgoals = teams[0].league.standings[0][0].all.goals.goalsFor.toString()+" "+"Goals";
teamname = teams[0].league.standings[0][0].team.name.toString();
teamphoto = teams[0].league.standings[0][0].team.logo.toString();
teampoints = teams[0].league.standings[0][0].points.toString()+" "+"Pts";
});
Here the full code of the app:
import 'package:flutter/material.dart';
import 'package:footyappp/Key/Key.dart';
import 'package:footyappp/clubs/Clubs.dart';
import 'package:footyappp/news%20copy/topScorers.dart';
import 'package:footyappp/results/results.dart';
import 'package:footyappp/schedules/schedules.dart';
import 'package:footyappp/stats/player_goals.dart';
import 'package:footyappp/stats/teams_json.dart';
import 'package:footyappp/tables%20copy/league_board.dart';
import 'package:footyappp/stats/player_assists.dart';
import 'package:footyappp/stats/player_red_cards.dart';
import 'package:footyappp/stats/player_yellow_cards.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'assist_json.dart';
import 'goals_json.dart';
class Statss extends StatefulWidget {
@override
_StatssState createState() => _StatssState();
}
class _StatssState extends State<Statss> {
List<AssistsJson> topassists = [];
List<GoalsJson> topgoals = [];
List<TeamsJson> teams = [];
List<String> data = [];
List<Choices> menu = [];
String assister;
String assisterphoto;
String scorerphoto;
String assists;
String goals;
String scorer;
String teamgoals;
String teamname;
String teamphoto;
String teampoints;
Future<void> getScorers() async {
http.Response response = await http.get(
'https://v3.football.api-sports.io/players/topscorers?league=39&season=2020',
headers: {'x-rapidapi-key': ApiKey.key,
'x-rapidapi-host':'v3.football.api-sports.io'});
String body = response.body;
var data = jsonDecode(body);
List<dynamic> clubList = data['response'];
setState(() {
topgoals = clubList
.map((dynamic item) => GoalsJson.fromJson(item))
.toList();
goals = topgoals[0].statistics[0].goals.total.toString();
scorer = topgoals[0].player.name+" "+topgoals[0].player.firstname;
scorerphoto = topgoals[0].player.photo;
});
}
Future<void> getStandings() async {
http.Response response = await http.get(
'https://v3.football.api-sports.io/standings?league=39&season=2020',
headers: {'x-rapidapi-key': ApiKey.key,
'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) => TeamsJson.fromJson(item))
.toList();
teamgoals = teams[0].league.standings[0][0].all.goals.goalsFor.toString()+" "+"Goals";
teamname = teams[0].league.standings[0][0].team.name.toString();
teamphoto = teams[0].league.standings[0][0].team.logo.toString();
teampoints = teams[0].league.standings[0][0].points.toString()+" "+"Pts";
});
}
Future<void> getAssisters() async {
http.Response response = await http.get(
'https://v3.football.api-sports.io/players/topassists?league=39&season=2020',
headers: {'x-rapidapi-key': ApiKey.key,
'x-rapidapi-host':'v3.football.api-sports.io'});
String body = response.body;
var data = jsonDecode(body);
List<dynamic> clubList = data['response'];
setState(() {
topassists = clubList
.map((dynamic item) => AssistsJson.fromJson(item))
.toList();
assists = topassists[0].statistics[0].goals.assists.toString();
assister = topassists[0].player.name+" "+topassists[0].player.firstname;
assisterphoto = topassists[0].player.photo;
});
}
@override
void initState() {
super.initState();
getScorers();
getAssisters();
getStandings();
}
List<String> images = [
"Assets/tt.jpg",
"Assets/qatarairways.jpg",
"Assets/LOGO_Danao.jpg",
"Assets/delice.jpg"
];
@override
Widget build(BuildContext context) {
List<Choices> menu = [
Choices("Top Scorer: ", goals.toString(), topgoals[0].player.name,topgoals[0].player.photo.toString()),
Choices("Top Assister: ", assists.toString(), topassists[0].player.name,topassists[0].player.photo.toString()),
Choices("Top Team Goals ", teamgoals.toString(), "",teamphoto.toString()),
Choices("1 st Team ", teampoints.toString(), "",teamphoto.toString()),
];
return teams.length == 0 || topassists.length == 0 || topgoals.length == 0
? Container(
color: Colors.white,
child: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
Color(0xFFe70066),
),
),
),
)
:Scaffold(
appBar: AppBar(
title: Text("Stats"),
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: ListView(
children: [
SizedBox(
height: 20,
),
Container(
margin: EdgeInsets.fromLTRB(10, 0, 0, 0),
child: Text(
"Statistiques",
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.w900,
color: Colors.white),
),
),
SizedBox(
height: 30,
),
Container(
padding: EdgeInsets.all(12.0),
child: GridView.builder(
shrinkWrap: true,
itemCount: menu.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 1.0,
mainAxisSpacing: 1.0),
itemBuilder: (BuildContext context, int index) {
return Card(
color: Colors.black,
elevation: 4.0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0),
),
child: Container(
//padding: EdgeInsets.all(16.0),
child:
Column(
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(30, 10, 30, 10),
height: 100,
width: 100,
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
image: NetworkImage(menu[index].image),
fit: BoxFit.fill
),
),
),
Container(
padding: EdgeInsets.all(7.0),
width: double.infinity,
child:
Center(
child: Text(menu[index].title+" "+menu[index].name,style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w900,
color: Colors.white),),
)
),
Container(
padding: EdgeInsets.all(7.0),
width: double.infinity,
child: Center(
child: Text(menu[index].record, style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.w900,
color: Colors.white),),
)
),
],
),
),
);
},
),
),
Container(
margin: EdgeInsets.fromLTRB(15, 30, 15, 0),
child: Column(
children: [
SizedBox(
height: 1,
),
ButtonTheme(
minWidth: double.infinity,
height: 40,
child: RaisedButton(
child: Align(
child: Text(
"Top Scorers",
style: TextStyle(fontSize: 17),
textAlign: TextAlign.right,
),
alignment: Alignment.centerLeft,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Scorers()),
);
},
color: Colors.grey.shade300,
textColor: Colors.black,
padding: EdgeInsets.fromLTRB(15, 8, 8, 8),
splashColor: Colors.green,
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0))),
),
SizedBox(
height: 1,
),
ButtonTheme(
minWidth: double.infinity,
height: 40,
child: RaisedButton(
child: Align(
child: Text(
"Top Assists",
style: TextStyle(fontSize: 17),
textAlign: TextAlign.right,
),
alignment: Alignment.centerLeft,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Assists()),
);
},
color: Colors.grey.shade300,
textColor: Colors.black,
padding: EdgeInsets.fromLTRB(15, 8, 8, 8),
splashColor: Colors.green,
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0))),
),
SizedBox(
height: 1,
),
ButtonTheme(
minWidth: double.infinity,
height: 40,
child: RaisedButton(
child: Align(
child: Text(
"Yellow Cards",
style: TextStyle(fontSize: 17),
textAlign: TextAlign.right,
),
alignment: Alignment.centerLeft,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => YellowCards()),
);
},
color: Colors.grey.shade300,
textColor: Colors.black,
padding: EdgeInsets.fromLTRB(15, 8, 8, 8),
splashColor: Colors.green,
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0))),
),
SizedBox(
height: 1,
),
ButtonTheme(
minWidth: double.infinity,
height: 40,
child: RaisedButton(
child: Align(
child: Text(
"Red Cards",
style: TextStyle(fontSize: 17),
textAlign: TextAlign.right,
),
alignment: Alignment.centerLeft,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => RedCards()),
);
},
color: Colors.grey.shade300,
textColor: Colors.black,
padding: EdgeInsets.fromLTRB(15, 8, 8, 8),
splashColor: Colors.green,
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0))),
),
SizedBox(
height: 1,
),
ButtonTheme(
minWidth: double.infinity,
height: 40,
child: RaisedButton(
child: Align(
child: Text(
"Team Stats",
style: TextStyle(fontSize: 17),
textAlign: TextAlign.right,
),
alignment: Alignment.centerLeft,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => LeagueBoard()),
);
},
color: Colors.grey.shade300,
textColor: Colors.black,
padding: EdgeInsets.fromLTRB(15, 8, 8, 8),
splashColor: Colors.green,
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0))),
),
SizedBox(
height: 30,
)
],
),
),
Container(
padding: EdgeInsets.all(12.0),
child: GridView.builder(
shrinkWrap: true,
itemCount: images.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 4.0,
mainAxisSpacing: 4.0),
itemBuilder: (BuildContext context, int index) {
return Image.asset(images[index]);
},
),
),
SizedBox(
height: 30,
)
],
),
));
}
}
class Choices {
String title;
String record;
String name;
String image;
Choices(this.title,this.record,this.name,this.image);
}
My problem is that i can not sort my list of teams by goals or wins or anything , i am trying to find the way about how to do it,
Here my model class using quicktype:
// To parse this JSON data, do
//
// final teamsJson = teamsJsonFromJson(jsonString);
import 'dart:convert';
List<TeamsJson> teamsJsonFromJson(String str) => List<TeamsJson>.from(json.decode(str).map((x) => TeamsJson.fromJson(x)));
String teamsJsonToJson(List<TeamsJson> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class TeamsJson {
TeamsJson({
this.league,
});
League league;
factory TeamsJson.fromJson(Map<String, dynamic> json) => TeamsJson(
league: League.fromJson(json["league"]),
);
Map<String, dynamic> toJson() => {
"league": league.toJson(),
};
}
class League {
League({
this.id,
this.name,
this.country,
this.logo,
this.flag,
this.season,
this.standings,
});
int id;
String name;
String country;
String logo;
String flag;
int season;
List<List<Standing>> standings;
factory League.fromJson(Map<String, dynamic> json) => League(
id: json["id"],
name: json["name"],
country: json["country"],
logo: json["logo"],
flag: json["flag"],
season: json["season"],
standings: List<List<Standing>>.from(json["standings"].map((x) => List<Standing>.from(x.map((x) => Standing.fromJson(x))))),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"country": country,
"logo": logo,
"flag": flag,
"season": season,
"standings": List<dynamic>.from(standings.map((x) => List<dynamic>.from(x.map((x) => x.toJson())))),
};
}
class Standing {
Standing({
this.rank,
this.team,
this.points,
this.goalsDiff,
this.group,
this.form,
this.status,
this.description,
this.all,
this.home,
this.away,
this.update,
});
int rank;
Team team;
int points;
int goalsDiff;
String group;
String form;
String status;
String description;
All all;
All home;
All away;
DateTime update;
factory Standing.fromJson(Map<String, dynamic> json) => Standing(
rank: json["rank"],
team: Team.fromJson(json["team"]),
points: json["points"],
goalsDiff: json["goalsDiff"],
group: json["group"],
form: json["form"],
status: json["status"],
description: json["description"],
all: All.fromJson(json["all"]),
home: All.fromJson(json["home"]),
away: All.fromJson(json["away"]),
update: DateTime.parse(json["update"]),
);
Map<String, dynamic> toJson() => {
"rank": rank,
"team": team.toJson(),
"points": points,
"goalsDiff": goalsDiff,
"group": group,
"form": form,
"status": status,
"description": description,
"all": all.toJson(),
"home": home.toJson(),
"away": away.toJson(),
"update": update.toIso8601String(),
};
}
class All {
All({
this.played,
this.win,
this.draw,
this.lose,
this.goals,
});
int played;
int win;
int draw;
int lose;
Goals goals;
factory All.fromJson(Map<String, dynamic> json) => All(
played: json["played"],
win: json["win"],
draw: json["draw"],
lose: json["lose"],
goals: Goals.fromJson(json["goals"]),
);
Map<String, dynamic> toJson() => {
"played": played,
"win": win,
"draw": draw,
"lose": lose,
"goals": goals.toJson(),
};
}
class Goals {
Goals({
this.goalsFor,
this.against,
});
int goalsFor;
int against;
factory Goals.fromJson(Map<String, dynamic> json) => Goals(
goalsFor: json["for"],
against: json["against"],
);
Map<String, dynamic> toJson() => {
"for": goalsFor,
"against": against,
};
}
class Team {
Team({
this.id,
this.name,
this.logo,
});
int id;
String name;
String logo;
factory Team.fromJson(Map<String, dynamic> json) => Team(
id: json["id"],
name: json["name"],
logo: json["logo"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"logo": logo,
};
}
Future getStandings()异步{
http.Response-Response=等待http.get(
'https://v3.football.api-sports.io/standings?league=39&season=2020',
标题:{'x-rapidapi-key':ApiKey.key,
'x-rapidapi-host':'v3.football.api sports.io';
字符串体=response.body;
var数据=jsonDecode(主体);
List clubList=data['response'];
设置状态(){
团队=俱乐部会员
.map((动态项)=>TeamsJson.fromJson(项))
.toList();
teamgoals=teams[0]。league.standings[0][0]。all.goals.goalsFor.toString()+“”+“goals”;
teamname=teams[0]。league.standings[0][0]。team.name.toString();
teamphoto=teams[0]。league.standings[0][0]。team.logo.toString();
teampoints=团队[0]。联盟。排名[0][0]。积分。toString()+“”+“Pts”;
});
下面是应用程序的完整代码:
进口“包装:颤振/材料.省道”;
导入“包:footyappp/Key/Key.dart”;
导入“包:footyappp/clubs/clubs.dart”;
导入“包:footyappp/news%20copy/topcorers.dart”;
导入“包:footyappp/results/results.dart”;
导入“包:footyappp/schedules/schedules.dart”;
导入“包:footyappp/stats/player_goals.dart”;
导入“package:footyappp/stats/teams_json.dart”;
导入“包装:footyappp/表格%20份/联盟板.dart”;
导入“套装:footyappp/stats/player_assesss.dart”;
导入“套装:footyappp/stats/player_red_cards.dart”;
导入“套装:footyappp/stats/player_yellow_cards.dart”;
导入“dart:convert”;
将“package:http/http.dart”导入为http;
导入“assist_json.dart”;
导入“goals_json.dart”;
类Statss扩展StatefulWidget{
@凌驾
_StatssState createState()=>\u StatssState();
}
类_StatssState扩展状态{
列表帮助=[];
列出topgoals=[];
列出团队=[];
列表数据=[];
列表菜单=[];
弦乐助听器;
字符串助理照片;
弦乐记分本;
弦乐助攻;
串目标;
弦乐得分手;
串团队目标;
字符串组名;
字符串团队照片;
串组点;
未来的getScorers()异步{
http.Response-Response=等待http.get(
'https://v3.football.api-sports.io/players/topscorers?league=39&season=2020',
标题:{'x-rapidapi-key':ApiKey.key,
'x-rapidapi-host':'v3.football.api sports.io';
字符串体=response.body;
var数据=jsonDecode(主体);
List clubList=data['response'];
设置状态(){
topgoals=clubList
.map((动态项)=>GoalsJson.fromJson(项))
.toList();
goals=topgoals[0]。统计信息[0]。goals.total.toString();
scorer=topgoals[0]。player.name+“”+topgoals[0]。player.firstname;
Scorephoto=topgoals[0]。player.photo;
});
}
Future getStandings()异步{
http.Response-Response=等待http.get(
'https://v3.football.api-sports.io/standings?league=39&season=2020',
标题:{'x-rapidapi-key':ApiKey.key,
'x-rapidapi-host':'v3.football.api sports.io';
字符串体=response.body;
var数据=jsonDecode(主体);
List clubList=data['response'];
设置状态(){
团队=俱乐部会员
.map((动态项)=>TeamsJson.fromJson(项))
.toList();
teamgoals=teams[0]。league.standings[0][0]。all.goals.goalsFor.toString()+“”+“goals”;
teamname=teams[0]。league.standings[0][0]。team.name.toString();
teamphoto=teams[0]。league.standings[0][0]。team.logo.toString();
teampoints=团队[0]。联盟。排名[0][0]。积分。toString()+“”+“Pts”;
});
}
未来的getAssisters()异步{
http.Response-Response=等待http.get(
'https://v3.football.api-sports.io/players/topassists?league=39&season=2020',
标题:{'x-rapidapi-key':ApiKey.key,
'x-rapidapi-host':'v3.football.api sports.io';
字符串体=response.body;
var数据=jsonDecode(主体);
List clubList=data['response'];
设置状态(){
topassists=俱乐部会员
.map((动态项)=>AssistsJson.fromJson(项))
.toList();
assists=topassists[0]。统计信息[0]。goals.assists.toString();
assister=topassists[0]。player.name+“”+topassists[0]。player.firstname;
assisterphoto=topassists[0]。player.photo;
});
}
@凌驾
void initState(){
super.initState();
getScorers();
getAssisters();
getStandings();
}
列表图像=[
“资产/tt.jpg”,
“资产/qatarairways.jpg”,
“资产/徽标_Danao.jpg”,
“Assets/delice.jpg”
];
@凌驾
小部件构建(构建上下文){
列表菜单=[
选项(“顶级得分手:”,goals.toString(),topgoals[0]。player.name,topgoals[0]。player.photo.toString()),
选项(“Top Assister:”,assists.toString(),topassists[0]。player.name,topassists[0]。player.photo.toString()),
选项(“顶级团队目标”、teamgoals.toString()、“”、teamphoto.toString()),
选择(一)
class Student implements Comparable {
int marks;
String name ;
Student(this.marks,this.name);
@override
int compareTo(other) {
if (this.marks < other.marks) {
return 1;
}
else if (this.marks > other.marks) {
return -1;
}
else{
return 0;
}
}
}
void main(){
List<Student> myList = [];
myList.add(Student(20,"A1"));
myList.add(Student(-1,"A2"));
myList.add(Student(-340,"A3"));
myList.add(Student(-30,"A4"));
myList.add(Student(2340,"A5"));
print('Before sort');
for(var item in myList){
print(item.marks.toString()+" "+item.name);
}
myList.sort();
print('After sort');
for(var item in myList){
print(item.marks.toString()+" "+item.name);
}
Comparator<Student> nameSorter = (a, b) => a.name.compareTo(b.name);
myList.sort(nameSorter);
print('After sort by name');
for(var item in myList){
print(item.marks.toString()+" "+item.name);
}
}
class League {
int get allGoals {
int sum = 0;
for (int i = 0; i < standings.length; i++) {
for (int j = 0; j < standings[i].length; j++) {
sum += standings[i][j].all.goals.goalsFor;
}
}
return sum;
}
}
teams.sort((t1, t2) {
return t1.league.allGoals > t2.league.allGoals ? 1
: (t1.league.allGoals < t2.league.allGoals -1 : 0);
});