Flutter颜色选择器插件flex_color_picker的使用

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

Flutter颜色选择器插件flex_color_picker的使用

简介

FlexColorPicker 是一个为Flutter应用提供的可定制化颜色选择器。它能够展示六种不同类型的颜色选择器,包括Material Design 2的颜色及其色调。此外,它还支持生成符合Material Design 3颜色系统的调色板,并且可以在Windows、Mac、Linux和Web平台上使用。

插件特性

  • 支持多种类型的颜色选择器(如:主色、强调色、自定义颜色等)
  • 可以生成Material Design 3准确的色调调色板
  • 具有桌面平台兼容性,包含焦点处理以及复制粘贴功能
  • 提供了丰富的API用于定制样式与行为

安装

pubspec.yaml 文件中添加依赖:

dependencies:
  flex_color_picker: ^latest_version

然后运行命令来安装包:

flutter pub get

使用示例

下面是一个完整的示例代码,展示了如何将 FlexColorPicker 集成到您的Flutter项目中:

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

void main() => runApp(MyApp());

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

class ColorPickerPage extends StatefulWidget {
  @override
  _ColorPickerPageState createState() => _ColorPickerPageState();
}

class _ColorPickerPageState extends State<ColorPickerPage> {
  late Color screenPickerColor;
  late Color dialogPickerColor;
  late Color dialogSelectColor;

  // 自定义颜色映射表
  final Map<ColorSwatch<Object>, String> colorsNameMap = <ColorSwatch<Object>, String>{
    ColorTools.createPrimarySwatch(const Color(0xFF6200EE)): 'Guide Purple',
    ColorTools.createPrimarySwatch(const Color(0xFF3700B3)): 'Guide Purple Variant',
    ColorTools.createAccentSwatch(const Color(0xFF03DAC6)): 'Guide Teal',
    ColorTools.createAccentSwatch(const Color(0xFF018786)): 'Guide Teal Variant',
    ColorTools.createPrimarySwatch(const Color(0xFFB00020)): 'Guide Error',
    ColorTools.createPrimarySwatch(const Color(0xFFCF6679)): 'Guide Error Dark',
    ColorTools.createPrimarySwatch(const Color(0xFF174378)): 'Blue blues',
  };

  @override
  void initState() {
    super.initState();
    screenPickerColor = Colors.blue;
    dialogPickerColor = Colors.red;
    dialogSelectColor = const Color(0xFFA239CA);
  }

  Future<bool> colorPickerDialog() async {
    return await ColorPicker(
      color: dialogPickerColor,
      onColorChanged: (Color color) => setState(() => dialogPickerColor = color),
      width: 40,
      height: 40,
      borderRadius: 4,
      spacing: 5,
      runSpacing: 5,
      wheelDiameter: 155,
      heading: Text('Select color', style: Theme.of(context).textTheme.titleMedium),
      subheading: Text('Select color shade', style: Theme.of(context).textTheme.titleMedium),
      wheelSubheading: Text('Selected color and its shades', style: Theme.of(context).textTheme.titleMedium),
      showMaterialName: true,
      showColorName: true,
      showColorCode: true,
      copyPasteBehavior: const ColorPickerCopyPasteBehavior(longPressMenu: true),
      pickersEnabled: const <ColorPickerType, bool>{
        ColorPickerType.primary: true,
        ColorPickerType.accent: true,
        ColorPickerType.custom: true,
        ColorPickerType.wheel: true,
      },
      customColorSwatchesAndNames: colorsNameMap,
    ).showPickerDialog(
      context,
      constraints: const BoxConstraints(minHeight: 480, minWidth: 320, maxWidth: 320),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('ColorPicker Demo')),
      body: ListView(
        padding: EdgeInsets.all(8.0),
        children: <Widget>[
          ListTile(
            title: Text('Click this color to modify it in a dialog.'),
            subtitle: Text('${ColorTools.materialNameAndCode(dialogPickerColor, colorSwatchNameMap: colorsNameMap)} '
                'aka ${ColorTools.nameThatColor(dialogPickerColor)}'),
            trailing: ColorIndicator(
              width: 44,
              height: 44,
              borderRadius: 4,
              color: dialogPickerColor,
              onSelectFocus: false,
              onSelect: () async {
                final Color colorBeforeDialog = dialogPickerColor;
                if (!(await colorPickerDialog())) {
                  setState(() => dialogPickerColor = colorBeforeDialog);
                }
              },
            ),
          ),
          ListTile(
            title: Text('Select color below to change this color'),
            subtitle: Text('${ColorTools.materialNameAndCode(screenPickerColor)} '
                'aka ${ColorTools.nameThatColor(screenPickerColor)}'),
            trailing: ColorIndicator(
              width: 44,
              height: 44,
              borderRadius: 22,
              color: screenPickerColor,
            ),
          ),
          SizedBox(
            width: double.infinity,
            child: Padding(
              padding: const EdgeInsets.all(6),
              child: Card(
                elevation: 2,
                child: ColorPicker(
                  color: screenPickerColor,
                  onColorChanged: (Color color) => setState(() => screenPickerColor = color),
                  width: 44,
                  height: 44,
                  borderRadius: 22,
                  heading: Text('Select color', style: Theme.of(context).textTheme.headlineSmall),
                  subheading: Text('Select color shade', style: Theme.of(context).textTheme.titleMedium),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

此示例演示了如何创建一个简单的Flutter应用程序,其中包含两个不同的颜色选择器实例。第一个实例是通过对话框显示颜色选择器,第二个实例直接嵌入到页面中作为卡片形式呈现。用户可以选择颜色并查看所选颜色的信息。

希望这个指南能帮助您更好地理解和使用 flex_color_picker 插件!如果您有任何问题或需要进一步的帮助,请随时提问。


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

1 回复

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


当然,以下是一个关于如何在Flutter项目中使用flex_color_picker插件的示例代码。这个插件提供了一个灵活的颜色选择器,允许用户通过不同的方式选择颜色。

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

dependencies:
  flutter:
    sdk: flutter
  flex_color_picker: ^3.0.6  # 请确保版本号是最新的

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

接下来,在你的Flutter应用中,你可以使用FlexColorPicker小部件来展示颜色选择器。以下是一个完整的示例,展示了如何在一个简单的Flutter应用中集成并使用flex_color_picker

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

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

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

class ColorPickerExample extends StatefulWidget {
  @override
  _ColorPickerExampleState createState() => _ColorPickerExampleState();
}

class _ColorPickerExampleState extends State<ColorPickerExample> {
  Color selectedColor = Colors.black;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('FlexColorPicker Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            // 显示当前选中的颜色
            Container(
              decoration: BoxDecoration(
                border: Border.all(color: Colors.black, width: 2),
                shape: BoxShape.circle,
              ),
              height: 100,
              width: 100,
              color: selectedColor,
              child: Center(
                child: Text(
                  '#${selectedColor.value.toRadixString(16).toUpperCase().padStart(8, '0')}',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
            SizedBox(height: 20),

            // FlexColorPicker 按钮
            ElevatedButton(
              onPressed: () {
                showDialog(
                  context: context,
                  builder: (context) => AlertDialog(
                    title: Text('Choose a color'),
                    content: SingleChildScrollView(
                      child: ColorPicker(
                        color: selectedColor,
                        onColorChanged: (color) {
                          setState(() {
                            selectedColor = color;
                          });
                        },
                        pickerMode: ColorPickerMode.ALL,  // 可以选择 ALL, WHEEL, PALETTE, SLIDERS 等模式
                        enableAlpha: true,  // 是否启用透明度选择
                        showLabel: true,  // 是否显示颜色标签
                      ),
                    ),
                    actions: [
                      TextButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        child: Text('Cancel'),
                      ),
                      TextButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                          // 可以在这里处理颜色选择后的逻辑
                        },
                        child: Text('OK'),
                      ),
                    ],
                  ),
                );
              },
              child: Text('Choose Color'),
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,包含一个颜色选择器按钮和一个用于显示当前选中颜色的容器。当用户点击“Choose Color”按钮时,会弹出一个对话框,显示FlexColorPicker小部件。用户可以通过颜色选择器选择不同的颜色,选择完成后,颜色会显示在容器中,并且颜色的十六进制值会显示在容器的中心。

你可以根据需要调整ColorPicker的属性,例如pickerModeenableAlphashowLabel,以适应你的应用需求。

回到顶部