【发布时间】:2019-10-16 20:51:29
【问题描述】:
自从我昨天开始对我的项目进行编码以来,我面临着同样的问题,该项目的一部分是从给定的 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();
},
),
),
),
);
}
}
我只得到以下消息:
类型列表动态不是映射字符串类型的子类型,动态
任何帮助将不胜感激。
提前致谢。
【问题讨论】: