flutter - '列表' 不是类型 'Map 的子类型'
问题描述
我正在尝试从 api https://type.fit/api/quotes获取报价,但它没有显示,它向我显示了这个错误:type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
这是 json 的模型类:
class Autogenerated {
String text;
String author;
Autogenerated({this.text, this.author});
factory Autogenerated.fromJson(Map<String, dynamic> json) {
return Autogenerated(
text: json['text'],
author: json['author'],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['text'] = this.text;
data['author'] = this.author;
return data;
}
}
现在我使用了这个import 'package:http/http.dart' as http;
,现在我使用了http.get
调用 api,如下所示:
final response =
await http.get('https://type.fit/api/quotes');
这是它的完整代码...
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:quotes_season/modal.dart';
import 'package:http/http.dart' as http;
class Quote extends StatefulWidget {
@override
_QuoteState createState() => _QuoteState();
}
Future<Autogenerated> fetchAlbum() async {
final response =
await http.get('https://type.fit/api/quotes');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Autogenerated.fromJson(json.decode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
class _QuoteState extends State<Quote> {
Future<Autogenerated> futureAutogenerated;
@override
void initState() {
super.initState();
futureAutogenerated = fetchAlbum();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: fetchAlbum(),
builder: (context, snapshot) {
if(snapshot.hasData){
return Center(child: Text(snapshot.data.title));
}else if(snapshot.hasError){
return Center(child: Text("${snapshot.error}"));
}
return CircularProgressIndicator();
}),
);
}
}
解决方案
您正在尝试从 API 端点获取 JSON 列表,但您的解析代码正在解析单个 JSON 对象。
您的方法必须更改为返回对象列表:
Future<List<Autogenerated>> fetchAlbum() async {
final response =
await http.get('https://type.fit/api/quotes');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
List jsonList = json.decode(response.body)
List list = List.generate(jsonList.length, (i) => Autogenerated.fromJson(jsonList[i]));
return list;
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
更改 API 调用后,您的状态类应如下所示:
class _QuoteState extends State<Quote> {
Future<List<Autogenerated>> futureAutogenerated;
@override
void initState() {
super.initState();
futureAutogenerated = fetchAlbum();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: futureAutogenerated,
builder: (context, snapshot) {
if(snapshot.hasData){
List<Autogenerated> list = snapshot.data;
Autogenerated firstItem = list[0];
return Center(child: Text(firstItem.text));
}else if(snapshot.hasError){
return Center(child: Text("${snapshot.error}"));
}
return CircularProgressIndicator();
}),
);
}
}
如果您的目标是创建元素列表,而不是单个元素,则需要修改正在使用的小部件:
return Center(child: Text(firstItem.text));
而是做这样的事情:
List<Autogenerated> list = snapshot.data;
return ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) => Text(list[index]),
);
推荐阅读
- pandas - 如何对 GroupBy 和连续日期条件下的值求和?
- linux - Execute bash command in jenkinsfile groovy
- reactjs - how to solve the emotion problem with typescript and typescript
- laravel - Docker Nginx PHP Laravel curl failed to connect to api.localhost port 80. Connection refused
- javascript - UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block
- r - Configuring max iterations in metaMDS
- transactions - Quarkus: Transaction-Listener
- php - 如何在 WordPress 中检索帖子的 Tag_ID?
- javascript - Hammer.js on pinchmove keep the centre of zoom in the centre of screen
- javascript - Sidebar nav menu submenu is collapsing on page reload in Angular 11