Flutter非官方开放API集成插件unofficial_open_api的使用
Flutter非官方开放API集成插件unofficial_open_api的使用
使用Dart轻松调用GPT-3 API。该插件涵盖了所有主要功能。
查看这些API的工作原理,请访问以下链接(已移除)。
使用方法
首先,在官方网站创建API密钥。
然后,通过以下Dart代码导入插件:
import 'package:unofficial_open_api/unofficial_open_api.dart';
接下来,创建Open AI服务并使用其服务:
final service = OpenAIService.create(
apiToken: 'your-api-key',
enableLogging: true,
);
final response = await service.getModels();
示例代码
以下是完整的示例代码,展示了如何在Flutter应用中使用unofficial_open_api
插件。
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:unofficial_open_api/unofficial_open_api.dart';
import 'package:logging/logging.dart';
// 定义一个Provider来管理生成图像的URL
final urlImageProvider = StateProvider<String?>((ref) => '');
// 创建一个Provider来管理OpenAIService实例
final openAIService = Provider(
(ref) => OpenAIService.create(
apiToken: const String.fromEnvironment('API_KEY'),
enableLogging: true,
),
);
void main() {
// 设置日志记录器
_setupLogger();
runApp(
const ProviderScope(
child: ExampleOpenAIApp(),
),
);
}
// 配置日志记录器
void _setupLogger() {
Logger.root.level = Level.ALL;
Logger.root.onRecord.listen((rec) {
log('${rec.level.name}: ${rec.time}: ${rec.message}');
});
}
// 主应用组件
class ExampleOpenAIApp extends StatelessWidget {
const ExampleOpenAIApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return const MaterialApp(
home: ExampleOpenAI(),
);
}
}
// 应用主页面
class ExampleOpenAI extends ConsumerWidget {
const ExampleOpenAI({super.key});
[@override](/user/override)
Widget build(BuildContext context, WidgetRef ref) {
final service = ref.read(openAIService);
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Base url: ${service.client.baseUrl}'),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () => _getModels(ref),
child: const Text("List of models"),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () => _getModelById(ref),
child: const Text("Model by id"),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () => _completion(ref),
child: const Text("Completion"),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () => _moderation(ref),
child: const Text("Moderation"),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () => _generation(ref),
child: const Text("Generation"),
),
GeneratedImage(url: ref.watch(urlImageProvider)),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () => _editMistake(ref),
child: const Text("Edit mistake"),
),
],
),
),
),
);
}
// 获取模型列表
Future<void> _getModels(WidgetRef ref) async {
final responseModels = await ref.read(openAIService).getModels();
if (!responseModels.isSuccessful) return;
final body = responseModels.body;
if (body == null) return;
final data = body.data;
if (data == null) return;
for (final element in data) {
log('Object id: ${element.id}');
}
}
// 根据ID获取模型
Future<void> _getModelById(WidgetRef ref) async {
final responseModel =
await ref.read(openAIService).getModel(modelId: 'text-davinci-002');
if (!responseModel.isSuccessful) return;
final body = responseModel.body;
if (body == null) return;
log('Object: $body');
}
// 创建Completion请求
Future<void> _completion(WidgetRef ref) async {
final responseModels = await ref.read(openAIService).createCompletion(
const CompletionRequest(
prompt: 'Create an out of office email sample for christmas holiday',
model: 'text-davinci-003',
temperature: 0,
maxTokens: 60,
),
);
if (!responseModels.isSuccessful) return;
final body = responseModels.body;
if (body == null) return;
log('$body');
}
// 创建Moderation请求
Future<void> _moderation(WidgetRef ref) async {
final responseModels = await ref.read(openAIService).createModeration(
const ModerationRequest(
input: 'This is Steve, my wonderful dog!',
model: 'text-moderation-latest',
),
);
if (!responseModels.isSuccessful) return;
final body = responseModels.body;
if (body == null) return;
log('$body');
}
// 创建Image请求
Future<void> _generation(WidgetRef ref) async {
final responseModels = await ref.read(openAIService).createImage(
const ImageRequest(
prompt: 'A real akita dog as superhero',
responseFormat: 'url',
user: 'unique-user-id'),
);
if (!responseModels.isSuccessful) return;
final body = responseModels.body;
if (body == null) return;
log('$body');
ref.read(urlImageProvider.notifier).state = body.data?.first.url;
}
// 创建Edit请求
Future<void> _editMistake(WidgetRef ref) async {
final responseModels = await ref.read(openAIService).createEdit(
const EditRequest(
input: 'Hello wrld!',
instruction: 'Fix the mistakes',
model: 'text-davinci-edit-001',
),
);
if (!responseModels.isSuccessful) return;
final body = responseModels.body;
if (body == null) return;
log('$body');
}
}
// 显示生成的图像
class GeneratedImage extends StatelessWidget {
final String? url;
const GeneratedImage({super.key, this.url});
[@override](/user/override)
Widget build(BuildContext context) {
if (url == null || url!.isEmpty) return const IgnorePointer();
return Image.network(url!);
}
}
更多关于Flutter非官方开放API集成插件unofficial_open_api的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter非官方开放API集成插件unofficial_open_api的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中集成并使用一个假设的非官方开放API插件 unofficial_open_api
的示例代码。请注意,由于这是一个假设的插件,具体的API接口、方法和类名需要根据实际的插件文档进行调整。以下示例代码旨在展示基本的集成步骤和调用方式。
1. 添加依赖
首先,在你的 pubspec.yaml
文件中添加 unofficial_open_api
依赖(假设它已经在Pub上发布)。如果它是一个本地插件或者从Git仓库获取的,你需要按照相应的步骤添加。
dependencies:
flutter:
sdk: flutter
unofficial_open_api: ^latest_version # 替换为实际版本号
然后运行 flutter pub get
来获取依赖。
2. 导入插件
在你的 Dart 文件中导入插件。
import 'package:unofficial_open_api/unofficial_open_api.dart';
3. 初始化插件
根据插件的文档,可能需要初始化插件。以下是一个假设的初始化过程:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 假设插件有一个初始化方法
awaitUnofficialOpenApi.initialize();
runApp(MyApp());
}
4. 使用插件的功能
假设 unofficial_open_api
插件提供了一个获取用户信息的方法,我们可以这样调用它:
import 'package:flutter/material.dart';
import 'package:unofficial_open_api/unofficial_open_api.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await UnofficialOpenApi.initialize();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Unofficial Open API Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: UserInfoScreen(),
);
}
}
class UserInfoScreen extends StatefulWidget {
@override
_UserInfoScreenState createState() => _UserInfoScreenState();
}
class _UserInfoScreenState extends State<UserInfoScreen> {
User? userInfo;
String? errorMessage;
@override
void initState() {
super.initState();
_fetchUserInfo();
}
Future<void> _fetchUserInfo() async {
try {
// 假设有一个获取用户信息的方法,需要传入API密钥等参数
UserInfoResult result = await UnofficialOpenApi.getUserInfo(apiKey: 'your_api_key');
setState(() {
userInfo = result.user;
errorMessage = null;
});
} catch (e) {
setState(() {
userInfo = null;
errorMessage = e.toString();
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('User Info'),
),
body: Center(
child: userInfo != null
? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Name: ${userInfo!.name}'),
Text('Email: ${userInfo!.email}'),
],
)
: Text(errorMessage ?? 'Loading...'),
),
);
}
}
// 假设的User类和数据结果类
class User {
final String name;
final String email;
User({required this.name, required this.email});
}
class UserInfoResult {
final User? user;
UserInfoResult({this.user});
}
注意事项
- API密钥管理:不要在代码中硬编码API密钥。考虑使用环境变量或Flutter的
shared_preferences
插件来安全地存储和管理密钥。 - 错误处理:始终添加适当的错误处理逻辑,以处理API调用失败的情况。
- 依赖更新:定期检查并更新你的依赖项,以确保使用最新版本的插件和库。
以上代码提供了一个基本的框架,展示了如何在Flutter项目中集成并使用一个假设的非官方开放API插件。实际使用时,请参照插件的官方文档进行调整。