Flutter Bungie API集成插件bungie_api的使用

发布于 1周前 作者 phonegap100 来自 Flutter

Flutter Bungie API集成插件bungie_api的使用

Bungie API Dart支持

本项目为Bungie.net API实现了Dart定义和API助手。该项目基于用于《命运物品管理器》的bungie-api-ts项目,但应该足够通用,可以在任何项目中使用。代码完全从Bungie的文档生成,虽然考虑过使用Swagger Codegen这样的工具,但最终选择了自定义生成器,以便使结果尽可能美观。

安装

在你的pubspec.yaml文件中添加以下依赖:

dependencies:
  bungie_api: ^12.2.4

接口和枚举

Bungie.net服务中定义的所有类型都有相应的定义。参见Bungie文档获取列表——接口名称是全名的最后一部分(例如,Destiny.Definitions.DestinyVendorActionDefinition变为DestinyVendorActionDefinition)。有一些例外情况,如SingleComponentResponseOfDestinyInventoryComponent,这些已经映射成更友好的形式,如SingleComponentResponse<DestinyInventoryComponent>,服务器响应现在是ServerResponse<T>而不是像DestinyCharacterResponse这样的东西。

API助手

除了类型之外,每个API端点还有简单的助手函数。这些助手定义了该端点的输入和输出,并将一个用户提供的函数与HTTP请求信息一起调用,然后你可以使用这些信息来发起HTTP请求。这种模式被用来让API助手能够提供完整的类型信息。这些助手不是完整的API客户端——它们帮助你构建一个。示例代码如下:

import 'dart:async';
import 'package:http/http.dart' as http;
import 'package:bungie_api_dart/destiny2.dart';

class BungieApiService {
  // 获取Manifest
  Future<ServerResponse<DestinyManifest>> getManifest() async {
    return await getDestinyManifest(new Client());
  }
}

// 实现HttpClient接口
class Client implements HttpClient {
  static const API_KEY = "your_api_key_here";

  [@override](/user/override)
  Future<Object> request(HttpClientConfig config) async {
    if (config.method == 'GET') {
      return await http.get(Uri.parse(config.url), headers: {'X-API-Key': API_KEY});
    } else {
      return await http.post(Uri.parse(config.url), headers: {'X-API-Key': API_KEY});
    }
  }
}

构建

./install.sh && ./build.sh

完整示例Demo

以下是一个完整的示例Demo,展示了如何使用bungie_api插件获取Manifest数据。

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:bungie_api_dart/destiny2.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Bungie API Demo")),
        body: Center(child: Text("Loading...")),
      ),
    );
  }
}

class BungieApiService {
  Future<ServerResponse<DestinyManifest>> getManifest() async {
    return await getDestinyManifest(new Client());
  }
}

class Client implements HttpClient {
  static const API_KEY = "your_api_key_here";

  [@override](/user/override)
  Future<Object> request(HttpClientConfig config) async {
    if (config.method == 'GET') {
      return await http.get(Uri.parse(config.url), headers: {'X-API-Key': API_KEY});
    } else {
      return await http.post(Uri.parse(config.url), headers: {'X-API-Key': API_KEY});
    }
  }
}

class MyAppState extends State<MyApp> {
  String _manifestData = "Loading...";

  [@override](/user/override)
  void initState() {
    super.initState();
    loadManifest();
  }

  void loadManifest() async {
    final service = BungieApiService();
    final response = await service.getManifest();

    setState(() {
      _manifestData = response.data.version.toString();
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Bungie API Demo")),
      body: Center(child: Text(_manifestData)),
    );
  }
}

更多关于Flutter Bungie API集成插件bungie_api的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter Bungie API集成插件bungie_api的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter应用中使用bungie_api插件来集成Bungie API的一个基本代码示例。这个示例将展示如何初始化插件、获取一个Bungie API访问令牌,并使用该令牌来请求一些基本数据。

首先,确保你已经在pubspec.yaml文件中添加了bungie_api依赖:

dependencies:
  flutter:
    sdk: flutter
  bungie_api: ^最新版本号 # 请替换为实际的最新版本号

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

接下来,在你的Flutter应用中,你可以按照以下步骤进行集成:

1. 初始化Bungie API客户端

你需要创建一个BungieClient实例,并配置API密钥和客户端ID。

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

class BungieService {
  final BungieClient _bungieClient;

  BungieService({required String apiKey, required String clientId})
      : _bungieClient = BungieClient(
          httpClient: http.Client(),
          apiKey: apiKey,
          clientId: clientId,
        );

  // 其他方法将在这里定义
}

2. 获取访问令牌

为了访问需要授权的数据,你需要获取一个访问令牌。这通常涉及到重定向用户到一个Bungie的授权URL,然后处理回调来获取令牌。但在这个简单示例中,我们假设你已经有了用户的授权码,并将用它来交换访问令牌。

import 'dart:convert';

Future<String?> getAccessToken(
    BungieClient client, String code, String redirectUri) async {
  final response = await client.post(
    Uri.parse('https://www.bungie.net/Platform/App/OAuth/Token/'),
    body: jsonEncode(<String, dynamic>{
      'grant_type': 'authorization_code',
      'code': code,
      'client_id': client.clientId,
      'client_secret': client.apiKey, // 注意:在实际应用中,client_secret 不应该暴露在客户端代码中
      'redirect_uri': redirectUri,
    }),
    headers: <String, String>{
      'Content-Type': 'application/json',
    },
  );

  if (response.statusCode == 200) {
    final data = jsonDecode(response.body) as Map<String, dynamic>;
    return data['access_token'] as String?;
  } else {
    throw Exception('Failed to get access token: ${response.statusCode}');
  }
}

3. 使用访问令牌请求数据

一旦你有了访问令牌,你可以用它来请求Bungie API中的数据。例如,获取当前用户的会员信息。

Future<void> fetchMembershipData(BungieClient client, String accessToken) async {
  final response = await client.get(
    Uri.parse('https://www.bungie.net/Platform/User/GetMembershipsById/'),
    parameters: <String, dynamic>{
      'membershipId': '你的会员ID', // 替换为你的Bungie.net会员ID
      'types': 'Destiny2',
    },
    headers: <String, String>{
      'X-API-Key': client.apiKey,
      'Authorization': 'Bearer $accessToken',
    },
  );

  if (response.statusCode == 200) {
    final data = jsonDecode(response.body) as Map<String, dynamic>;
    // 处理响应数据
    print(data);
  } else {
    throw Exception('Failed to fetch membership data: ${response.statusCode}');
  }
}

4. 在你的应用中调用这些方法

在你的Flutter应用中,你可以像这样调用上述方法:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  final apiKey = '你的Bungie API密钥';
  final clientId = '你的Bungie客户端ID';
  final redirectUri = '你的重定向URI';
  final code = '用户授权码'; // 这通常是通过OAuth流程获得的

  final bungieService = BungieService(apiKey: apiKey, clientId: clientId);

  String? accessToken;
  try {
    accessToken = await getAccessToken(bungieService._bungieClient, code, redirectUri);
    if (accessToken != null) {
      await fetchMembershipData(bungieService._bungieClient, accessToken);
    }
  } catch (e) {
    print('Error: $e');
  }

  runApp(MyApp());
}

请注意,这个示例代码是为了演示目的而简化的,并没有处理所有的错误情况和边界条件。在实际应用中,你需要更加健壮的错误处理和用户交互逻辑。

此外,由于bungie_api插件可能会提供更高层次的封装和简化API调用,建议查阅该插件的官方文档和示例代码,以获取最新和最佳的使用方式。

回到顶部