Flutter引用名言插件quotable的使用

Flutter引用名言插件quotable的使用

quotable-dart

quotable-dart 是一个简单的 API 包装器,用于访问 https://github.com/lukePeavey/quotable 提供的名言 API。

使用方法

以下是如何在 Flutter 项目中使用 quotable-dart 的示例代码:

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  [@override](/user/override)
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String _quoteContent = '';
  String _quoteAuthor = '';

  Future<void> _fetchRandomQuote() async {
    final quote = await getRandomQuote(author: 'johann-wolfgang-von-goethe');
    setState(() {
      _quoteContent = quote.content;
      _quoteAuthor = quote.author;
    });
  }

  Future<void> _fetchListQuotes() async {
    final quotes = await getQuotes(limit: 2, sortBy: SortByQuote.author);
    List<String> contents = [];
    for (var item in quotes.results) {
      contents.add(item.content);
    }
    setState(() {
      _quoteContent = contents.join('\n');
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Quotable 插件示例'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: _fetchRandomQuote,
              child: Text('获取随机名言'),
            ),
            SizedBox(height: 20),
            Text(
              _quoteContent,
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 10),
            Text(
              '- $_quoteAuthor',
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 14),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _fetchListQuotes,
              child: Text('获取多条名言'),
            ),
          ],
        ),
      ),
    );
  }
}

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

1 回复

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


在 Flutter 中使用 quotable 插件来引用名言,首先需要了解 quotable 是一个提供随机名言的 API 服务。你可以通过 HTTP 请求来获取名言数据,并将其显示在你的 Flutter 应用中。

以下是一个简单的步骤指南,展示如何在 Flutter 中使用 quotable API 来获取并显示名言。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 http 依赖,用于发送 HTTP 请求。

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3

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

2. 创建获取名言的函数

接下来,你可以创建一个函数来从 quotable API 获取名言数据。

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<Map<String, dynamic>> fetchQuote() async {
  final response = await http.get(Uri.parse('https://api.quotable.io/random'));

  if (response.statusCode == 200) {
    return json.decode(response.body);
  } else {
    throw Exception('Failed to load quote');
  }
}

3. 在 UI 中显示名言

现在,你可以在 Flutter 的 UI 中使用 FutureBuilder 来获取并显示名言。

import 'package:flutter/material.dart';

class QuoteScreen extends StatefulWidget {
  [@override](/user/override)
  _QuoteScreenState createState() => _QuoteScreenState();
}

class _QuoteScreenState extends State<QuoteScreen> {
  Future<Map<String, dynamic>> futureQuote;

  [@override](/user/override)
  void initState() {
    super.initState();
    futureQuote = fetchQuote();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Quotable Quotes'),
      ),
      body: Center(
        child: FutureBuilder<Map<String, dynamic>>(
          future: futureQuote,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return CircularProgressIndicator();
            } else if (snapshot.hasError) {
              return Text('Error: ${snapshot.error}');
            } else if (snapshot.hasData) {
              return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    snapshot.data['content'],
                    style: TextStyle(fontSize: 24, fontStyle: FontStyle.italic),
                    textAlign: TextAlign.center,
                  ),
                  SizedBox(height: 10),
                  Text(
                    '- ${snapshot.data['author']}',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                ],
              );
            } else {
              return Text('No data found');
            }
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            futureQuote = fetchQuote();
          });
        },
        child: Icon(Icons.refresh),
      ),
    );
  }
}

4. 运行应用

最后,你可以在 main.dart 中运行这个应用。

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Quotable Quotes',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: QuoteScreen(),
    );
  }
}
回到顶部