如何在每个视图模型的Flutter中正确组织API调用?

问题描述 投票:0回答:1

[我大约一个月前开始研究Flutter,并且阅读并观看了一些不错的教程,其中最好的是带有Provider和视图模型的响应式体系结构,以防止在创建应用程序时重复代码。

现在,我正在为自己的工作编写我的第一个应用程序,我需要执行一些API调用。我还没有找到好的文章或视频,但是却教导了一种将API请求正确组织到单独文件中以防止重复的好方法,因此,我来​​这里询问您的指导。

这是我的做法。我考虑过要创建一个实现api.dart包方法的http服务。到目前为止,只有get(),但我已经可以看到其他人最终将重复太多此条件。

class Api {
  Future<dynamic> get(String url) async {
    final response = await http.get('$kBaseUrl/$url');

    if (response.statusCode != 200) {
      throw Exception(json.decode(response.body)[0]['mensagem']);
    }

    return json.decode(response.body);
  }
}

然后,例如,在到目前为止我仅有的视图模型中,我通过单击按钮来实现get()中的api.dart。按钮中的model是我上面提到的architecture的完成方式。

Future<void> submit() async {
  print('Email: $email, password: $password');
  get();
}

Future get() async {
  _setBusy(true); // loading status on
  _setError(''); // clean errors

  try {
    await _api.get('clientes');
  } catch (e) {
    _setError(e.message);
  }

  _setBusy(false); // loading status off
}
PrimaryButton(
  onTap: () {
    model.submit();
  },
  disabled: model.busy, // the loading state to modify the styling of the button
),

就是这样。我觉得它可能会好得多,而且我希望从一开始就拥有最好的方法,这样我就可以了解有关构建文件的更多信息,并且可以随着应用程序的增长保持文件的清洁。我将不胜感激任何指导,代码,文章,视频和/或存储库。

flutter dart architecture directory-structure
1个回答
1
投票
很好的问题,@ gamofe。

就文件结构而言,Flutter还是有点荒凉的西部。话虽这么说,在我的项目中,以及在我阅读的绝大多数教程中,文件夹结构如下所示:

lib/src lib/src/repositories lib/src/repositories/common lib/src/repositories/user lib/src/repositories/user/user_repository.dart lib/src/repositories/item/item_repository.dart lib/src/blocs lib/src/blocs/user lib/src/blocs/user/barrel.dart lib/src/blocs/user/user_state.dart lib/src/blocs/user/user_events.dart lib/src/blocs/user/user_bloc.dart lib/src/models/user.dart lib/src/screens/login_screen.dart lib/src/screens/item_feed.dart lib/src/widgets

此外,我非常罕见地应该直接从视图层进行API调用。我建议您阅读BLoC模式。这是Flutter应用程序中状态管理的常用方法(并由Google推荐)。 

基本上,BLoC是流。在您的视图中,您侦听流中的新状态事件。如果要更新数据,则将新事件“分发”到流中,最终将其转换为状态输出。

在应用程序中实现Bloc模式将帮助您实现所需的分离和DRY代码。

Flutter Bloc是一个帮助程序库,它将使您开始使用Bloc模式运行。文档非常好,示例很多。有一些文档概述了如何很好地管理视图,状态和网络请求之间的关系。

FWIW,I've put together an example Flutter application实现了所有这些概念。对于每个新项目,我都会使用它进行复制,以帮助我快速摇摆和滚动。随意戳一下。我已尽最大努力遵循最佳做法,因此它有望成为一个体面的榜样。

© www.soinside.com 2019 - 2024. All rights reserved.