在 Flutter 中,自定义图标主要有以下几种方法,适用于不同场景:
1. 使用 Icon 组件和自定义字体图标(推荐)
这是最常用的方法,通过将图标打包为字体文件(如 .ttf)并在 pubspec.yaml 中配置。
步骤:
- 准备图标文件:从网站如 FlutterIcon 或 IcoMoon 上传 SVG 图标,生成字体文件(如 
my_icons.ttf)和对应的映射文件(如 my_icons.dart)。 
- 配置 
pubspec.yaml:flutter:
  fonts:
    - family: MyIcons
      fonts:
        - asset: assets/fonts/my_icons.ttf
 
- 使用生成的映射文件:
import 'my_icons.dart';
Icon(MyIcons.custom_icon, size: 30, color: Colors.blue),
 
2. 使用 SvgPicture 组件(矢量图标)
适用于 SVG 格式的图标,保持清晰度且文件较小。
步骤:
- 添加依赖:
dependencies:
  flutter_svg: ^2.0.9
 
- 将 SVG 文件放入项目(如 
assets/icons/icon.svg),并在 pubspec.yaml 中声明:flutter:
  assets:
    - assets/icons/
 
- 在代码中使用:
import 'package:flutter_svg/flutter_svg.dart';
SvgPicture.asset(
  'assets/icons/icon.svg',
  width: 30,
  height: 30,
),
 
3. 使用 Image 组件(位图图标)
适用于 PNG、JPG 等格式,适合复杂图标。
步骤:
- 将图片文件(如 
icon.png)放入 assets/images/,并在 pubspec.yaml 中声明资源。 
- 在代码中使用:
Image.asset(
  'assets/images/icon.png',
  width: 30,
  height: 30,
),
 
4. 自定义 CustomPaint 绘制图标
适用于简单动态图标,但代码较复杂。
示例代码:
CustomPaint(
  size: Size(30, 30),
  painter: _CustomIconPainter(),
),
class _CustomIconPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()..color = Colors.red;
    canvas.drawCircle(Offset(size.width / 2, size.height / 2), 10, paint);
  }
  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
选择建议:
- 字体图标:适合多个图标、需要统一风格和颜色控制。
 
- SVG:适合单色或简单彩色矢量图标,缩放无损。
 
- 位图:适合复杂图案,但放大可能失真。
 
- CustomPaint:适合动态或简单图形,但开发成本高。
 
根据需求选择合适的方法,通常字体图标和 SVG 是最常用的方案。