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

标签 json api http flutter

自从我昨天开始在我的项目上编码以来,我面临着同样的问题,该项目的一部分是从给定的 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/

相关文章:

php - Jquery/Php 使用 Ajax POST 返回处理状态

javascript - 如何格式化 JSON 中的引用以执行链接

javascript - 如何使用ajax正确地将json发送到RestController?

javascript - 带有 Google API 狂热字符的 Django 和 JSON POST

python - 带有 python 客户端的 Duo Security API

java - 如何从java中的HttpServletRequest中获取调用了哪个端点操作?

api - 获取 URL 的推文数量的官方方法

javascript - vue.js 从 REST API 获取数据的问题

Django 错误 : Invalid HTTP_HOST header: u'/run/myprojectname/gunicorn. socks :'

python - 如何向http请求添加数据