Flutter GIF选择插件giphy_selector的使用

Flutter GIF选择插件giphy_selector的使用

本插件允许你从GIPHY获取GIF、贴纸或表情符号,使用纯Dart代码并通过Giphy SDK遵循设计指南。

Giphy Selector演示

获取开始

在使用该插件之前,你需要在Giphy开发者页面注册你的应用并获取API密钥。

本地化

目前支持英语、法语和西班牙语。

void main() {
  runApp(MaterialApp(
    title: 'Demo',
    localizationsDelegates: [
      GlobalMaterialLocalizations.delegate,
      GlobalWidgetsLocalizations.delegate,
      GiphyGetUILocalizations.delegate
    ],
    supportedLocales: [
      Locale('en', ''),
      Locale('es', ''),
      Locale('fr', ''),
    ],
    home: MyHomePage(title: 'Demo'),
  ));
}

获取仅GIF

此部分用于获取不带包装的GIF,并通过点击来查看更多内容。

import 'package:giphy_selector/giphy_selector.dart';

GiphyGif gif = await GiphySelector.getGif(
  context: context, // 必须参数
  apiKey: "your api key HERE", // 必须参数
  lang: GiphyLanguage.english, // 可选参数 - 查询语言
  randomID: "abcd", // 可选参数 - 特定用户的ID/代理
  modalOptions: ModalOptions( // 可选参数 - 在模态框中显示Giphy选择器
    Offset.zero,
    Alignment.topLeft
  ),
  tabColor:Colors.teal, // 可选参数 - 默认为强调色
);

选项

参数名 类型 描述 默认值
lang String 使用ISO 639-1语言代码或使用GiphyLanguage常量 GiphyLanguage.english
randomID String 特定用户的ID/代理 null
searchText String 输入搜索提示,建议使用flutter_18n包进行翻译 "Search GIPHY"
modalOptions ModalOptions 当非null时,用于在模态框中定位Giphy选择器 null
tabColor Color 选项卡和加载进度的颜色 Theme.of(context).accentColor

获取随机ID

Future<void> doSomeThing() async {
  GiphyClient giphyClient = GiphyClient(apiKey: 'YOUR API KEY');
  String randomId = await giphyClient.getRandomId();
}

小部件

GiphyGifWidget

参数名 类型 描述 默认值
gif 必须 GiphyGif GiphyGif对象,来自流或JSON 无
giphyGetWrapper 必须 GiphyGetWrapper 选择器实例用于通过作者查找更多内容 null
showGiphyLabel bool 显示或隐藏Powered by GIPHY标签 true
borderRadius BorderRadius 为图像添加圆角 null
imageAlignment Alignment 此小部件是一个包含图像和点击按钮的堆栈,此属性调整对齐方式 Alignment.center

GiphyGetWrapper

参数名 类型 描述 默认值
giphy_api_key 必须 String 你的Giphy API密钥 null
builder function 返回Stream<GiphyGif>和GiphyGetWrapper实例 null

可用方法

void getGif(String queryText, BuildContext context);
void build(BuildContext context) {
  return GiphyGetWrapper(
      giphy_api_key: 'REPLACE_WITH YOUR_API_KEY',
      // 包含Stream<GiphyGif>和GiphyGetWrapper实例的构建器
      builder: (stream, giphyGetWrapper) =>
          StreamBuilder<GiphyGif>(
              stream: stream,
              builder: (context, snapshot) {
                return Scaffold(
                  body: snapshot.hasData
                      ? SizedBox(
                    // 带有点击更多功能的GiphyGifWidget
                    child: GiphyGifWidget(
                      imageAlignment: Alignment.center,
                      gif: snapshot.data,
                      giphyGetWrapper: giphyGetWrapper,
                      borderRadius: BorderRadius.circular(30),
                      showGiphyLabel: true,
                    ),
                  )
                      : Text("No GIF"),
                  floatingActionButton: FloatingActionButton(
                    onPressed: () async {
                      // 打开Giphy表单
                      giphyGetWrapper.getGif('', context);
                    },
                    tooltip: 'Open Sticker',
                    child: Icon(Icons.insert_emoticon),
                  ),
                );
              }
          )
  );
}

使用示例

首先导出你的Giphy API密钥:

export GIPHY_API_KEY=YOUR_GIPHY_API_KEY

然后运行项目。

示例代码

import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:giphy_selector/giphy_selector.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  if (!kIsWeb) {
    await dotenv.load(mergeWith: Platform.environment);
  } else {
    await dotenv.load();
  }

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // 这个小部件是你应用程序的根。
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Demo',
      theme: ThemeData(
        brightness: Brightness.light,
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      darkTheme: ThemeData(
        brightness: Brightness.dark,
        primarySwatch: Colors.purple,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GiphyGetUILocalizations.delegate
      ],
      supportedLocales: const [
        Locale('en', ''),
        Locale('es', ''),
        Locale('fr', ''),
      ],
      home: const MyHomePage(title: 'Demo'),
      themeMode: ThemeMode.system,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  [@override](/user/override)
  // ignore: library_private_types_in_public_api
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  GiphyGif? currentGif;
  late final GiphyClient client;
  String randomId = '';
  String giphyApiKey = '';

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

    client = GiphyClient(apiKey: giphyApiKey, randomId: '');
    WidgetsBinding.instance.addPostFrameCallback((_) {
      client.getRandomId().then((value) {
        setState(() {
          randomId = value;
        });
      });
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return GiphySelectorWrapper(
        apiKey: giphyApiKey,
        builder: (stream, giphyGetWrapper) {
          stream.listen((gif) {
            setState(() {
              currentGif = gif;
            });
          });

          return Scaffold(
            appBar: AppBar(
              title: Row(
                children: [
                  Image.asset("assets/img/GIPHY Transparent 18px.png"),
                  const SizedBox(
                    width: 20,
                  ),
                  const Text("Demo")
                ],
              ),
            ),
            body: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Align(
                alignment: Alignment.center,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    const SizedBox(
                      height: 20,
                    ),
                    Text("Random ID: $randomId"),
                    const Text(
                      "Selected GIF",
                      style:
                          TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(
                      height: 10,
                    ),
                    currentGif != null
                        ? SizedBox(
                            child: GiphyGifWidget(
                              imageAlignment: Alignment.center,
                              gif: currentGif!,
                              giphyGetWrapper: giphyGetWrapper,
                              borderRadius: BorderRadius.circular(30),
                              showGiphyLabel: true,
                            ),
                          )
                        : const Text("No GIF")
                  ],
                ),
              ),
            ),
            floatingActionButton: FloatingActionButton(
                onPressed: () async {
                  giphyGetWrapper.getGif('', context);
                },
                tooltip: 'Open Sticker',
                child: const Icon(Icons
                    .insert_emoticon)), // 这个逗号使自动格式化更美观
          );
        });
  }
}

更多关于Flutter GIF选择插件giphy_selector的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

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


当然,以下是如何在Flutter项目中使用giphy_selector插件来选择GIF的示例代码。giphy_selector插件允许用户从GIPHY API中选择GIF并获取其URL。

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

dependencies:
  flutter:
    sdk: flutter
  giphy_selector: ^latest_version  # 请替换为最新的版本号

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

接下来,配置GIPHY API密钥。你需要在GIPHY官网注册并获取一个API密钥。然后,在你的Flutter项目中,可以通过环境变量或直接在代码中设置这个密钥(注意:出于安全考虑,不建议直接在代码中硬编码API密钥,最好使用环境变量或配置文件)。

以下是一个完整的示例代码,展示如何使用giphy_selector插件:

import 'package:flutter/material.dart';
import 'package:giphy_selector/giphy_selector.dart';

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  String? selectedGifUrl;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Giphy Selector Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            if (selectedGifUrl != null)
              Image.network(selectedGifUrl!, fit: BoxFit.cover, width: 300),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                // 在这里设置你的GIPHY API密钥
                String apiKey = 'YOUR_GIPHY_API_KEY'; // 请替换为你的GIPHY API密钥
                
                // 打开Giphy选择器
                GiphySelector.showDialog(
                  context: context,
                  apiKey: apiKey,
                  limit: 10, // 设置显示的GIF数量
                  quality: 'hd', // 设置GIF质量
                ).then((result) {
                  if (result != null && result.length > 0) {
                    setState(() {
                      selectedGifUrl = result[0]['images']['fixed_height']['url'];
                    });
                  }
                });
              },
              child: Text('Select GIF'),
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中:

  1. MyApp是应用程序的根widget。
  2. MyHomePage是一个包含按钮和图像显示区域的StatefulWidget。
  3. 当用户点击“Select GIF”按钮时,会调用GiphySelector.showDialog方法,显示GIF选择器对话框。
  4. 用户选择一个GIF后,结果会通过.then()回调返回,并将选中的GIF URL设置为selectedGifUrl。
  5. 如果selectedGifUrl不为空,则显示选中的GIF图像。

请确保将YOUR_GIPHY_API_KEY替换为你从GIPHY官网获取的API密钥。

这样,你就可以在Flutter应用中实现GIF选择了。

回到顶部