Flutter web - 3 网络请求 Protocol Buffer

介绍

由于业务使用的通信协议为 Protocol Buffer,所以文章主要以如何通过 Protocol Buffer 发起网络请求为主。

安装 protoc

需要借助 protocol buffer 编译工具,将 .proto 文件编译为 .dart 文件

安装地址

目录结构

├─protocols
│  ├─lib
│  │  ├─api
│  │  │  └─api.dart
│  │  ├─gen
│  │  ├─pb
│  │  │  └─web.ext.proto
│  │  └─protocols.dart
│  └─pubspec.yaml

在项目根目录下创建 protocols,添加 pubspec.yaml,使其成为一个模块。在 pb 目录中存放 .proto 文件,生成的 .dart 文件放在 gen 文件夹中。

pubspec.yaml 文件内容:

使用了 protobufprotoc_pluginhttp 依赖。

name: protocols
description: A new Flutter package project.
version: 0.0.1

publish_to: none

environment:
  sdk: ">=3.3.0 <4.0.0"
  flutter: ">=3.19.0"

dependencies:
  flutter:
    sdk: flutter

  protobuf: ^3.1.0
  http: ^1.2.2

dev_dependencies:
  flutter_test:
    sdk: flutter

  protoc_plugin: 21.1.2

flutter:


在终端中打开 protocols 目录并执行 flutter pub get 来安装依赖。

web.ext.proto内容:

syntax = "proto3";

service WebService {
  rpc GetResponse(RequestMessage) returns (ResponseMessage);
}

message RequestMessage {
  string name = 1;
}

message ResponseMessage {
  string message = 1;
}

执行编译命令

protoc --dart_out=D:\my_flutter_web\protocols\lib\gen --proto_path=D:\my_flutter_web\protocols\lib\pb web.ext.proto

将会在 protocols\lib\gen 目录下生成 web.ext.pb.dart、web.ext.pbenum.dart、web.ext.pbjson.dart、web.ext.pbserver.dart 文件。

在这里插入图片描述

主要使用 web.ext.pb.dartweb.ext.pbenum.dart 文件。

实现 request.dart

分析 web.ext.pb.dart 文件,可以看出需要创建一个 class 继承抽象类 RpcClient 来实现 invoke 方法。

web.ext.pb.dart 文件部分内容:

...
class WebServiceApi {
  $pb.RpcClient _client;
  WebServiceApi(this._client);

  $async.Future<ResponseMessage> getResponse($pb.ClientContext? ctx, RequestMessage request) =>
    _client.invoke<ResponseMessage>(ctx, 'WebService', 'GetResponse', request, ResponseMessage())
  ;
}
...

request.dart:

import 'package:http/http.dart' as http;
import 'package:protobuf/protobuf.dart';

class Request extends RpcClient {
  final String apiUrl;

  Request({required this.apiUrl});
  
  
  Future<T> invoke<T extends GeneratedMessage>(
      ClientContext? ctx,
      String serviceName,
      String methodName,
      GeneratedMessage request,
      T emptyResponse) async {
      
    final response = await http.post(
      Uri.parse(apiUrl),
      headers: {
        'Content-Type': 'application/x-protobuf',
      },
      body: request.writeToBuffer(),
    );

    emptyResponse.mergeFromBuffer(response.bodyBytes);

    return Future.value(emptyResponse);
  }
}

这只是简单实现版本,实际要根据业务需求与使用的 rpc 类型对代码进行调整。

api.dart

import 'package:protocols/gen/web.ext.pb.dart';
import 'package:protocols/request.dart';

final Request _request = Request(apiUrl: 'xxx');

WebServiceApi _webServiceApi = WebServiceApi(_request);

Future<ResponseMessage> getResponse(String name) async {
  return await _webServiceApi.getResponse(null, RequestMessage(name: name));
}

只需创建 WebServiceApi 实例,并把 Request 实例作为参数传入,即可通过 WebServiceApi 实例调用 web.ext.pb.dart 中的 getResponse 方法。后续只需在项目中引入 api.dart 文件,并调用 getResponse 方法即可。

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Flutter中的TextField是一个常用的输入控件,它允许用户在应用程序中输入文本。 TextField通常用于表单中,可以接收用户输入的文本,比如用户名、密码、电子邮件地址等。 以下是一个基本的TextField示例: ```dart TextField( decoration: InputDecoration( hintText: '请输入文本', ), ); ``` 在上面的示例中,我们使用了decoration属性来设置TextField的外观,其中hintText属性用于设置提示文本。 TextField还有许多其他的属性可以设置,比如maxLength(允许输入的最大长度)、keyboardType(键盘类型)、obscureText(是否隐藏输入内容)等等。 下面是一个更完整的TextField示例: ```dart class MyTextField extends StatefulWidget { @override _MyTextFieldState createState() => _MyTextFieldState(); } class _MyTextFieldState extends State<MyTextField> { final TextEditingController _controller = TextEditingController(); @override Widget build(BuildContext context) { return TextField( controller: _controller, maxLength: 10, keyboardType: TextInputType.text, obscureText: true, decoration: InputDecoration( hintText: '请输入文本', labelText: '文本框', prefixIcon: Icon(Icons.text_fields), suffixIcon: IconButton( icon: Icon(Icons.clear), onPressed: () { setState(() { _controller.clear(); }); }, ), border: OutlineInputBorder(), ), onChanged: (value) { print('输入的文本为:$value'); }, ); } } ``` 在上面的示例中,我们使用了TextEditingController来控制TextField的文本内容,maxLength属性限制了用户输入的最大长度为10,keyboardType属性指定了键盘类型为文本类型,obscureText属性设置为true表示隐藏输入内容。 此外,我们还设置了decoration属性来自定义TextField的外观,包括了输入提示文本、标签文本、前缀图标、后缀图标和边框样式等。 最后,我们通过onChanged回调函数来监听用户输入的文本,并打印出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值