【发布时间】:2020-03-31 00:12:09
【问题描述】:
我正在使用获取 JSON 数组并将其推送到由列表视图读取的 JSON 对象的 HTTP 请求。我很难将 JSON 数组强制转换为 JSON 对象,因此我目前通过json.decode(response.body)[0] 调用每个对象一次。如何将 JSON 数组转换为 JSON 对象并让列表视图读取整个 JSON 对象?
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Post> fetchPost() async {
final url = <my_url>;
final response =
await http.get(url);
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON.
print(json.decode(response.body));
// TODO: Identify a way to convert JSON Array to JSON Object
return Post.fromJson(json.decode(response.body)[0]);
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
class Post {
final String title;
Post({this.title});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
title: json['title']
);
}
}
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future<Post> post;
@override
void initState() {
super.initState();
post = fetchPost();
}
@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<Post>(
future: post,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data.title);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
),
),
);
}
}
【问题讨论】:
-
有没有报错?
-
可以显示json结果吗?
-
你能发布你的json响应吗?
-
JSON 是
[{'id': 1, 'title': 'A'}, {'id': 2, 'title': 'B'}。当我删除响应正文上的索引[0]时,该对象不是Map<String, dynamic>。我想继续删除索引并将整个数组放入一个对象中