gpt4 book ai didi

api - Flutter:Futurebuilder从类中获取空值

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

我正在尝试制作实时比分应用程序,我有一个由quiqtype.io从json创建的模型:

import 'dart:convert';

Live liveFromJson(String str) => Live.fromJson(json.decode(str));

String liveToJson(Live data) => json.encode(data.toJson());

class Live {
Live({
this.success,
this.data,
});

bool success;
Data data;

factory Live.fromJson(Map<String, dynamic> json) => Live(
success: json["success"],
data: Data.fromJson(json["data"]),
);

Map<String, dynamic> toJson() => {
"success": success,
"data": data.toJson(),
};
}

class Data {
Data({
this.fixtures,
this.nextPage,
this.prevPage,
});

List<Fixture> fixtures;
String nextPage;
bool prevPage;

factory Data.fromJson(Map<String, dynamic> json) => Data(
fixtures: List<Fixture>.from(
json["fixtures"].map((x) => Fixture.fromJson(x))),
nextPage: json["next_page"],
prevPage: json["prev_page"],
);

Map<String, dynamic> toJson() => {
"fixtures": List<dynamic>.from(fixtures.map((x) => x.toJson())),
"next_page": nextPage,
"prev_page": prevPage,
};
}

class Fixture {
Fixture({
this.id,
this.date,
this.time,
this.round,
this.homeName,
this.awayName,
this.location,
this.leagueId,
this.competitionId,
this.homeId,
this.awayId,
this.competition,
this.league,
});

String id;
DateTime date;
String time;
String round;
String homeName;
String awayName;
String location;
String leagueId;
String competitionId;
String homeId;
String awayId;
Competition competition;
League league;

factory Fixture.fromJson(Map<String, dynamic> json) => Fixture(
id: json["id"],
date: DateTime.parse(json["date"]),
time: json["time"],
round: json["round"],
homeName: json["home_name"],
awayName: json["away_name"],
location: json["location"],
leagueId: json["league_id"],
competitionId: json["competition_id"],
homeId: json["home_id"],
awayId: json["away_id"],
competition: Competition.fromJson(json["competition"]),
league: json["league"] == null ? null : League.fromJson(json["league"]),
);

Map<String, dynamic> toJson() => {
"id": id,
"date":
"${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}",
"time": time,
"round": round,
"home_name": homeName,
"away_name": awayName,
"location": location,
"league_id": leagueId,
"competition_id": competitionId,
"home_id": homeId,
"away_id": awayId,
"competition": competition.toJson(),
"league": league == null ? null : league.toJson(),
};
}

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

String id;
String name;

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

Map<String, dynamic> toJson() => {
"id": id,
"name": name,
};
}

class League {
League({
this.id,
this.name,
this.countryId,
});

String id;
String name;
String countryId;

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

Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"country_id": countryId,
};
}
我创建API服务类:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:myexpect/models/match_fixture.dart';

class Api {
Future<Live> get_fixture() async {
var fixture_model = null;
var client = http.Client();
try {
var url =
'https://livescore-api.com/api-client/fixtures/matches.json?key=xxxxxxC&secret=yyyyy&page=1';
var response = await client.get(url);
if (response.statusCode == 200) {
var jsonString = response.body;
var jsonMap = json.decode(jsonString);
fixture_model = Live.fromJson(jsonMap);
print(jsonMap ): //--- printed the list in console successfully
}
} catch (Exception) {
return fixture_model;
}
}
}
我现在正在尝试在此页面的将来构建中查看此数据:
import 'package:flutter/material.dart';
import '../services/live_score_api.dart';
import '../models/match_fixture.dart';

class LiveScore extends StatefulWidget {
@override
_LiveScoreState createState() => _LiveScoreState();
}

class _LiveScoreState extends State<LiveScore> {
Future<Live> _fixtures;

@override
void initState() {
_fixtures = Api().get_fixture();

super.initState();
}

@override
Widget build(BuildContext context) {
return FutureBuilder<Live>(
future: _fixtures,
builder: (ctx, snapshot) {
if (snapshot.connectionState == ConnectionState.none ||
snapshot.connectionState == ConnectionState.waiting ||
snapshot.connectionState == ConnectionState.active ||
snapshot.data == null) {
return Container(
child: Text('Loading.......'),
);
} else {
return ListView.builder(
itemCount: snapshot.data.data.fixtures.length,
itemBuilder: (ctx, index) {
var data = snapshot.data.data.fixtures[index];
return Text(data.time);
});
}
},
);
}
}
当我加载此页面时,在控制台上成功打印的数据列表,但 future builder 收到null,因此仅查看了文本“Loading ...”,并且未发现任何错误

最佳答案

您想像这样实现 future builder :

    return FutureBuilder<Live>(
future: _fixtures,
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
case ConnectionState.active:
// Loading widget
return CircularProgressIndicator();
case ConnectionState.done:
if (snapshot.hasError) {
// return error widget
}
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.data.fixtures.length,
itemBuilder: (ctx, index) {
var data = snapshot.data.data.fixtures[index];
return Text(data.time);
});
}
}
},
);
最重要的是,您捕获了异常,但没有引发异常。这样就不会抛出错误。您想在 future builder 中了解哪些内容。我建议抛出异常。

关于api - Flutter:Futurebuilder从类中获取空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63795251/

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