简体   繁体   English

获取数据 flutter api

[英]fetch data flutter api

I want to get data from API and I tried the link in postman and its working here it is: [ { "Id": "14", "title": "Facebook vs instagram?", }, { "Id": "15", "title": "Facebook vs instagram?", }, { "Id": "16", "title": "Facebook vs instagram?", }, ]我想从 API 获取数据,我尝试了 postman 中的链接,它在这里工作的是:[ {“Id”:“14”,“title”:“Facebook vs instagram?”,},{“Id”:“ 15", "title": "Facebook vs instagram?", }, { "Id": "16", "title": "Facebook vs instagram?", }, ]

but when I am trying to do a map this error appears: error catch type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List' in type cast.但是当我尝试执行 map 时,会出现此错误:error catch type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List' in type cast。

Here is my code: This error appears in this file and print(recieved) print the same data as postman but the problem in map httpservice.dart: `这是我的代码:此文件中出现此错误并打印(收到)打印与 postman 相同的数据,但 map httpservice.dart 中的问题:`

class HttpService {
  final String postsURL =
      "";

  Future<List<Post>> getPosts() async {
    var request = http.MultipartRequest("POST", Uri.parse(postsURL));

    request.fields.addAll(
      {
        'post_type': "read_user",
        'uid': "27",
      },
    );

    var headers = {
      'token': "aaa",
      'lang': "lang",
    };

    request.headers.addAll(headers);
    List<Post> Posts = [];
    try {
      http.StreamedResponse response = await request.send();

      if (response.statusCode == 200) {
        var response = await http.Response.fromStream(streamedResponse);
final result = jsonDecode(response.body) as List; 

        List<Post> posts = result
            .map(
              (dynamic item) => Post.fromJson(item),
            )
            .toList();

        return Posts;
      } else {
        print("error response $response.statusCode");
      }
    } catch (e) {
      print("error catch $e");
    }
    return Posts;
  }
}

` post_model.dart: ` post_model.dart:

` `

class Post { class后{

  final String Id;
  final String title;

  Post({
    required this.Id,
    required this.title,
  });

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

` post.dart: ` post.dart:

class PostsPage extends StatelessWidget {
  final HttpService httpService = HttpService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Posts"),
      ),
      body: FutureBuilder(
        future: httpService.getPosts(),
        builder: (BuildContext context, AsyncSnapshot<List<Post>> snapshot) {
          if (snapshot.hasData) {
            List<Post> posts = snapshot.data!;
            return ListView(
              children: posts
                  .map(
                    (Post post) => ListTile(
                      title: Text(post.title),
                      subtitle: Text("${post.Id}"),
                    ),
                  )
                  .toList(),
            );
          } else {
            return Center(child: CircularProgressIndicator());
          }
        },
      ),
    );
  }
}

The http package gives the data as json in default. http package 默认数据为 json。 You are again trying to decode the decode the response body but the jsonDecode expects string type as parameter.您再次尝试对响应正文进行解码,但 jsonDecode 需要字符串类型作为参数。

Simply, all you need to do is remove the jsonDecode简单地说,您需要做的就是删除 jsonDecode

From

final result = jsonDecode(response.body) as List; 

to

final result = response.body as Map<String, dynamic>; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM