我得到一个 - 类型 'List<dynamic>' 不是类型 'Map<String, dynamic>' 错误的子类型



我有一个json中的地图列表,我试图在列表上渲染'title'。

我通过api (http.get)读取数据,然后解析它。

我想在列表中显示标题。

这是我的代码…

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

获取数据

Future<Welcome> fetchAlbum() async {
final response = await http.get('https://jsonplaceholder.typicode.com/posts');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Welcome.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}

转换为json

List<Welcome> welcomeFromJson(String str) =>
List<Welcome>.from(json.decode(str).map((x) => Welcome.fromJson(x)));
String welcomeToJson(List<Welcome> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

模型类欢迎

class Welcome {
Welcome({
this.userId,
this.id,
this.title,
this.body,
});
int userId;
int id;
String title;
String body;
factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
userId: json["userId"],
id: json["id"],
title: json["title"],
body: json["body"],
);
Map<String, dynamic> toJson() => {
"userId": userId,
"id": id,
"title": title,
"body": body,
};
}
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future<Welcome> futureAlbum;
@override
void initState() {
super.initState();
futureAlbum = fetchAlbum();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Welcome>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return new Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
),
),
);
}
}

我得到一个错误说"类型"List"不是类型"Map<String,>' "的子类型

fetchAlbum函数更改为

Future<List<Welcome>> fetchAlbum() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/posts');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
// return Welcome.fromJson(jsonDecode(response.body));
var jsonData = jsonDecode(response.body);
List<Welcome> welcome = [];
for (var v in jsonData) {
Welcome w1 = Welcome(
userId: v['userId'],
id: v['id'],
title: v['title'],
body: v['body']);
welcome.add(w1);
}
return welcome;
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}

futurebuilder小部件将是这个

child: FutureBuilder(
future: fetchAlbum(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Container(
margin: EdgeInsets.all(8),
child: Column(
children: [
Text("User Id = ${snapshot.data[index].userId}"),
Text("Id = ${snapshot.data[index].id}"),
Text("Title = ${snapshot.data[index].title}"),
Text("Body = ${snapshot.data[index].body}"),
],
),
);
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),

相关内容

最新更新