flutter:获取帖子列表是最佳实践代码吗?

时间:2019-01-09 15:26:28

标签: api dart flutter

从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);
      }
    });      
} 
}}

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

感谢前进

2 个答案:

答案 0 :(得分:0)

首先,我认为您不会在函数中返回任何内容。另外,变量post,我想是一个List,在您的函数内部不存在。所以我会这样更改:

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编程的频道上找到将Bloc模式与Web API结合使用的示例:https://www.youtube.com/watch?v=ALcbTxz3bUw

答案 1 :(得分:0)

让我们假设您有一个称为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,则可以拥有一个bloc并从中获取参数。