我目前正在构建一个应用程序,该应用程序摄取 WordPress REST API 来显示博客文章。在初始应用程序加载时,我希望它使用一种方法提取初始数据,然后通过用户交互提取更多帖子。我目前正在进行这项工作,但是,我的实现似乎很复杂,并且可能有一种更干净的方法来完成这项工作。我的实现基于此 GitHub 问题响应。我的代码如下所示:
在main.dart:
final blogRepository = FutureProvider((ref) async {
final posts = await getPosts();
return BlogService(posts);
},
);
final blogProvider = StateNotifierProvider<BlogService, List<BlogPost>>((ref) => throw UnimplementedError(
"Access to a [BlogService] should be provided through a [ProviderScope]."));
Run Code Online (Sandbox Code Playgroud)
在blogservice.dart:
class BlogService extends StateNotifier<List<BlogPost>> {
final List<BlogPost> _posts;
BlogService(this._posts) : super(_posts);
List<BlogPost> get posts => _posts;
Future<void> morePosts(int length) async {
Response response;
var dio = Dio();
response = await dio.get('https://wordpress-site.com/wp-json/wp/v2/posts/?offset=' + …Run Code Online (Sandbox Code Playgroud)