Flutter字体选择插件flutter_font_picker的使用

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

Flutter字体选择插件 flutter_font_picker 的使用

flutter_font_picker 是一个允许用户从自定义下拉菜单中选择并应用 Google 字体的 Flutter 小部件。它依赖于 google_fonts 包来加载和显示字体,并支持多语言本地化。

简单示例

在您的 build 方法中,可以使用按钮,当按下时,会导航到字体选择屏幕:

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

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Font Picker Demo',
      theme: ThemeData(
        primarySwatch: Colors.teal,
      ),
      home: const MyHomePage(title: 'Font Picker Demo'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  PickerFont? _selectedFont;
  final List<String> _myGoogleFonts = [
    "Abril Fatface",
    "Aclonica",
    "Alegreya Sans",
    // 添加更多字体...
  ];

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(24.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                child: const Text('Pick a font (with a screen)'),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => FontPicker(
                        onFontChanged: (font) {
                          setState(() {
                            _selectedFont = font;
                          });
                          debugPrint(
                            "${font.fontFamily} with font weight ${font.fontWeight} and font style ${font.fontStyle}. FontSpec: ${font.toFontSpec()}",
                          );
                        },
                        googleFonts: _myGoogleFonts,
                      ),
                    ),
                  );
                },
              ),
              if (_selectedFont != null)
                Text(
                  'This will be styled with the font: ${_selectedFont!.fontFamily}',
                  style: _selectedFont!.toTextStyle(),
                ),
            ],
          ),
        ),
      ),
    );
  }
}

解释:

  1. 导入包:确保导入了 flutter_font_pickergoogle_fonts
  2. 创建 _selectedFont 变量:用于存储用户选择的字体。
  3. 按钮:点击按钮后,弹出字体选择界面。
  4. onFontChanged 回调:当用户选择一个字体时,更新 _selectedFont 并打印选择信息。
  5. 显示所选字体:如果已选择字体,则使用 toTextStyle() 方法将其应用于文本。

FontPicker 设置选项

  • onFontChanged: 必需参数,返回包含所选字体详细信息的对象。
  • googleFonts: 要在字体选择器中使用的 Google 字体列表,默认包含所有 975 种字体。建议仅使用有限数量的字体以提高性能。
  • initialFontFamily: 初始字体,默认为 'Roboto'
  • showFontInfo: 是否显示字体详情(类别、变体数)。
  • showFontVariants: 是否显示字体变体(粗细和样式)。
  • showInDialog: 设置为 true 以在 AlertDialog 中使用字体选择器。
  • recentsCount: 保存最近使用的字体数量。
  • lang: 显示 UI 的语言,默认为英文 ('en')。

完整示例 DEMO

以下是一个完整的示例,展示了如何在应用程序中集成 flutter_font_picker 插件:

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

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Font Picker Demo',
      theme: ThemeData(
        primarySwatch: Colors.teal,
      ),
      home: const MyHomePage(title: 'Font Picker Demo'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  String _selectedFont = "Roboto";
  TextStyle? _selectedFontTextStyle;
  final List<String> _myGoogleFonts = [
    "Abril Fatface",
    "Aclonica",
    "Alegreya Sans",
    "Architects Daughter",
    "Archivo",
    "Archivo Narrow",
    "Bebas Neue",
    "Bitter",
    "Bree Serif",
    "Bungee",
    "Cabin",
    "Cairo",
    "Coda",
    "Comfortaa",
    "Comic Neue",
    "Cousine",
    "Croissant One",
    "Faster One",
    "Forum",
    "Great Vibes",
    "Heebo",
    "Inconsolata",
    "Josefin Slab",
    "Lato",
    "Libre Baskerville",
    "Lobster",
    "Lora",
    "Merriweather",
    "Montserrat",
    "Mukta",
    "Nunito",
    "Offside",
    "Open Sans",
    "Oswald",
    "Overlock",
    "Pacifico",
    "Playfair Display",
    "Poppins",
    "Raleway",
    "Roboto",
    "Roboto Mono",
    "Source Sans Pro",
    "Space Mono",
    "Spicy Rice",
    "Squada One",
    "Sue Ellen Francisco",
    "Trade Winds",
    "Ubuntu",
    "Varela",
    "Vollkorn",
    "Work Sans",
    "Zilla Slab",
  ];

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(24.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                child: const Text('Pick a font (with a screen)'),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => FontPicker(
                        recentsCount: 10,
                        onFontChanged: (font) {
                          setState(() {
                            _selectedFont = font.fontFamily;
                            _selectedFontTextStyle = font.toTextStyle();
                          });
                          debugPrint(
                            "${font.fontFamily} with font weight ${font.fontWeight} and font style ${font.fontStyle}. FontSpec: ${font.toFontSpec()}",
                          );
                        },
                        googleFonts: _myGoogleFonts,
                      ),
                    ),
                  );
                },
              ),
              ElevatedButton(
                child: const Text('Pick a font (with a dialog)'),
                onPressed: () {
                  showDialog(
                    context: context,
                    builder: (context) {
                      return AlertDialog(
                        content: SingleChildScrollView(
                          child: SizedBox(
                            width: double.maxFinite,
                            child: FontPicker(
                              showInDialog: true,
                              initialFontFamily: 'Anton',
                              onFontChanged: (font) {
                                setState(() {
                                  _selectedFont = font.fontFamily;
                                  _selectedFontTextStyle = font.toTextStyle();
                                });
                                debugPrint(
                                  "${font.fontFamily} with font weight ${font.fontWeight} and font style ${font.fontStyle}. FontSpec: ${font.toFontSpec()}",
                                );
                              },
                              googleFonts: _myGoogleFonts,
                            ),
                          ),
                        ),
                      );
                    },
                  );
                },
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Expanded(
                    child: Padding(
                      padding: EdgeInsets.all(8.0),
                      child: Text(
                        'Pick a font: ',
                        textAlign: TextAlign.right,
                        style: TextStyle(fontWeight: FontWeight.w700),
                      ),
                    ),
                  ),
                  Expanded(
                    child: TextField(
                      readOnly: true,
                      textAlign: TextAlign.center,
                      decoration: InputDecoration(
                        suffixIcon: const Icon(Icons.arrow_drop_down_sharp),
                        hintText: _selectedFont,
                        border: InputBorder.none,
                      ),
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => FontPicker(
                              onFontChanged: (font) {
                                setState(() {
                                  _selectedFont = font.fontFamily;
                                  _selectedFontTextStyle = font.toTextStyle();
                                });
                                debugPrint(
                                  "${font.fontFamily} with font weight ${font.fontWeight} and font style ${font.fontStyle}. FontSpec: ${font.toFontSpec()}",
                                );
                              },
                              googleFonts: _myGoogleFonts,
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                ],
              ),
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: Container(
                    decoration: BoxDecoration(
                      border: Border.all(
                        color: Colors.blueGrey,
                        width: 2.0,
                      ),
                    ),
                    child: Padding(
                      padding: const EdgeInsets.all(12.0),
                      child: Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              'Font: $_selectedFont',
                              style: _selectedFontTextStyle,
                            ),
                            Text(
                              'The quick brown fox jumped',
                              style: _selectedFontTextStyle,
                            ),
                            Text(
                              'over the lazy dog',
                              style: _selectedFontTextStyle,
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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

1 回复

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


当然,以下是如何在Flutter应用中使用flutter_font_picker插件的一个示例代码案例。这个插件允许用户从预定义的字体列表中选择字体,并将其应用于文本。

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

dependencies:
  flutter:
    sdk: flutter
  flutter_font_picker: ^x.y.z  # 替换为最新版本号

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

接下来,你可以在你的Flutter应用中使用这个插件。以下是一个完整的示例代码:

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  String? selectedFontName;
  TextStyle? selectedFontStyle;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Font Picker Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Selected Font:',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 16),
            Text(
              'Sample Text',
              style: selectedFontStyle ?? TextStyle(fontSize: 24),
            ),
            SizedBox(height: 32),
            ElevatedButton(
              onPressed: () async {
                FontPickerResult result = await FlutterFontPicker.showFontPicker(
                  context: context,
                  textStyle: TextStyle(fontSize: 24),
                  text: 'Sample Text',
                  showTextStyleButton: true,
                );

                if (result != null && result.fontFamily != null) {
                  setState(() {
                    selectedFontName = result.fontFamily!;
                    selectedFontStyle = result.textStyle;
                  });
                }
              },
              child: Text('Select Font'),
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中:

  1. 我们首先定义了一个MyApp类,它是应用的根组件。
  2. MyHomePage是一个有状态的组件,它包含用于显示所选字体和打开字体选择器的UI。
  3. selectedFontNameselectedFontStyle用于存储用户选择的字体名称和样式。
  4. FlutterFontPicker.showFontPicker方法用于显示字体选择器对话框。当用户选择一个字体时,更新selectedFontNameselectedFontStyle状态,这会触发UI的重新构建,以显示所选字体。

确保在实际项目中替换flutter_font_picker: ^x.y.z为最新的版本号,你可以在pub.dev上查找最新版本。

这个示例展示了如何使用flutter_font_picker插件来选择字体并将其应用于文本。你可以根据需要进一步自定义和扩展这个示例。

回到顶部