Flutter Postman集合导入插件postman_collection的使用

Flutter Postman 集合导入插件 postman_collection 的使用

此插件是一个 Postman 集合模式生成器,允许您轻松为您的 Dio 和 http 客户端生成模式。

安装

要安装该包,只需运行以下命令:

dart pub add postman_collection

使用

要使用该包,您可以将其导入到项目中并调用 generateSchema 函数。以下是一个示例:

import 'package:postman_collection/postman_collection.dart';

PostmanCollection.fromJson(...);

示例代码

以下是一个完整的示例代码,展示了如何使用 postman_collection 插件生成 Postman 集合文件。

import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:yaml/yaml.dart';
import 'package:example/src/dio.dart';
import 'package:example/src/models.dart';
import 'package:postman_collection/postman_collection.dart';
import 'package:retrofit/retrofit.dart';

part 'main.g.dart';

class UploadFileResponse {
  final String url;

  UploadFileResponse({required this.url});

  factory UploadFileResponse.fromJson(Map<String, dynamic> json) {
    return UploadFileResponse(
      url: json['url'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'url': url,
    };
  }
}

[@RestApi](/user/RestApi)()
abstract class AppClient {
  factory AppClient(Dio dio, {String baseUrl}) = _AppClient;

  [@POST](/user/POST)('/upload')
  [@MultiPart](/user/MultiPart)()
  Future<HttpResponse<UploadFileResponse>> uploadFile(
    @Part() File file,
  );

  [@GET](/user/GET)('/app/{platform}')
  Future<HttpResponse<AppResponse>> getAppData({
    [@Path](/user/Path)() required String platform,
    @Header('Accept-Language') required String language,
    @Query('version') required String version,
    [@Body](/user/Body)() required AppDataRequestBody body,
  });
}

class AppClientDoc with PostmanCollectionDocumentationMixin {
  AppClientDoc(this._client);

  final AppClient _client;

  [@override](/user/override)
  Future<PostmanCollectionItem> doc() async {
    return PostmanCollectionItem(
      name: PostmanCollectionItem.getNameFromClass(runtimeType),
      item: await Future.wait([
        getAppDataDoc(),
        getUploadFileDoc(),
      ]),
    );
  }

  Future<PostmanCollectionItem> getAppDataDoc() async {
    final function = _client.getAppData;

    return PostmanCollectionItem(
      name: PostmanCollectionItem.getNameFromFunction(function),
      request: PostmanCollectionRequest.fromRequestOptions(
        await getRequestOptionsFromRetrofit(
          () => function(
            platform: 'android',
            version: '1.0.1',
            language: 'en',
            body: AppDataRequestBody(
              date: DateTime.now(),
            ),
          ),
        ),
      ),
      response: [
        PostmanCollectionResponse(
          name: 'Default',
          status: '200',
          postmanPreviewLanguage: 'json',
          body: jsonEncode(
            AppResponse(
              name: 'Postman',
              version: '1.0.0',
            ).toJson(),
          ),
        ),
        PostmanCollectionResponse(
          name: 'Error',
          status: '400',
          postmanPreviewLanguage: 'json',
          body: jsonEncode(MessageResponse().toJson()),
        ),
      ],
    );
  }

  Future<PostmanCollectionItem> getUploadFileDoc() async {
    final function = _client.uploadFile;

    return PostmanCollectionItem(
      name: PostmanCollectionItem.getNameFromFunction(function),
      request: PostmanCollectionRequest.fromRequestOptions(
        await getRequestOptionsFromRetrofit(
          () => function(File('pubspec.yaml')),
        ),
      ),
      response: [
        PostmanCollectionResponse(
          name: 'Default',
          status: '200',
          postmanPreviewLanguage: 'json',
          body: jsonEncode({
            'url': 'https://example.com/test.txt',
          }),
        ),
        PostmanCollectionResponse(
          name: 'Error',
          status: '400',
          postmanPreviewLanguage: 'json',
          body: jsonEncode(MessageResponse().toJson()),
        ),
      ],
    );
  }
}

[@RestApi](/user/RestApi)()
abstract class UserClient {
  factory UserClient(Dio dio, {String baseUrl}) = _UserClient;

  [@GET](/user/GET)('/users/')
  Future<HttpResponse<List<UserResponse>>> get();

  [@GET](/user/GET)('/users/{id}')
  Future<HttpResponse<UserResponse>> getDetail([@Path](/user/Path)() String id);

  [@POST](/user/POST)('/users/')
  [@MultiPart](/user/MultiPart)() // 添加此注解以标记为 form-data
  Future<HttpResponse<UserResponse>> create([@Body](/user/Body)() CreateUserRequestBody body);

  [@PUT](/user/PUT)('/users/{id}')
  Future<HttpResponse<UserResponse>> update(
    [@Path](/user/Path)() String id,
    [@Body](/user/Body)() UpdateUserRequestBody body,
  );

  [@DELETE](/user/DELETE)('/users/{id}')
  Future<HttpResponse<UserResponse>> delete([@Path](/user/Path)() String id);
}

class UserClientDoc with PostmanCollectionDocumentationMixin {
  UserClientDoc(this._client);

  final UserClient _client;

  Future<PostmanCollectionItem> getDoc() async {
    final function = _client.get;

    return PostmanCollectionItem(
      name: PostmanCollectionItem.getNameFromFunction(function),
      request: PostmanCollectionRequest.fromRequestOptions(
        await getRequestOptionsFromRetrofit(function),
      ),
      response: [
        PostmanCollectionResponse(
          name: 'Default',
          status: '200',
          postmanPreviewLanguage: 'json',
          body: jsonEncode([
            UserResponse(name: 'John Doe', email: 'johndoe@email.com'),
          ].map((e) => e.toJson()).toList()),
        )
      ],
    );
  }

  Future<PostmanCollectionItem> getDetailDoc() async {
    final function = _client.getDetail;

    return PostmanCollectionItem(
      name: PostmanCollectionItem.getNameFromFunction(function),
      request: PostmanCollectionRequest.fromRequestOptions(
        await getRequestOptionsFromRetrofit(() => function('1')),
      ),
      response: [
        PostmanCollectionResponse(
          name: 'Default',
          status: '200',
          postmanPreviewLanguage: 'json',
          body: jsonEncode(
            UserResponse(
              name: 'John Doe',
              email: 'johndoe@email.com',
            ).toJson(),
          ),
        )
      ],
    );
  }

  Future<PostmanCollectionItem> createDoc() async {
    final function = _client.create;

    return PostmanCollectionItem(
      name: PostmanCollectionItem.getNameFromFunction(function),
      request: PostmanCollectionRequest.fromRequestOptions(
        await getRequestOptionsFromRetrofit(
          () => function(
            CreateUserRequestBody(
              name: 'John Doe',
              email: 'asd',
              image: File("${Directory.current.path}/lib/src/dio.dart"),
            ),
          ),
        ),
      ),
      response: [
        PostmanCollectionResponse(
          name: 'Default',
          status: '200',
          postmanPreviewLanguage: 'json',
          body: jsonEncode(
            UserResponse(
              name: 'John Doe',
              email: 'asd',
            ).toJson(),
          ),
        )
      ],
    );
  }

  Future<PostmanCollectionItem> updateDoc() async {
    final function = _client.update;

    return PostmanCollectionItem(
      name: PostmanCollectionItem.getNameFromFunction(function),
      request: PostmanCollectionRequest.fromRequestOptions(
        await getRequestOptionsFromRetrofit(
          () => function(
            '1',
            UpdateUserRequestBody(
              name: 'John Doe',
              email: 'asd',
            ),
          ),
        ),
      ),
      response: [
        PostmanCollectionResponse(
          name: 'Default',
          status: '200',
          postmanPreviewLanguage: 'json',
          body: jsonEncode(
            UserResponse(
              name: 'John Doe',
              email: 'asd',
            ).toJson(),
          ),
        )
      ],
    );
  }

  Future<PostmanCollectionItem> deleteDoc() async {
    final function = _client.delete;

    return PostmanCollectionItem(
      name: PostmanCollectionItem.getNameFromFunction(function),
      request: PostmanCollectionRequest.fromRequestOptions(
        await getRequestOptionsFromRetrofit(() => function('1')),
      ),
      response: [
        PostmanCollectionResponse(
          name: 'Default',
          status: '200',
          postmanPreviewLanguage: 'json',
          body: jsonEncode(
            UserResponse(
              name: 'John Doe',
              email: 'asd',
            ).toJson(),
          ),
        )
      ],
    );
  }

  [@override](/user/override)
  Future<PostmanCollectionItem> doc() async {
    return PostmanCollectionItem(
      name: PostmanCollectionItem.getNameFromClass(runtimeType),
      item: await Future.wait([
        getDoc(),
        getDetailDoc(),
        createDoc(),
        updateDoc(),
        deleteDoc(),
      ]),
    );
  }
}

Future<void> main() async {
  final dio = getDocumentationDio();

  final pubspecYaml = loadYaml(File('pubspec.yaml').readAsStringSync());

  final projectName = pubspecYaml['name'];

  print('Generating Postman Collection for $projectName');

  final collection = PostmanCollection(
    info: PostmanCollectionInfo(
      name: projectName,
      schema: PostmanCollectionInfo.schemaV210,
      version: PostmanCollectionVersion.fromString('1.0.0'),
    ),
    item: await Future.wait([
      AppClientDoc(AppClient(dio)),
      UserClientDoc(UserClient(dio)),
    ].map((e) => e.doc()).toList()),
  );

  final file = File('versions/${PostmanCollection.filename(projectName)}');

  await file.writeAsString(jsonEncode(collection.toJson()));
  print('Postman Collection generated at ${file.path}');
}

String jsonEncode(Object? object) {
  return JsonEncoder.withIndent('  ').convert(object);
}

更多关于Flutter Postman集合导入插件postman_collection的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter Postman集合导入插件postman_collection的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,我可以为你提供一个关于如何在Flutter项目中使用postman_collection插件来导入Postman集合的示例。postman_collection是一个Flutter插件,用于解析和使用Postman集合。

首先,你需要在你的pubspec.yaml文件中添加postman_collection依赖:

dependencies:
  flutter:
    sdk: flutter
  postman_collection: ^x.y.z  # 请替换为最新版本号

然后运行flutter pub get来安装依赖。

接下来,你可以编写一个示例应用来演示如何使用这个插件。以下是一个完整的示例代码:

import 'package:flutter/material.dart';
import 'package:postman_collection/postman_collection.dart';
import 'dart:convert';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Postman Collection Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String? collectionJson;
  List<Request>? requests;

  @override
  void initState() {
    super.initState();
    // 这里你可以从文件或其他来源加载你的Postman集合JSON
    // 这里假设你已经有一个JSON字符串作为示例
    collectionJson = '''
    {
      "info": {
        "_postman_id": "xxxx-xxxx-xxxx-xxxx-xxxx",
        "name": "Example Collection",
        "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
      },
      "item": [
        {
          "name": "Example Request",
          "request": {
            "method": "GET",
            "header": [],
            "url": {
              "raw": "https://api.example.com/v1/resource",
              "protocol": "https",
              "host": [
                "api",
                "example",
                "com"
              ],
              "path": [
                "v1",
                "resource"
              ]
            }
          },
          "response": []
        }
      ]
    }
    ''';

    // 解析Postman集合
    parseCollection();
  }

  void parseCollection() async {
    try {
      final collection = Collection.fromJson(jsonDecode(collectionJson!));
      setState(() {
        requests = collection.items.map((item) => item.request).toList();
      });
    } catch (e) {
      print("Error parsing collection: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Postman Collection Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: requests == null
            ? Center(child: Text('Loading...'))
            : ListView.builder(
                itemCount: requests!.length,
                itemBuilder: (context, index) {
                  final request = requests![index];
                  return ListTile(
                    title: Text('Request ${index + 1}: ${request.method} ${request.url?.raw}'),
                    subtitle: Text('Headers: ${request.header.map((header) => "${header.key}: ${header.value}").join(", ")}'),
                  );
                }),
      ),
    );
  }
}

在这个示例中,我们:

  1. pubspec.yaml文件中添加了postman_collection依赖。
  2. MyApp应用中创建了一个简单的UI。
  3. _MyHomePageStateinitState方法中,我们定义了一个Postman集合的JSON字符串(你可以从文件或其他来源加载这个JSON)。
  4. 使用Collection.fromJson方法解析这个JSON字符串。
  5. 将解析后的请求列表存储在状态中,并在UI中显示。

这个示例展示了如何从JSON字符串解析Postman集合,并显示集合中的请求信息。你可以根据需要扩展这个示例,例如添加对响应的处理、发送请求等。

回到顶部