gpt4 book ai didi

json - 如何从 Flutter 中的 API 获取 JSON 数据

转载 作者:IT王子 更新时间:2023-10-29 07:18:59 25 4
gpt4 key购买 nike

自从我昨天开始在我的项目上编码以来,我面临着同样的问题,该项目的一部分是从给定的 api 获取一些 json 数据。

我的 api 链接是:http://alkadhum-col.edu.iq/wp-json/wp/v2/posts?_embed

我正在研究 flutter SDK,我很困惑为什么它不适合我!我的工作是只获取链接、标题和 source_url 对象,但我无法获取它。

我在 flutter 文档中尝试了以下代码
https://flutter.dev/docs/cookbook/networking/fetch-data根据我的需要修改后没有得到任何数据。

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

Future<Post> fetchPost() async {
final response =
await http.get('http://alkadhum-col.edu.iq/wp-json/wp/v2/posts/');

if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return Post.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}

class Post {

final int id;
String title;
String link;


Post({this.id, this.title, this.link});

factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id'],
title: json['title'].toString(),
link: json['link'].toString()
);
}
}

void main() => runApp(MyApp(post: fetchPost()));

class MyApp extends StatelessWidget {
final Future<Post> post;

MyApp({Key key, this.post}) : super(key: key);

@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.link);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}

// By default, show a loading spinner
return CircularProgressIndicator();
},
),
),
),
);
}
}

我只收到下面的信息:
Type List dynamic 不是 Map String 类型的子类型,dynamic

任何帮助将不胜感激。
提前致谢。

最佳答案

您的 JSON 响应类型为 List<dynamic>但你正在接受 Map String, dynamic 的回复但你可以这样做

     import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:clickmeetplay/iam/user/postbean.dart';
import 'package:http/http.dart' as http;

class PostHome extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(body: PostScreen(),),);
}
}

class PostScreen extends StatefulWidget {
@override
_PostScreenState createState() => _PostScreenState();
}

class _PostScreenState extends State<PostScreen> {

List<Post> _postList =new List<Post>();

Future<List<Post> > fetchPost() async {
final response =
await http.get('http://alkadhum-col.edu.iq/wp-json/wp/v2/posts/');

if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
List<dynamic> values=new List<dynamic>();
values = json.decode(response.body);
if(values.length>0){
for(int i=0;i<values.length;i++){
if(values[i]!=null){
Map<String,dynamic> map=values[i];
_postList .add(Post.fromJson(map));
debugPrint('Id-------${map['id']}');
}
}
}
return _postList;

} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
@override
Widget build(BuildContext context) {
return Container();
}

@override
void initState() {

fetchPost();

}
}

bean 类

class Post {

final int id;
String title;
String link;


Post({this.id, this.title, this.link});

factory Post.fromJson(Map<String, dynamic> json) {
return Post(
id: json['id'],
title: json['title'].toString(),
link: json['link'].toString()
);
}
}

enter image description here

关于json - 如何从 Flutter 中的 API 获取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56391114/

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