Flutter引用名言插件quotable_flutter的使用

Flutter引用名言插件quotable_flutter的使用

特性

本插件(非官方)使用了一个名为 Quotable 的免费开源名言API。

截图 2022-06-27 at 19 20 52

通过此插件,您可以获取随机名言、名言列表或按名言和作者搜索。您还可以使用标签过滤名言,并根据参数进行排序或排序。

开始使用

首先,您需要定义 QuoteAuthor 模型。

// Quote Model
Quote({
    String id,
    String content,
    String author,
    int length,
    List<String> tags,
});

// Author Model
Author({
    String id,
    String bio,
    String description,
    String link,
    String name,
    String slug,
    int quoteCount,
});

然后,您可以通过以下方法从 Quotable 仓库获取名言:

// 获取随机名言
Future<Quote> Quotable.getRandom({
    List<String>? tags, 
    int? maxLength, 
    int? minLength,
});

// 获取名言列表
Future<List<Quote>> Quotable.getListQuotes({
    List<String>? tags,
    List<String>? authors,
    SortBy sortBy = SortBy.dateAdded,
    Order order = Order.desc,
    int page = 1,
    int limit = 20,
})

// 搜索名言
Future<List<Quote>> Quotable.searchQuotes({
    required String query,
    int page = 1,
    int limit = 20,
})

// 搜索作者
Future<List<Author>> Quotable.searchAuthor({
    required String query,
    int page = 1,
    int limit = 20,
})

如果您对 pagelimit 或它们如何一起工作感到困惑,可以阅读 Quotable 文档 中的表格。

使用示例

以下是一个完整的示例,展示了如何在 Flutter 应用程序中使用 quotable_flutter 插件。

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

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: QuotableDemo(),
    );
  }
}

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Quotable Demo')),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                'Get Random Quote',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 24),
              ),
              FutureBuilder<Quote>(
                future: Quotable.getRandom(),
                builder: (_, snapshot) {
                  if (snapshot.hasData) {
                    Quote quote = snapshot.data!;

                    return ListTile(
                      title: Text(quote.author),
                      subtitle: Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('quote: ${quote.content}'),
                          Text('tags: ${quote.tags.toString()}'),
                          Text('id: ${quote.id}'),
                        ],
                      ),
                    );
                  } else {
                    return const CircularProgressIndicator();
                  }
                },
              ),
              const SizedBox(height: 20),
              const Text(
                'Get List of Quotes',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 24),
              ),
              FutureBuilder<List<Quote>>(
                future: Quotable.getListQuotes(limit: 2),
                builder: (_, snapshot) {
                  if (snapshot.hasData) {
                    List<Quote> quotes = snapshot.data!;

                    return ListView.separated(
                      separatorBuilder: (_, __) => const Divider(height: 0),
                      itemCount: quotes.length,
                      shrinkWrap: true,
                      itemBuilder: (_, index) {
                        Quote quote = quotes[index];
                        return ListTile(
                          title: Text(quote.author),
                          subtitle: Text(quote.content),
                        );
                      },
                    );
                  } else {
                    return const CircularProgressIndicator();
                  }
                },
              ),
              const SizedBox(height: 20),
              const Text(
                "Search Quotes ('wisdom')",
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 24),
              ),
              FutureBuilder<List<Quote>>(
                future: Quotable.searchQuotes(query: 'wisdom', limit: 3),
                builder: (_, snapshot) {
                  if (snapshot.hasData) {
                    List<Quote> quotes = snapshot.data!;

                    return ListView.separated(
                      separatorBuilder: (_, __) => const Divider(height: 0),
                      itemCount: quotes.length,
                      shrinkWrap: true,
                      itemBuilder: (_, index) {
                        Quote quote = quotes[index];
                        return ListTile(
                          title: Text(quote.author),
                          subtitle: Text(quote.content),
                        );
                      },
                    );
                  } else {
                    return const CircularProgressIndicator();
                  }
                },
              ),
              const SizedBox(height: 20),
              const Text(
                "Search Authors ('einstein')",
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 24),
              ),
              FutureBuilder<List<Author>>(
                future: Quotable.searchAuthor(query: 'einstein', limit: 3),
                builder: (_, snapshot) {
                  if (snapshot.hasData) {
                    List<Author> authors = snapshot.data!;

                    return ListView.separated(
                      separatorBuilder: (_, __) => const Divider(height: 0),
                      itemCount: authors.length,
                      shrinkWrap: true,
                      itemBuilder: (_, index) {
                        Author author = authors[index];
                        return ListTile(
                          leading: IconButton(
                            icon: const Icon(Icons.link),
                            onPressed: () => print(author.link),
                          ),
                          title: Text(author.name),
                          subtitle: Column(
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text('- ${author.description}'),
                              Text('- ${author.bio}'),
                              Text('- ${author.slug}'),
                              Text('- ${author.quoteCount.toString()}'),
                            ],
                          ),
                        );
                      },
                    );
                  } else {
                    return const CircularProgressIndicator();
                  }
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter引用名言插件quotable_flutter的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

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


quotable_flutter 是一个 Flutter 插件,用于从 Quotable API 获取名言警句。使用这个插件,你可以轻松地在你的 Flutter 应用中显示随机的名言。

安装插件

首先,你需要在 pubspec.yaml 文件中添加 quotable_flutter 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  quotable_flutter: ^1.0.0  # 请查看最新版本

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

使用插件

  1. 导入包:在需要使用 quotable_flutter 的文件中导入包。
import 'package:quotable_flutter/quotable_flutter.dart';
  1. 获取名言:使用 Quotable 类的 getRandomQuote 方法来获取随机名言。
Future<void> fetchRandomQuote() async {
  try {
    Quote quote = await Quotable.getRandomQuote();
    print('Quote: ${quote.content}');
    print('Author: ${quote.author}');
  } catch (e) {
    print('Failed to fetch quote: $e');
  }
}
  1. 在 UI 中显示名言:你可以将获取到的名言显示在应用的 UI 中。
class QuoteScreen extends StatefulWidget {
  [@override](/user/override)
  _QuoteScreenState createState() => _QuoteScreenState();
}

class _QuoteScreenState extends State<QuoteScreen> {
  Quote? _quote;

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

  Future<void> fetchRandomQuote() async {
    try {
      Quote quote = await Quotable.getRandomQuote();
      setState(() {
        _quote = quote;
      });
    } catch (e) {
      print('Failed to fetch quote: $e');
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Random Quote'),
      ),
      body: Center(
        child: _quote == null
            ? CircularProgressIndicator()
            : Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    _quote!.content,
                    style: TextStyle(fontSize: 20),
                    textAlign: TextAlign.center,
                  ),
                  SizedBox(height: 10),
                  Text(
                    '- ${_quote!.author}',
                    style: TextStyle(fontSize: 16, fontStyle: FontStyle.italic),
                  ),
                ],
              ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: fetchRandomQuote,
        child: Icon(Icons.refresh),
      ),
    );
  }
}
回到顶部