Api 调用抛出错误类型 'Null' 不是类型 'List<Quotes>' 的子类型
Api call throwing error type 'Null' is not a subtype of type 'List<Quotes>'
这是我的 api 电话。
class Httpservice {
final Uri postURL = Uri.parse(
"https://quotes.rest/qod?category=inspire",
);
static dynamic quoteOfTheDay;
Future<List<Quotes>> getQuotes() async {
Response res = await get(postURL);
final jsonItems = json.decode(res.body)["contents"]["quotes"];
List<Quotes> quote = jsonItems.map<Quotes>((json) {
return Quotes.fromJson(json);
}).toList();
quoteOfTheDay = quote;
return quote;
}
}
这是展示页面
class PostsPage extends StatelessWidget {
final List<Quotes> quote = Httpservice.quoteOfTheDay;
PostsPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("quotes"),
),
body: FutureBuilder(
//future: httpService.getQuotes(),
builder: (BuildContext context, AsyncSnapshot<List<Quotes>>
snapshot) {
if (snapshot.hasData) {
//Future.delayed(const Duration(seconds: 5));
// Quote? quotes = snapshot.data;
if (kDebugMode) {
print('" ${quote[0].quote} ?? '' "');
}
return Text('" ${quote[0].quote} ?? '' "');
} else {
return Scaffold(
body: Column(children: const [
SizedBox(height: 400.0),
Center(
child: CircularProgressIndicator(
color: Colors.black,
),
),
SizedBox(
height: 10.0,
),
Text('loading')
]),
);
}
},
),
);
}
}
这是模型数据
class Quotes {
String? quote;
String? length;
String? author;
List<String>? tags;
String? category;
String? language;
String? date;
String? permalink;
String? id;
String? background;
String? title;
Quotes(
{this.quote,
this.length,
this.author,
this.tags,
this.category,
this.language,
this.date,
this.permalink,
this.id,
this.background,
this.title});
Quotes.fromJson(Map<String, dynamic> json) {
quote = json['quote'];
length = json['length'];
author = json['author'];
tags = json['tags'].cast<String>();
category = json['category'];
language = json['language'];
date = json['date'];
permalink = json['permalink'];
id = json['id'];
background = json['background'];
title = json['title'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['quote'] = quote;
data['length'] = length;
data['author'] = author;
data['tags'] = tags;
data['category'] = category;
data['language'] = language;
data['date'] = date;
data['permalink'] = permalink;
data['id'] = id;
data['background'] = background;
data['title'] = title;
return data;
}
}
模型数据 2
import 'quotes.dart';
class Contents {
List<Quotes>? quotes;
Contents({this.quotes});
Contents.fromJson(Map<String, dynamic> json) {
if (json['quotes']) {
quotes = <Quotes>[];
json['quotes'].forEach((v) {
quotes!.add(Quotes.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
if (quotes != null) {
data['quotes'] = quotes!.map((v) => v.toJson()).toList();
}
return data;
}
}
这是所有主要页面的代码。当我尝试显示 class 引用中的引用时,什么也没有显示。当我尝试导航到显示 page.Another 异常时,我不断收到此错误:类型 'Null' 不是类型 'List' 的子类型
我真的不知道我做错了什么,我崩溃了。
我认为问题出在这一行 final List<Quotes> quote = Httpservice.quoteOfTheDay;
。由于变量 quote
需要 List<Quotes>
而您正在调用 Httpservice.quoteOfTheDay
返回空值。
相反,您应该调用 Httpservice.getQuotes()
,因为此方法返回预期值。
final List<Quotes> quote = Httpservice.getQuotes();
您正在使用 FutureBuilder 获取数据。返回的快照确实有列表,但是您在 FutureBuilder 之前得到 quoteOfTheDay,它是空的。最好的方法是在加载数据时通过快照获取数据。
这是工作代码:
帖子页面:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'http_service.dart';
import 'model_quote.dart';
class PostsPage extends StatelessWidget {
PostsPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("quotes"),
),
body: FutureBuilder(
future: Httpservice().getQuotes(),
builder: (BuildContext context, AsyncSnapshot<List<Quotes>> snapshot) {
if (snapshot.hasData) {
//Future.delayed(const Duration(seconds: 5));
// Quote? quotes = snapshot.data;
final List<Quotes> quotes = snapshot.data!;
return ListView.builder(
itemCount: quotes.length,
itemBuilder: (ctx, i) {
return Container(
child: Text('" ${quotes[0].quote} ?? ' ' "'));
});
} else {
return Column(children: const [
SizedBox(height: 400.0),
Center(
child: CircularProgressIndicator(
color: Colors.black,
),
),
SizedBox(
height: 10.0,
),
Text('loading')
]);
}
},
),
);
}
}
HTTP 服务
import 'dart:convert';
import 'package:http/http.dart';
import 'model_quote.dart';
class Httpservice {
final Uri postURL = Uri.parse(
"https://quotes.rest/qod?category=inspire",
);
Future<List<Quotes>> getQuotes() async {
Response res = await get(postURL);
final jsonItems = json.decode(res.body)["contents"]["quotes"];
List<Quotes> quote = jsonItems.map<Quotes>((json) {
print(json);
return Quotes.fromJson(json);
}).toList();
return quote;
}
}
这是我的 api 电话。
class Httpservice {
final Uri postURL = Uri.parse(
"https://quotes.rest/qod?category=inspire",
);
static dynamic quoteOfTheDay;
Future<List<Quotes>> getQuotes() async {
Response res = await get(postURL);
final jsonItems = json.decode(res.body)["contents"]["quotes"];
List<Quotes> quote = jsonItems.map<Quotes>((json) {
return Quotes.fromJson(json);
}).toList();
quoteOfTheDay = quote;
return quote;
}
}
这是展示页面
class PostsPage extends StatelessWidget {
final List<Quotes> quote = Httpservice.quoteOfTheDay;
PostsPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("quotes"),
),
body: FutureBuilder(
//future: httpService.getQuotes(),
builder: (BuildContext context, AsyncSnapshot<List<Quotes>>
snapshot) {
if (snapshot.hasData) {
//Future.delayed(const Duration(seconds: 5));
// Quote? quotes = snapshot.data;
if (kDebugMode) {
print('" ${quote[0].quote} ?? '' "');
}
return Text('" ${quote[0].quote} ?? '' "');
} else {
return Scaffold(
body: Column(children: const [
SizedBox(height: 400.0),
Center(
child: CircularProgressIndicator(
color: Colors.black,
),
),
SizedBox(
height: 10.0,
),
Text('loading')
]),
);
}
},
),
);
}
}
这是模型数据
class Quotes {
String? quote;
String? length;
String? author;
List<String>? tags;
String? category;
String? language;
String? date;
String? permalink;
String? id;
String? background;
String? title;
Quotes(
{this.quote,
this.length,
this.author,
this.tags,
this.category,
this.language,
this.date,
this.permalink,
this.id,
this.background,
this.title});
Quotes.fromJson(Map<String, dynamic> json) {
quote = json['quote'];
length = json['length'];
author = json['author'];
tags = json['tags'].cast<String>();
category = json['category'];
language = json['language'];
date = json['date'];
permalink = json['permalink'];
id = json['id'];
background = json['background'];
title = json['title'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['quote'] = quote;
data['length'] = length;
data['author'] = author;
data['tags'] = tags;
data['category'] = category;
data['language'] = language;
data['date'] = date;
data['permalink'] = permalink;
data['id'] = id;
data['background'] = background;
data['title'] = title;
return data;
}
}
模型数据 2
import 'quotes.dart';
class Contents {
List<Quotes>? quotes;
Contents({this.quotes});
Contents.fromJson(Map<String, dynamic> json) {
if (json['quotes']) {
quotes = <Quotes>[];
json['quotes'].forEach((v) {
quotes!.add(Quotes.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
if (quotes != null) {
data['quotes'] = quotes!.map((v) => v.toJson()).toList();
}
return data;
}
}
这是所有主要页面的代码。当我尝试显示 class 引用中的引用时,什么也没有显示。当我尝试导航到显示 page.Another 异常时,我不断收到此错误:类型 'Null' 不是类型 'List' 的子类型 我真的不知道我做错了什么,我崩溃了。
我认为问题出在这一行 final List<Quotes> quote = Httpservice.quoteOfTheDay;
。由于变量 quote
需要 List<Quotes>
而您正在调用 Httpservice.quoteOfTheDay
返回空值。
相反,您应该调用 Httpservice.getQuotes()
,因为此方法返回预期值。
final List<Quotes> quote = Httpservice.getQuotes();
您正在使用 FutureBuilder 获取数据。返回的快照确实有列表,但是您在 FutureBuilder 之前得到 quoteOfTheDay,它是空的。最好的方法是在加载数据时通过快照获取数据。 这是工作代码:
帖子页面:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'http_service.dart';
import 'model_quote.dart';
class PostsPage extends StatelessWidget {
PostsPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("quotes"),
),
body: FutureBuilder(
future: Httpservice().getQuotes(),
builder: (BuildContext context, AsyncSnapshot<List<Quotes>> snapshot) {
if (snapshot.hasData) {
//Future.delayed(const Duration(seconds: 5));
// Quote? quotes = snapshot.data;
final List<Quotes> quotes = snapshot.data!;
return ListView.builder(
itemCount: quotes.length,
itemBuilder: (ctx, i) {
return Container(
child: Text('" ${quotes[0].quote} ?? ' ' "'));
});
} else {
return Column(children: const [
SizedBox(height: 400.0),
Center(
child: CircularProgressIndicator(
color: Colors.black,
),
),
SizedBox(
height: 10.0,
),
Text('loading')
]);
}
},
),
);
}
}
HTTP 服务
import 'dart:convert';
import 'package:http/http.dart';
import 'model_quote.dart';
class Httpservice {
final Uri postURL = Uri.parse(
"https://quotes.rest/qod?category=inspire",
);
Future<List<Quotes>> getQuotes() async {
Response res = await get(postURL);
final jsonItems = json.decode(res.body)["contents"]["quotes"];
List<Quotes> quote = jsonItems.map<Quotes>((json) {
print(json);
return Quotes.fromJson(json);
}).toList();
return quote;
}
}