Flutter Holodex API访问插件dart_holodex_api的使用

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

Flutter Holodex API访问插件dart_holodex_api的使用

Table of Contents

Getting started

  1. Holodex获取API密钥,具体步骤见这里
  2. 将此包添加到你的pubspec.yaml文件中:
    dependencies:
      dart_holodex_api: ^版本号
    
  3. 运行dart pub getflutter pub get

Usage

Get a video by its ID

import 'package:dart_holodex_api/dart_holodex_api.dart';
import 'package:dotenv/dotenv.dart';

void main() async {
  final dotenv = DotEnv();
  dotenv.load();

  final String apiKey = dotenv.getOrElse('API', () {
    print('API key not found, exiting');
    throw Exception('API key not provided, can not run example');
  });

  final holodexClient = HolodexClient(apiKey: apiKey);

  try {
    final VideoFull video = await holodexClient.getVideoById(
      'Gx_GPwpyLxw',
      includes: [
        Includes.channelStats,
        Includes.clips,
        Includes.liveInfo,
        Includes.mentions,
        Includes.refers,
        Includes.simulcasts,
        Includes.songs,
        Includes.sources,
      ],
    );
    print('Requested Video: ${video.toString()}');
  } catch (e) {
    print('Error fetching video: $e');
  } finally {
    holodexClient.close();
  }
}

Get a list of videos

final videoFilter = VideoFilter(
  channelId: 'UCsYcCwDqv6Sg8KMIIMF54SA', // Kiriku Translation
  includes: <Includes>[
    Includes.channelStats,
    Includes.clips,
    Includes.liveInfo,
    Includes.mentions,
    Includes.refers,
    Includes.simulcasts,
    Includes.songs,
    Includes.sources,
  ],
  languages: <Language>[Language.all],
  limit: 50,
  maxUpcomingHours: 1000,
  offset: 50,
  order: Order.descending,
  paginated: true,
  sort: <VideoSort>[VideoSort.availableAt],
  status: <VideoStatus>[VideoStatus.past],
);

final PaginatedVideos videoList = await holodexClient.getVideos(videoFilter);
print('Videos: ${videoList.items.length}\nTotal Videos: ${videoList.total}\n');

Get a list of live videos

final liveVideoFilter = VideoFilter(includes: [Includes.channelStats]);
final PaginatedVideos liveVideos = await holodexClient.getLiveVideos(liveVideoFilter);
print('Live videos: ${liveVideos.items.length}\n');

Get a channel by its ID

final Channel ceresFauna = await holodexClient.getChannelById('UCO_aKKYxn4tvrqPjcTzZ6EQ');
print('Requested Channel Name: ${ceresFauna.name}\n');

Get a list of channels

final channelFilter = const ChannelFilter(
  limit: 25,
  offset: 0,
  order: Order.ascending,
  organization: Organization.AtelierLive,
  sort: [ChannelSort.organization],
);
final List<Channel> channels = await holodexClient.getChannels(channelFilter);
print('Atelier Live Channels: ${channels.length}\n');

Quickly Access Live / Upcoming for a set of Channels

final List<Video> quickLiveVideos = await holodexClient.getLiveVideosFromChannelsQuickly([
  'UCQ0UDLQCjY0rmuxCDE38FGg', // Matsuri
  'UCZlDXzGoo7d44bwdNObFacg', // Kanata
  'UCqm3BQLlJfvkTsX_hvm0UmA' // Watame
]);
print('Requested Live Videos From Channels: ${quickLiveVideos.length}\n');

Get Videos Related To Channel

final PaginatedResult<VideoFull> matsuriClips = await holodexClient.getVideosRelatedToChannel(
  'UCQ0UDLQCjY0rmuxCDE38FGg', // Matsuri
  type: VideoSearchType.clips
);
print('Clips including Matsuri: ${matsuriClips.total}');
print('Returned clips including Matsuri: ${matsuriClips.videos.length}');

Get Clips of a VTuber

final PaginatedVideos matsuriClips2 = await holodexClient.getVTuberClips(
  'UCQ0UDLQCjY0rmuxCDE38FGg', // Matsuri
);
print('Clips including Matsuri: ${matsuriClips2.total}');
print('Returned clips including Matsuri: ${matsuriClips2.items.length}\n');

Get Collabs that mention a VTuber

final PaginatedVideos matsuriCollabs = await holodexClient.getVTuberCollabs('UCQ0UDLQCjY0rmuxCDE38FGg');
print('Collabs including Matsuri: ${matsuriCollabs.total}');
print('Returned collabs including Matsuri: ${matsuriCollabs.items.length}\n');

Get Videos From Channel

final PaginatedVideos matsuriUploads = await holodexClient.getChannelVideos('UCQ0UDLQCjY0rmuxCDE38FGg');
print('Total Matsuri uploads: ${matsuriUploads.total}');
print('Returned uploads: ${matsuriUploads.items.length}\n');

Get a single Video’s metadata

final VideoFull shionSingingStream = await holodexClient.getVideoMetadata(
  'eJJuy5rY57w', // Shion's singing stream
  includeTimestampComments: true,
  filterRecommendationLanguages: [Language.all],
);
final List<Comment> timestampComments = shionSingingStream.comments;
final List<Video> recommendations = shionSingingStream.recommendations;

print('Songs: ${shionSingingStream.songcount}');
print('Video Comments With Timestamps: ${timestampComments.length}');
print('Video Recommendations: ${recommendations.length}\n');

Search For Videos

final singingSearchFilter = SearchFilter(
  sort: SearchSort.newest,
  languages: [Language.all],
  targets: [SearchTarget.clip, SearchTarget.stream],
  topics: ['singing'],
  organizations: [
    Organization.Hololive,
    Organization.Nijisanji,
  ],
  paginated: true,
  offset: 0,
  limit: 25,
);

final PaginatedVideos searchVideos = await holodexClient.searchVideos(
  conditions: ['karaoke'],
  filter: singingSearchFilter,
);
print('Videos Found: ${searchVideos.items.length}\n');

Search For Videos With a Comment

final PaginatedVideos searchComments = await holodexClient.searchComments(
  comment: 'shion',
  filter: singingSearchFilter,
);
print('Videos with Comment: ${searchComments.items.length}\n');

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

1 回复

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


当然,以下是一个关于如何在Flutter项目中使用dart_holodex_api插件的示例代码。这个插件假设是用于访问某个名为“Holodex”的API,尽管实际API的细节和插件的具体实现可能有所不同,但以下代码提供了一个基本的框架和思路。

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

dependencies:
  flutter:
    sdk: flutter
  dart_holodex_api: ^latest_version  # 替换为实际最新版本号

然后运行flutter pub get来获取依赖。

接下来,在你的Flutter项目中创建一个服务类来封装对Holodex API的访问。以下是一个简单的示例:

import 'package:flutter/material.dart';
import 'package:dart_holodex_api/dart_holodex_api.dart';  // 假设这是插件的导入路径

class HolodexService {
  final HolodexApiClient apiClient;

  HolodexService({required this.apiClient});

  // 示例:获取某个资源的方法
  Future<HolodexResource?> fetchResource(String resourceId) async {
    try {
      final response = await apiClient.getResource(resourceId);
      if (response.success) {
        return response.data;
      } else {
        throw Exception('Failed to fetch resource: ${response.message}');
      }
    } catch (e) {
      print('Error fetching resource: $e');
      rethrow;
    }
  }
}

// 假设HolodexApiClient是插件提供的用于与API交互的客户端类
// 这里我们假设它有一个getResource方法,返回一个包含success、data和message字段的响应对象
class HolodexApiClient {
  // 实际的API URL和认证信息可能需要根据实际情况配置
  final String baseUrl = 'https://api.holodex.example.com';
  final String apiKey = 'your_api_key_here';  // 替换为你的实际API密钥

  // 示例:获取资源的方法
  Future<HolodexResponse<HolodexResource>> getResource(String resourceId) async {
    final url = '$baseUrl/resources/$resourceId';
    final response = await http.get(Uri.parse(url), headers: {
      'Authorization': 'Bearer $apiKey',
      'Content-Type': 'application/json',
    });

    if (response.statusCode == 200) {
      final data = HolodexResource.fromJson(jsonDecode(response.body));
      return HolodexResponse.success(data);
    } else {
      return HolodexResponse.error('Failed to fetch resource', null);
    }
  }
}

// 假设HolodexResponse是一个泛型响应类,用于封装API响应
class HolodexResponse<T> {
  final bool success;
  final T? data;
  final String? message;

  HolodexResponse.success(this.data) : success = true, message = null;
  HolodexResponse.error(this.message, this.data) : success = false;
}

// 假设HolodexResource是API返回的资源数据的模型类
class HolodexResource {
  final String id;
  final String name;
  // 其他字段...

  HolodexResource({required this.id, required this.name});

  factory HolodexResource.fromJson(Map<String, dynamic> json) {
    return HolodexResource(
      id: json['id'] as String,
      name: json['name'] as String,
      // 其他字段的解析...
    );
  }
}

在你的Flutter应用中,你可以这样使用这个服务类来获取资源并显示:

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Holodex API Demo'),
        ),
        body: FutureBuilder<HolodexResource?>(
          future: _fetchResource(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return CircularProgressIndicator();
            } else if (snapshot.hasError) {
              return Text('Error: ${snapshot.error!}');
            } else if (snapshot.hasData) {
              final resource = snapshot.data!;
              return Text('Resource: ${resource.name}');
            } else {
              return Text('No data');
            }
          },
        ),
      ),
    );
  }

  Future<HolodexResource?> _fetchResource() async {
    final apiClient = HolodexApiClient();
    final service = HolodexService(apiClient: apiClient);
    return service.fetchResource('example_resource_id');  // 替换为实际的资源ID
  }
}

请注意,上述代码是基于假设的API结构和插件功能编写的。实际使用时,你需要根据dart_holodex_api插件的文档和API的实际响应结构来调整代码。特别是HolodexApiClientHolodexResponseHolodexResource类的实现将依赖于实际的API设计和插件提供的接口。

回到顶部