soa快速指南_扑扑网络快速指南

soa快速指南

When doing mobile development it’s inevitable: using an API. How can we consume those APIs nicely in Flutter? We managed to find a pretty nice setup after doing a few production projects, so let’s have a look!

在进行移动开发时,不可避免的是:使用API​​。 我们如何在Flutter中很好地使用这些API? 在完成几个生产项目后,我们设法找到了一个非常不错的设置,让我们来看一下!

首先,什么是REST API? (First things first: which REST API?)

Let’s set up our API before starting off our Flutter project. For this example, we’ll use the OpenWeatherMap API. Just click the link and make sure to sign up and get your API_KEY, since we’ll be needing that to make the API calls.

在开始Flutter项目之前,让我们设置API。 在此示例中,我们将使用OpenWeatherMap API。 只需单击链接并确保注册并获取您的API_KEY ,因为我们将需要它来进行API调用。

That’s it! Once you signed up and got your API key we can start configuring our Flutter app.

而已! 注册并获取API密钥后,我们就可以开始配置Flutter应用了。

入门:改造?! (Getting started: Retrofit?!)

Assuming you already have a Flutter project up and running, we’ll add our first dependencies to our pubspec.yaml file to set up our API client:

假设您已经启动并运行了Flutter项目,我们将第一个依赖项添加到pubspec.yaml文件中以设置API客户端:

dependencies: 
dio: 3.0.9
retrofit: 1.3.4dev_dependencies:
retrofit_generator: 1.3.4+1
build_runner: 1.9.0
  • Dio is our Http client, handling the connection for us.

    Dio是我们的Http客户端,为我们处理连接。

  • Retrofit is a Dio client that makes consuming REST APIs easier for us. Those coming from Android will be pleased to see it in Flutter I guess 🤓

    Retrofit是Dio客户端,它使我们更容易使用REST API。 我猜🤓来自Android的人会很高兴在Flutter中看到它

  • Build runner is used for code generation in Dart, apart from pub.

    构建亚军用于代码生成的Dart,除了pub

Just flutter pub get and then start setting up the client!

只是flutter pub get ,然后开始设置客户端!

We’ll add a new class and define it as a RestApi with a base URL through an annotation.

我们将添加一个新类,并通过注释将其定义为具有基本URL的RestApi

import 'package:dio/dio.dart';
import 'package:retrofit/retrofit.dart';


part 'ow_api.g.dart';


@RestApi(baseUrl: "https://community-open-weather-map.p.rapidapi.com")
abstract class OwApi {
  factory OwApi(Dio dio, {String baseUrl}) = _OwApi;
}

Notice the part below the imports: this is used for code generation. Go ahead and run the following:

请注意导入下面的part :这用于代码生成。 继续并运行以下命令:

flutter packages pub run build_runner build 

This will use build runner and generate the code for our client in the class we defined in the part. You should see it popping up in the same package as the API class once build runner is finished.

这将使用构建运行器并在我们在part定义的类中为我们的客户端生成代码。 一旦构建运行器完成,您应该看到它在与API类相同的程序包中弹出。

API client setup, done ✅

API客户端设置完成

Want to define your base URL through Dio? You actually can! The base URL defined in Dio has a lower priority than the one defined in the annotation, but leaving the base URL in the annotation empty will result in the client using the one defined in Dio 👌

是否想通过Dio定义基本URL? 您实际上可以! Dio中定义的基础URL的优先级低于注释中定义的优先级,但是将注释中的基础URL保留为空将导致客户端使用Dio中定义的基础URL👌

JSON解析:定义我们的模型 (JSON parsing: defining our model)

Let’s start off by defining the response model before actually implementing our first API call. We won’t focus on the full response for this example, but rather look at the part that contains the current temperature:

让我们从定义响应模型开始,然后再实际实现我们的第一个API调用。 在此示例中,我们将不关注全部响应,而是查看包含当前温度的部分:

{
  "main":{
    "temp":284.04,
    "pressure":1011,
    "humidity":93,
    "temp_min":280.93,
    "temp_max":287.04
  },
}

So now that we know what we’re going to receive, let’s add a dependency to start parsing the JSON response:

因此,既然我们知道将要接收的内容,我们就添加一个依赖项以开始解析JSON响应:

json_serializable: 3.3.0

Awesome! Now let’s start creating some classes to represent the response. We’ll start off with a weather response class and create another class for the main block. Just implement each field and annotate the class with @JsonSerializable().

太棒了! 现在让我们开始创建一些代表响应的类。 我们将从天气响应类开始,然后为主块创建另一个类。 只需实现每个字段并使用@JsonSerializable()注释类@JsonSerializable()

import 'package:json_annotation/json_annotation.dart';


part 'weather_response.g.dart';


@JsonSerializable()
class WeatherResponse {
  final MainResponse main;


  WeatherResponse({this.main});


  factory WeatherResponse.fromJson(Map<String, dynamic> json) => _$WeatherResponseFromJson(json);
  Map<String, dynamic> toJson() => _$WeatherResponseToJson(this);
}


@JsonSerializable()
class MainResponse {
  final double temp;


  MainResponse({this.temp});


  factory MainResponse.fromJson(Map<String, dynamic> json) => _$MainResponseFromJson(json);
  Map<String, dynamic> toJson() => _$MainResponseToJson(this);
}

Cool, just run build runner again and we should be able to parse the current temperature from the response now 😄

太酷了,只需再次运行构建运行器,我们现在应该能够从响应中解析当前温度temperature

添加您的第一个API调用 (Adding your first API call)

So let’s head back to our client now. We’re going to need a GET request to fetch the current temperature. Looking at the documentation of our API, we’ll have to add some headers to the request and add a query parameter for the requested location. Luckily Retrofit makes this all quite easy for us to do!

因此,让我们现在回到我们的客户。 我们将需要一个GET请求来获取当前温度。 查看我们API的文档,我们必须向请求添加一些标头,并为请求的位置添加查询参数。 幸运的是,翻新使我们可以轻松完成所有这些工作!

@GET("/weather")
@Headers(<String, String>{
  "x-rapidapi-host": "community-open-weather-map.p.rapidapi.com",
  "x-rapidapi-key": "{YOUR_API_KEY}"
})
Future<WeatherResponse> getCurrentWeather(
  @Query('q') String location,
);

I think the code-snippet speaks for itself. We can use an annotation to define what kind of request we want to do (get, post, put, etc), use an annotation to add additional headers and annotate parameters to define it as a query parameter. Most use-cases should be covered, take a look at the documentation to see if it fits your needs!

我认为代码片段可以说明一切。 我们可以使用批注定义我们要执行的请求类型(获取,发布,放置等),使用批注添加其他标头并注释参数以将其定义为查询参数。 大多数用例都应涵盖在内,请查看文档以了解其是否符合您的需求!

Defining headers for each call can become quite repetitive, so make sure you configure Dio for all the general stuff as much as possible!

为每个调用定义标题会变得很重复,因此请确保为所有常规内容尽可能地配置Dio!

拨打电话 (Making the call)

That’s actually it already! We’ll just need to initialize everything and do the actual call.

到此为止! 我们只需要初始化所有内容并进行实际调用即可。

final dio = Dio(); // Provide a Dio instance to the client
final client = OwApi(dio); // Initialise the client


// Do the request and print the current temperature of Amsterdam
client.getCurrentWeather('Amsterdam')
    .then((response) => print(response.main.temp));

I would like to point out that we make use of a service locator to get dependencies like Dio or the API client throughout our project. I’d highly recommend using Get it for that, it’s great!

我想指出的是,我们利用服务定位器来获取整个项目中的Dio或API客户端之类的依赖项。 我强烈建议您使用Get it ,这太好了!

That’s a wrap! I hope you got the gist of it. Retrofit made it super easy to implement calls and the automatic type conversion is also a nice benefit over handling everything through Dio ourselves as we used to do here at PINCH. A complete example can be found in the Github project below.

这是一个包装! 希望您能理解。 改造使实现调用非常容易,而且自动类型转换与通过Dio自己处理一切一样,也有很大的好处,就像我们在 PINCH 上所做的那样 完整的示例可以在下面的Github项目中找到。

Stay healthy, stay safe and keep coding 🐦

保持健康,安全并保持编码 🐦

翻译自: https://itnext.io/networking-in-flutter-quick-guide-c491819a64f0

soa快速指南

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值