Flutter GIF搜索与展示插件giphy_get的使用

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

Flutter GIF搜索与展示插件giphy_get的使用

giphy_get

Flutter_Tests pub package platform-flutter style-lint

Overview

此包允许通过纯Dart代码从GIPHY获取GIF、贴纸或表情符号,遵循Giphy SDK设计指南

灵感

结果

Getting Started

重要!您必须在Giphy Developers注册您的应用并获取API密钥。

Localizations

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

return MaterialApp(
  title: 'Giphy Get Demo',
  localizationsDelegates: [
    // 默认代理
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,

    // 添加这行
    GiphyGetUILocalizations.delegate
  ],
  supportedLocales: [
    // 您支持的语言
    Locale('en', ''),
    Locale('es', ''),
    Locale('da', ''),
  ],
  home: MyHomePage(title: 'Giphy Get Demo'),
  themeMode: Provider.of<ThemeProvider>(context).currentTheme,
);

获取GIF

获取单个GIF

import 'package:giphy_get/giphy_get.dart';

GiphyGif gif = await GiphyGet.getGif(
  context: context, // 必填
  apiKey: "your api key HERE", // 必填。
  lang: GiphyLanguage.english, // 可选 - 查询语言。
  randomID: "abcd", // 可选 - 特定用户的ID/代理。
  tabColor: Colors.teal, // 可选 - 默认强调色。
  debounceTimeInMilliseconds: 350, // 可选 - 搜索按键之间的暂停时间
);

Options

Value Type Description Default
lang String 使用ISO 639-1语言代码或GiphyLanguage常量 GiphyLanguage.english
randomID String 特定用户的ID/代理 null
searchText String 输入搜索提示,建议使用flutter_18n包进行翻译 "Search GIPHY"
tabColor Color 标签和加载进度的颜色 Theme.of(context).accentColor
debounceTimeInMilliseconds int 搜索按键之间的暂停时间 350
showGIFs bool 是否显示GIF标签 true
showStickers bool 是否显示贴纸标签 true
showEmojis bool 是否显示表情符号标签 true
tapTopBuilder Widget Function(BuildContext context) 自定义标签顶部构建器 null. 显示默认Giphy样式的标签顶部
tabBottomBuilder Widget Function(BuildContext context) 自定义标签底部构建器。注意:Giphy要求必须显示版权信息 null. 显示默认Giphy版权标志
searchAppBarBuilder Widget Function(BuildContext context, FocusNode focusNode, bool autofocus, TextEditingController textEditingController, void Function() onClearSearch) 自定义搜索栏输入构建器 null. 显示默认Giphy样式的搜索栏输入

获取随机ID

GiphyClient giphyClient = GiphyClient(apiKey: "YOUR API KEY");
String randomId = await giphyClient.getRandomId();

Widgets

可选但如果您想获取更多用户GIF或查看Giphy上的内容,遵循Giphy设计指南,则此小部件是必需的。

GIPHY

GiphyGifWidget

Value Type Description Default
gif (必填) GiphyGif 来自流或JSON的GiphyGif对象 null
giphyGetWrapper (必填) GiphyGetWrapper 用于“点击查看更多”的实例 null
showGiphyLabel boolean 显示或隐藏底部的“由GIPHY提供动力”标签 true
borderRadius BorderRadius ex: BorderRadius.circular(10) 为图像添加圆角 null
imageAlignment Alignment 此小部件是一个Stack,包含图像和点击按钮,此属性调整对齐方式 Alignment.center

GiphyGetWrapper

Value Type Description Default
giphy_api_key 必填 String 您的Giphy API密钥 null
builder function 返回Stream<GiphyGif>和GiphyGetWrapper实例 null

方法

void getGif(String queryText,BuildContext context)
return GiphyGetWrapper(
    giphy_api_key: REPLACE_WITH YOUR_API_KEY,
    // Builder with Stream<GiphyGif> and Instance of GiphyGetWrapper
    builder: (stream, giphyGetWrapper) => StreamBuilder<GiphyGif>(
      stream: stream,
      builder: (context, snapshot) {
        return Scaffold(
          body: snapshot.hasData
              ? SizedBox(
                // GiphyGifWidget with tap to more
                child: GiphyGifWidget(
                  imageAlignment: Alignment.center,
                  gif: snapshot.data,
                  giphyGetWrapper: giphyGetWrapper,
                  borderRadius: BorderRadius.circular(30),
                  showGiphyLabel: true,
                ),
              )
              : Text("No GIF"),
          floatingActionButton: FloatingActionButton(
            onPressed: () async {
              //Open Giphy Sheet
              giphyGetWrapper.getGif('', context);
            },
            tooltip: 'Open Sticker',
            child: Icon(Icons.insert_emoticon)),
        );
    })

    });

示例APP

首先导出您的Giphy API密钥:

export GIPHY_API_KEY=YOUR_GIPHY_API_KEY

然后运行。

完整示例代码

import 'package:flutter/material.dart';
import 'package:giphy_get/giphy_get.dart';
import 'package:giphy_get/l10n.dart';
import 'package:giphy_get_demo/providers/theme_provider.dart';
import 'package:provider/provider.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  runApp(MultiProvider(providers: [
    ChangeNotifierProvider(
        create: (ctx) => ThemeProvider(currentTheme: ThemeMode.system))
  ], child: const MyApp()));
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Giphy Get Demo',
      theme: ThemeData(
          brightness: Brightness.light,
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
          useMaterial3: Provider.of<ThemeProvider>(context).material3),
      darkTheme: ThemeData(
          brightness: Brightness.dark,
          primarySwatch: Colors.purple,
          visualDensity: VisualDensity.adaptivePlatformDensity,
          useMaterial3: Provider.of<ThemeProvider>(context).material3),
      localizationsDelegates: [
        ...GlobalMaterialLocalizations.delegates,
        GlobalWidgetsLocalizations.delegate,
        GiphyGetUILocalizations.delegate
      ],
      supportedLocales: const [
        Locale('en', ''),
        Locale('es', ''),
        Locale('da', ''),
        Locale('fr', ''),
      ],
      home: const MyHomePage(title: 'Giphy Get Demo'),
      themeMode: Provider.of<ThemeProvider>(context).currentTheme,
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  const MyHomePage({required this.title, super.key});
  
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late ThemeProvider themeProvider = Provider.of<ThemeProvider>(context);

  GiphyGif? currentGif;
  late GiphyClient client = GiphyClient(apiKey: giphyApiKey, randomId: '');
  String randomId = "";
  String giphyApiKey = const String.fromEnvironment("GIPHY_API_KEY");

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      client.getRandomId().then((value) {
        setState(() {
          randomId = value;
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return GiphyGetWrapper(
        giphy_api_key: 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("GET DEMO")
                ],
              ),
            ),
            body: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                children: [
                  Row(
                    children: [
                      const Expanded(child: Text("Dark Mode")),
                      Switch(
                          value:
                              Theme.of(context).brightness == Brightness.dark,
                          onChanged: (value) {
                            themeProvider.setCurrentTheme(
                                value ? ThemeMode.dark : ThemeMode.light);
                          })
                    ],
                  ),
                  Row(
                    children: [
                      const Expanded(child: Text("Material 3")),
                      Switch(
                          value: themeProvider.material3,
                          onChanged: (value) {
                            themeProvider.setMaterial3(value);
                          })
                    ],
                  ),
                  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,
                    showGIFs: true,
                    showStickers: true,
                    showEmojis: true,
                  );
                },
                tooltip: 'Open Sticker',
                child: const Icon(Icons.insert_emoticon)),
          );
        });
  }
}

更多关于Flutter GIF搜索与展示插件giphy_get的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter GIF搜索与展示插件giphy_get的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个使用Flutter的giphy_get插件进行GIF搜索与展示的示例代码。这个插件允许你从GIPHY API中获取GIF,并在Flutter应用中展示它们。

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

dependencies:
  flutter:
    sdk: flutter
  giphy_get: ^latest_version  # 请使用最新版本号替换latest_version

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

接下来,创建一个简单的Flutter应用,展示如何使用giphy_get插件。

主文件 main.dart

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

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

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

class GiphySearchScreen extends StatefulWidget {
  @override
  _GiphySearchScreenState createState() => _GiphySearchScreenState();
}

class _GiphySearchScreenState extends State<GiphySearchScreen> {
  final TextEditingController _searchController = TextEditingController();
  List<GiphyImage> _giphys = [];

  void _searchGiphys() async {
    setState(() {
      _giphys = [];
    });

    String query = _searchController.text;
    if (query.isEmpty) {
      return;
    }

    try {
      List<GiphyImage> result = await GiphyGet.searchGifs(query);
      setState(() {
        _giphys = result;
      });
    } catch (e) {
      print("Error fetching giphys: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GIPHY Search'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _searchController,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Search GIFs',
                suffixIcon: IconButton(
                  icon: Icon(Icons.search),
                  onPressed: _searchGiphys,
                ),
              ),
            ),
            SizedBox(height: 16),
            Expanded(
              child: GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  crossAxisSpacing: 8,
                  mainAxisSpacing: 8,
                ),
                itemCount: _giphys.length,
                itemBuilder: (context, index) {
                  GiphyImage giphy = _giphys[index];
                  return GestureDetector(
                    onTap: () {
                      // Navigate to full screen view or any other action
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => GiphyDetailScreen(giphy),
                        ),
                      );
                    },
                    child: Image.network(
                      giphy.images.fixed_height.url,
                      fit: BoxFit.cover,
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class GiphyDetailScreen extends StatelessWidget {
  final GiphyImage giphy;

  GiphyDetailScreen(this.giphy);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GIF Detail'),
      ),
      body: Center(
        child: Image.network(
          giphy.images.fixed_height_small.url,
          fit: BoxFit.cover,
        ),
      ),
    );
  }
}

说明

  1. 依赖安装:确保在pubspec.yaml中添加了giphy_get依赖,并运行flutter pub get
  2. 搜索功能:在GiphySearchScreen中,使用TextField来输入搜索词,点击搜索图标或按键盘回车键时调用_searchGiphys方法,从GIPHY API获取GIF列表。
  3. 展示GIF:使用GridView.builder来展示搜索到的GIF列表,每个GIF项都是一个Image.network,其URL从GIPHY API获取。
  4. 详情页面:点击某个GIF时,跳转到详情页面GiphyDetailScreen,展示该GIF的详细视图。

这个示例展示了如何使用giphy_get插件进行GIF搜索和展示。你可以根据需要进行扩展和修改,比如添加加载状态、错误处理、更多的UI美化等。

回到顶部