简体   繁体   中英

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?", }, ]

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.

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: `

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:

`

class Post {

  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:

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. You are again trying to decode the decode the response body but the jsonDecode expects string type as parameter.

Simply, all you need to do is remove the jsonDecode

From

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

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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