gpt4 book ai didi

flutter - Flutter/Dart Json解析

转载 作者:行者123 更新时间:2023-12-03 04:40:48 24 4
gpt4 key购买 nike

我试图解析这种json类型:

    "teams": [
{
"id": 1,
"name": "New Jersey Devils",
"link": "/api/v1/teams/1",
"venue": {
"name": "Prudential Center",
"link": "/api/v1/venues/null",
"city": "Newark",
"timeZone": {
"id": "America/New_York",
"offset": -4,
"tz": "EDT"
}
},
"abbreviation": "NJD",
"teamName": "Devils",
"locationName": "New Jersey",
"firstYearOfPlay": "1982",
"division": {
"id": 18,
"name": "Metropolitan",
"nameShort": "Metro",
"link": "/api/v1/divisions/18",
"abbreviation": "M"
}.........
但是我只需要 'id''name'属性。
这是我的模型:
class TeamDetail{
final int id;
final String name;

TeamDetail({this.id, this.name});

factory TeamDetail.fromJson(Map<String, dynamic> json){
return TeamDetail(
id: json["id"],
name: json["name"],
);
}
}
而我的方法:
Future<TeamDetail> getTeamDetail() async{
final response = await http.get('https://statsapi.web.nhl.com/api/v1/teams/1');

if(response.statusCode == 200){

return TeamDetail.fromJson(json.decode(response.body));

}else{
throw Exception("Failed to load");
}
}
但是,当我调用该方法时,我总是收到一个空值。你能帮我吗。
谢谢

最佳答案

您可以复制粘贴运行完整的代码打击
您可以返回List<TeamDetail>程式码片段

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
...
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
copyright: json["copyright"],
teams: List<TeamDetail>.from(
json["teams"].map((x) => TeamDetail.fromJson(x))),
);
工作演示
enter image description here
完整的代码
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));

class Payload {
Payload({
this.copyright,
this.teams,
});

String copyright;
List<TeamDetail> teams;

factory Payload.fromJson(Map<String, dynamic> json) => Payload(
copyright: json["copyright"],
teams: List<TeamDetail>.from(
json["teams"].map((x) => TeamDetail.fromJson(x))),
);
}

class TeamDetail {
TeamDetail({
this.id,
this.name,
});

int id;
String name;

factory TeamDetail.fromJson(Map<String, dynamic> json) => TeamDetail(
id: json["id"],
name: json["name"],
);
}

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);

final String title;

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

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
Future<List<TeamDetail>> _future;

Future<List<TeamDetail>> getTeamDetail() async {
final response =
await http.get('https://statsapi.web.nhl.com/api/v1/teams/1');

if (response.statusCode == 200) {
var payload = payloadFromJson(response.body);
return payload.teams;
} else {
throw Exception("Failed to load");
}
}

@override
void initState() {
_future = getTeamDetail();
super.initState();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder(
future: _future,
builder: (context, AsyncSnapshot<List<TeamDetail>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Card(
elevation: 6.0,
child: Padding(
padding: const EdgeInsets.only(
top: 6.0,
bottom: 6.0,
left: 8.0,
right: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(snapshot.data[index].id.toString()),
Spacer(),
Text(snapshot.data[index].name),
],
),
));
});
}
}
}));
}
}

关于flutter - Flutter/Dart Json解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63257129/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com