Flutter 颜色完全指南

什么是 Color?

在 Flutter 中,Color 类用于表示颜色,支持多种颜色表示方式。

颜色的表示方式

1. 预定义颜色

Flutter 提供了大量预定义的颜色常量。

dart 复制代码
// 基础颜色
Colors.red
Colors.blue
Colors.green
Colors.yellow
Colors.orange
Colors.purple
Colors.pink
Colors.brown
Colors.grey
Colors.black
Colors.white

2. 颜色深浅

每种颜色都有不同的深浅度(50-900)。

dart 复制代码
// 蓝色的不同深浅
Colors.blue[50]    // 最浅
Colors.blue[100]
Colors.blue[200]
Colors.blue[300]
Colors.blue[400]
Colors.blue[500]   // 默认
Colors.blue[600]
Colors.blue[700]
Colors.blue[800]
Colors.blue[900]   // 最深

3. ARGB 格式

使用 ARGB(透明度、红、绿、蓝)值创建颜色。

dart 复制代码
// Color.fromARGB(透明度, 红, 绿, 蓝)
Color(0xFFFF0000)           // 红色(完全不透明)
Color(0x80FF0000)           // 半透明红色

// 或使用 fromARGB
Color.fromARGB(255, 255, 0, 0)    // 红色
Color.fromARGB(128, 255, 0, 0)    // 半透明红色

4. RGB 格式

只指定 RGB 值,透明度默认为 255(完全不透明)。

dart 复制代码
Color.fromRGBO(255, 0, 0, 1.0)    // 红色,透明度 1.0
Color.fromRGBO(255, 0, 0, 0.5)    // 半透明红色,透明度 0.5

5. 十六进制颜色

dart 复制代码
// 格式:0xAARRGGBB
// AA = 透明度(00-FF)
// RR = 红色(00-FF)
// GG = 绿色(00-FF)
// BB = 蓝色(00-FF)

Color(0xFFFF0000)    // 红色
Color(0xFF00FF00)    // 绿色
Color(0xFF0000FF)    // 蓝色
Color(0xFFFFFFFF)    // 白色
Color(0xFF000000)    // 黑色

// 半透明
Color(0x80FF0000)    // 半透明红色(80 = 128/255)

颜色属性和方法

1. 透明度 opacity

dart 复制代码
Colors.red.withOpacity(0.5)    // 50% 透明度
Colors.blue.withOpacity(0.3)   // 30% 透明度
Colors.green.withOpacity(1.0)  // 完全不透明

2. 获取颜色值

dart 复制代码
Color color = Colors.red;

color.alpha    // 透明度值(0-255)
color.red      // 红色值(0-255)
color.green    // 绿色值(0-255)
color.blue     // 蓝色值(0-255)
color.opacity  // 透明度(0.0-1.0)
color.value    // 完整的 ARGB 值

3. 颜色混合

dart 复制代码
// 使用 Color.lerp 在两个颜色之间插值
Color.lerp(Colors.red, Colors.blue, 0.5)  // 红蓝混合 50%
Color.lerp(Colors.red, Colors.blue, 0.0)  // 完全是红色
Color.lerp(Colors.red, Colors.blue, 1.0)  // 完全是蓝色

Material Design 颜色

1. MaterialColor

dart 复制代码
// MaterialColor 包含一组深浅不同的颜色
MaterialColor red = Colors.red;

red[50]     // 最浅
red[100]
red[200]
red[300]
red[400]
red[500]    // 默认
red[600]
red[700]
red[800]
red[900]    // 最深

2. 主题色

dart 复制代码
// 在 MaterialApp 中定义主题色
MaterialApp(
  theme: ThemeData(
    primarySwatch: Colors.blue,      // 主色调
    primaryColor: Colors.blue,       // 主颜色
    accentColor: Colors.orange,      // 强调色(已废弃)
    colorScheme: ColorScheme.fromSeed(
      seedColor: Colors.blue,
    ),
  ),
)

3. 使用主题色

dart 复制代码
// 在组件中使用主题色
Container(
  color: Theme.of(context).primaryColor,
)

Text(
  '文本',
  style: TextStyle(
    color: Theme.of(context).colorScheme.primary,
  ),
)

颜色方案 ColorScheme

dart 复制代码
ColorScheme(
  brightness: Brightness.light,
  primary: Colors.blue,              // 主色
  onPrimary: Colors.white,           // 主色上的文字颜色
  secondary: Colors.orange,          // 次要色
  onSecondary: Colors.white,         // 次要色上的文字颜色
  error: Colors.red,                 // 错误色
  onError: Colors.white,             // 错误色上的文字颜色
  background: Colors.white,          // 背景色
  onBackground: Colors.black,        // 背景上的文字颜色
  surface: Colors.white,             // 表面色
  onSurface: Colors.black,           // 表面上的文字颜色
)

实战案例

案例1:基础颜色使用

dart 复制代码
Container(
  width: 100,
  height: 100,
  color: Colors.blue,
  child: Center(
    child: Text(
      '蓝色',
      style: TextStyle(color: Colors.white),
    ),
  ),
)

案例2:不同深浅的颜色

dart 复制代码
Row(
  children: [
    Container(width: 50, height: 50, color: Colors.blue[100]),
    Container(width: 50, height: 50, color: Colors.blue[300]),
    Container(width: 50, height: 50, color: Colors.blue[500]),
    Container(width: 50, height: 50, color: Colors.blue[700]),
    Container(width: 50, height: 50, color: Colors.blue[900]),
  ],
)

案例3:透明度

dart 复制代码
Stack(
  children: [
    Container(
      width: 200,
      height: 200,
      color: Colors.blue,
    ),
    Container(
      width: 150,
      height: 150,
      color: Colors.red.withOpacity(0.5),  // 半透明红色
    ),
    Container(
      width: 100,
      height: 100,
      color: Colors.green.withOpacity(0.5),  // 半透明绿色
    ),
  ],
)

案例4:渐变色

dart 复制代码
Container(
  width: 200,
  height: 200,
  decoration: BoxDecoration(
    gradient: LinearGradient(
      colors: [Colors.blue, Colors.purple],
      begin: Alignment.topLeft,
      end: Alignment.bottomRight,
    ),
  ),
)

案例5:自定义颜色

dart 复制代码
// 定义自己的颜色常量
class MyColors {
  static const Color primary = Color(0xFF2196F3);
  static const Color secondary = Color(0xFFFF9800);
  static const Color success = Color(0xFF4CAF50);
  static const Color warning = Color(0xFFFFC107);
  static const Color danger = Color(0xFFF44336);
  static const Color info = Color(0xFF00BCD4);
}

// 使用
Container(
  color: MyColors.primary,
)

案例6:颜色选择器

dart 复制代码
class ColorPicker extends StatefulWidget {
  @override
  _ColorPickerState createState() => _ColorPickerState();
}

class _ColorPickerState extends State<ColorPicker> {
  Color _selectedColor = Colors.blue;

  final List<Color> _colors = [
    Colors.red,
    Colors.pink,
    Colors.purple,
    Colors.blue,
    Colors.cyan,
    Colors.teal,
    Colors.green,
    Colors.lime,
    Colors.yellow,
    Colors.orange,
  ];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          width: 200,
          height: 200,
          decoration: BoxDecoration(
            color: _selectedColor,
            borderRadius: BorderRadius.circular(20),
            boxShadow: [
              BoxShadow(
                color: _selectedColor.withOpacity(0.5),
                blurRadius: 20,
                spreadRadius: 5,
              ),
            ],
          ),
        ),
        SizedBox(height: 20),
        Wrap(
          spacing: 10,
          runSpacing: 10,
          children: _colors.map((color) {
            return GestureDetector(
              onTap: () {
                setState(() {
                  _selectedColor = color;
                });
              },
              child: Container(
                width: 50,
                height: 50,
                decoration: BoxDecoration(
                  color: color,
                  shape: BoxShape.circle,
                  border: Border.all(
                    color: _selectedColor == color
                        ? Colors.black
                        : Colors.transparent,
                    width: 3,
                  ),
                ),
              ),
            );
          }).toList(),
        ),
      ],
    );
  }
}

案例7:颜色深浅选择

dart 复制代码
class ShadeSelector extends StatefulWidget {
  @override
  _ShadeSelectorState createState() => _ShadeSelectorState();
}

class _ShadeSelectorState extends State<ShadeSelector> {
  MaterialColor _color = Colors.blue;
  int _shade = 500;

  final List<int> _shades = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          width: double.infinity,
          height: 100,
          color: _color[_shade],
          child: Center(
            child: Text(
              '${_color.toString().split('.').last} $_shade',
              style: TextStyle(
                color: _shade > 500 ? Colors.white : Colors.black,
                fontSize: 20,
              ),
            ),
          ),
        ),
        SizedBox(height: 20),
        Wrap(
          spacing: 5,
          children: _shades.map((shade) {
            return GestureDetector(
              onTap: () {
                setState(() {
                  _shade = shade;
                });
              },
              child: Container(
                width: 60,
                height: 40,
                color: _color[shade],
                child: Center(
                  child: Text(
                    '$shade',
                    style: TextStyle(
                      color: shade > 500 ? Colors.white : Colors.black,
                      fontSize: 12,
                    ),
                  ),
                ),
              ),
            );
          }).toList(),
        ),
      ],
    );
  }
}

案例8:RGB 滑块

dart 复制代码
class RGBSlider extends StatefulWidget {
  @override
  _RGBSliderState createState() => _RGBSliderState();
}

class _RGBSliderState extends State<RGBSlider> {
  double _red = 255;
  double _green = 0;
  double _blue = 0;

  Color get _color => Color.fromRGBO(
        _red.toInt(),
        _green.toInt(),
        _blue.toInt(),
        1.0,
      );

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          width: 200,
          height: 200,
          decoration: BoxDecoration(
            color: _color,
            borderRadius: BorderRadius.circular(20),
          ),
          child: Center(
            child: Text(
              'RGB(${_red.toInt()}, ${_green.toInt()}, ${_blue.toInt()})',
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
        SizedBox(height: 20),
        _buildSlider('红色', _red, Colors.red, (value) {
          setState(() => _red = value);
        }),
        _buildSlider('绿色', _green, Colors.green, (value) {
          setState(() => _green = value);
        }),
        _buildSlider('蓝色', _blue, Colors.blue, (value) {
          setState(() => _blue = value);
        }),
      ],
    );
  }

  Widget _buildSlider(
    String label,
    double value,
    Color color,
    ValueChanged<double> onChanged,
  ) {
    return Row(
      children: [
        SizedBox(
          width: 60,
          child: Text(label),
        ),
        Expanded(
          child: Slider(
            value: value,
            min: 0,
            max: 255,
            activeColor: color,
            onChanged: onChanged,
          ),
        ),
        SizedBox(
          width: 40,
          child: Text('${value.toInt()}'),
        ),
      ],
    );
  }
}

案例9:颜色混合

dart 复制代码
class ColorBlender extends StatefulWidget {
  @override
  _ColorBlenderState createState() => _ColorBlenderState();
}

class _ColorBlenderState extends State<ColorBlender> {
  Color _color1 = Colors.red;
  Color _color2 = Colors.blue;
  double _blend = 0.5;

  Color get _blendedColor => Color.lerp(_color1, _color2, _blend)!;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          children: [
            Expanded(
              child: Container(
                height: 100,
                color: _color1,
                child: Center(
                  child: Text('颜色 1', style: TextStyle(color: Colors.white)),
                ),
              ),
            ),
            Expanded(
              child: Container(
                height: 100,
                color: _blendedColor,
                child: Center(
                  child: Text('混合', style: TextStyle(color: Colors.white)),
                ),
              ),
            ),
            Expanded(
              child: Container(
                height: 100,
                color: _color2,
                child: Center(
                  child: Text('颜色 2', style: TextStyle(color: Colors.white)),
                ),
              ),
            ),
          ],
        ),
        SizedBox(height: 20),
        Slider(
          value: _blend,
          min: 0,
          max: 1,
          divisions: 100,
          label: '${(_blend * 100).toInt()}%',
          onChanged: (value) {
            setState(() {
              _blend = value;
            });
          },
        ),
        Text('混合比例: ${(_blend * 100).toInt()}%'),
      ],
    );
  }
}

案例10:主题色切换

dart 复制代码
class ThemeColorDemo extends StatefulWidget {
  @override
  _ThemeColorDemoState createState() => _ThemeColorDemoState();
}

class _ThemeColorDemoState extends State<ThemeColorDemo> {
  MaterialColor _primaryColor = Colors.blue;

  final List<MaterialColor> _colors = [
    Colors.red,
    Colors.pink,
    Colors.purple,
    Colors.blue,
    Colors.cyan,
    Colors.teal,
    Colors.green,
    Colors.orange,
  ];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: _primaryColor,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('主题色切换'),
        ),
        body: Column(
          children: [
            Padding(
              padding: EdgeInsets.all(20),
              child: Text('选择主题色:'),
            ),
            Wrap(
              spacing: 10,
              runSpacing: 10,
              children: _colors.map((color) {
                return GestureDetector(
                  onTap: () {
                    setState(() {
                      _primaryColor = color;
                    });
                  },
                  child: Container(
                    width: 50,
                    height: 50,
                    decoration: BoxDecoration(
                      color: color,
                      shape: BoxShape.circle,
                      border: Border.all(
                        color: _primaryColor == color
                            ? Colors.black
                            : Colors.transparent,
                        width: 3,
                      ),
                    ),
                  ),
                );
              }).toList(),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {},
              child: Text('按钮'),
            ),
            SizedBox(height: 10),
            FloatingActionButton(
              onPressed: () {},
              child: Icon(Icons.add),
            ),
          ],
        ),
      ),
    );
  }
}

完整示例

dart 复制代码
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ColorDemo(),
    );
  }
}

class ColorDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Flutter 颜色示例')),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('预定义颜色', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            SizedBox(height: 10),
            Wrap(
              spacing: 10,
              runSpacing: 10,
              children: [
                _buildColorBox(Colors.red, 'Red'),
                _buildColorBox(Colors.blue, 'Blue'),
                _buildColorBox(Colors.green, 'Green'),
                _buildColorBox(Colors.yellow, 'Yellow'),
                _buildColorBox(Colors.orange, 'Orange'),
                _buildColorBox(Colors.purple, 'Purple'),
              ],
            ),
            SizedBox(height: 30),

            Text('颜色深浅', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            SizedBox(height: 10),
            Row(
              children: [
                _buildColorBox(Colors.blue[100]!, '100'),
                _buildColorBox(Colors.blue[300]!, '300'),
                _buildColorBox(Colors.blue[500]!, '500'),
                _buildColorBox(Colors.blue[700]!, '700'),
                _buildColorBox(Colors.blue[900]!, '900'),
              ],
            ),
            SizedBox(height: 30),

            Text('透明度', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            SizedBox(height: 10),
            Stack(
              children: [
                Container(
                  width: 200,
                  height: 100,
                  color: Colors.blue,
                ),
                Container(
                  width: 150,
                  height: 100,
                  color: Colors.red.withOpacity(0.5),
                ),
              ],
            ),
            SizedBox(height: 30),

            Text('渐变色', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            SizedBox(height: 10),
            Container(
              width: double.infinity,
              height: 100,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Colors.blue, Colors.purple],
                ),
                borderRadius: BorderRadius.circular(10),
              ),
            ),
            SizedBox(height: 30),

            Text('自定义颜色', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            SizedBox(height: 10),
            Row(
              children: [
                _buildColorBox(Color(0xFFFF5722), 'Custom 1'),
                _buildColorBox(Color(0xFF009688), 'Custom 2'),
                _buildColorBox(Color(0xFFE91E63), 'Custom 3'),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildColorBox(Color color, String label) {
    return Container(
      width: 60,
      height: 60,
      decoration: BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Center(
        child: Text(
          label,
          style: TextStyle(
            color: Colors.white,
            fontSize: 10,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }
}

常用颜色对照表

Material Design 颜色

颜色名 代码 十六进制
红色 Colors.red #F44336
粉色 Colors.pink #E91E63
紫色 Colors.purple #9C27B0
深紫色 Colors.deepPurple #673AB7
靛蓝 Colors.indigo #3F51B5
蓝色 Colors.blue #2196F3
浅蓝 Colors.lightBlue #03A9F4
青色 Colors.cyan #00BCD4
蓝绿 Colors.teal #009688
绿色 Colors.green #4CAF50
浅绿 Colors.lightGreen #8BC34A
黄绿 Colors.lime #CDDC39
黄色 Colors.yellow #FFEB3B
琥珀 Colors.amber #FFC107
橙色 Colors.orange #FF9800
深橙 Colors.deepOrange #FF5722
棕色 Colors.brown #795548
灰色 Colors.grey #9E9E9E
蓝灰 Colors.blueGrey #607D8B

透明度对照表

百分比 十六进制 十进制
100% FF 255
95% F2 242
90% E6 230
85% D9 217
80% CC 204
75% BF 191
70% B3 179
65% A6 166
60% 99 153
55% 8C 140
50% 80 128
45% 73 115
40% 66 102
35% 59 89
30% 4D 77
25% 40 64
20% 33 51
15% 26 38
10% 1A 26
5% 0D 13
0% 00 0

最佳实践

1. 使用主题色

dart 复制代码
// ✅ 好:使用主题色
Container(
  color: Theme.of(context).primaryColor,
)

// ❌ 不好:硬编码颜色
Container(
  color: Colors.blue,
)

2. 定义颜色常量

dart 复制代码
// ✅ 好:定义颜色常量
class AppColors {
  static const Color primary = Color(0xFF2196F3);
  static const Color secondary = Color(0xFFFF9800);
}

Container(
  color: AppColors.primary,
)

3. 考虑可访问性

dart 复制代码
// 确保文字和背景有足够的对比度
Container(
  color: Colors.blue,
  child: Text(
    '文本',
    style: TextStyle(color: Colors.white),  // 白色文字在蓝色背景上
  ),
)

4. 使用透明度

dart 复制代码
// ✅ 好:使用 withOpacity
Colors.red.withOpacity(0.5)

// ❌ 不好:手动计算透明度
Color(0x80FF0000)

总结

Flutter 颜色的核心要点:

  1. 多种颜色表示方式(预定义、ARGB、RGB、十六进制)
  2. 颜色深浅(50-900)
  3. 透明度控制(opacity、withOpacity)
  4. 主题色系统(ThemeData、ColorScheme)
  5. 颜色混合(Color.lerp)

记住:

  • Colors.xxx 是预定义颜色
  • Colors.xxx[500] 是默认深浅
  • withOpacity() 设置透明度
  • Color(0xFFRRGGBB) 是十六进制格式
  • 使用主题色而不是硬编码

掌握 Flutter 颜色系统,让你的应用更加美观!

相关推荐
奋斗的小青年!!2 小时前
Flutter跨平台开发鸿蒙应用实战:OA系统考勤打卡组件深度解析
flutter·harmonyos·鸿蒙
2501_916008893 小时前
iOS 上架需要哪些准备,账号、Bundle ID、证书、描述文件、安装测试及上传
android·ios·小程序·https·uni-app·iphone·webview
—Qeyser5 小时前
Flutter GestureDetector 完全指南:让任何组件都能响应手势
flutter·云原生·容器·kubernetes
豆豆菌5 小时前
Flutter运行时Running Gradle task ‘assembleDebug‘...很久无法启动
flutter
摘星编程5 小时前
React Native for OpenHarmony 实战:DatePickerAndroid 日期选择器详解
android·react native·react.js
鸣弦artha6 小时前
Flutter框架跨平台鸿蒙开发 —— Image Widget 基础:图片加载方式
flutter·华为·harmonyos
奋斗的小青年!!6 小时前
在OpenHarmony上玩转Flutter弹出菜单:我的实战经验分享
flutter·harmonyos·鸿蒙
花卷HJ7 小时前
Android 沉浸式全屏实践:主题 + 状态栏文字颜色完整方案
android
奋斗的小青年!!8 小时前
Flutter跨平台开发:笔记分享功能适配OpenHarmony
flutter·harmonyos·鸿蒙