【问题标题】:flutter: is it best practice code to fetch list of posts?颤振:获取帖子列表是最佳实践代码吗?
【发布时间】:2019-01-09 15:26:27
【问题描述】:

我从 API 获取帖子的 Flutter 代码是:

Future<List<Posts>> fetchPosts() async {
var url = 'https://*****.com/wp-json/wp/v2/posts';
final response = await http.get(url, headers: {"Accept": 'application/json'});
if (response.statusCode == 200) {
    setState(() {
      var jsonData = json.decode(response.body);
      for (var p in jsonData) {
        Posts post = Posts(
          id: p['id'],
          date: p['date'],
          title: p['title'],
          link: p['link'],
          postViews: p['views'],
          featuredImage: p['featured_image'],
          featuredImageBig: p['featured_image_big'],
          categories: p['categories'],
          comments: p['comments'],
          content: p['content'],
        );
        posts.add(post);
      }
    });      
} 
}}

我问是获取帖子列表的最佳实践代码吗?

提前感谢

【问题讨论】:

    标签: api dart flutter


    【解决方案1】:

    假设您有一个名为 Post 的类:

    class Post {
      final String id;
      final String link;
      final String imageUrl;
      final String title;
    
      Post(this.id, this.link, this.imageUrl, this.title);
    
      factory Post.fromJson(Map<String, dynamic> json) {
        return new Post(json['id'], json['link'], json['imageUrl'], json['title']);
      }
    
      static Future<List<Post>> get(int skip, int take) async {
        var response =
            await Api.get('api/v1/posts?SkipCount=$skip&MaxResultCount=$take&');
    
        final responseJson = json.decode(response.body);
        final items = (responseJson["items"] as List).map((i) => new Post.fromJson(i));
    
        return items.toList();
      }
    }
    

    你唯一需要的其他东西是 Api 类:

    import 'dart:async';
    import 'package:http/http.dart' as http;
    
    class Api{
      static const String BaseUrl = 'http://yourapiwebsite.com/';
    
      static Future<http.Response> get(String url){
        return http.get(BaseUrl + url);
      }
    }
    

    这可以处理您所有的正常通话。如果您打算将动态参数从 UI 传递到 API,您可以拥有一个块并从中获取参数。

    【讨论】:

    • 非常感谢(Siavash)我所需要的
    【解决方案2】:

    首先,我认为您不会在函数中返回任何内容。还有变量帖子,我猜你的函数中不存在一个列表。所以我会这样改变它:

    Future<List<Posts>> fetchPosts() async {
        List<Posts> posts = [];    
    
        var url = 'https://*****.com/wp-json/wp/v2/posts';
        final response = await http.get(url, headers: {"Accept": 'application/json'});
        if (response.statusCode == 200) {
          setState(() {
            var jsonData = json.decode(response.body);
            for (var p in jsonData) {
              Posts post = Posts(
                id: p['id'],
                date: p['date'],
                title: p['title'],
                link: p['link'],
                postViews: p['views'],
                featuredImage: p['featured_image'],
                featuredImageBig: p['featured_image_big'],
                categories: p['categories'],
                comments: p['comments'],
                content: p['content'],
              );
              posts.add(post);
            }
          });
        }
    
        return posts;
      }}
    

    此实现适用于小规模应用程序。当您的应用程序规模增加时,您可能会支持不同类型的请求等,您应该查看 Bloc 模式以获得最佳实践。

    您可以在 Tensor Programming 的频道上找到将 Bloc 模式与 Web API 一起使用的示例:https://www.youtube.com/watch?v=ALcbTxz3bUw

    【讨论】:

      猜你喜欢
      • 2020-05-02
      • 2011-01-19
      • 2019-01-29
      • 1970-01-01
      • 1970-01-01
      • 2012-01-13
      • 1970-01-01
      • 2021-09-27
      • 2021-12-02
      相关资源
      最近更新 更多