
到目前为止,你已经掌握了:
但是一个 App 不仅要功能完整,还要美观一致。 Flutter 提供了 Theme / ThemeData 来统一管理样式。
在 MaterialApp 中配置:
MaterialApp(
title: 'Flutter 美化示例',
theme: ThemeData(
primarySwatch: Colors.blue,
brightness: Brightness.light,
accentColor: Colors.orange,
textTheme: TextTheme(
bodyText1: TextStyle(fontSize: 16, color: Colors.black),
bodyText2: TextStyle(fontSize: 14, color: Colors.grey[700]),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
primary: Colors.blue,
onPrimary: Colors.white,
textStyle: TextStyle(fontSize: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
),
),
home: HomePage(),
);
📌 说明:
primarySwatch → App 主色brightness → 明暗主题accentColor → 点缀颜色(部分组件使用)textTheme → 全局文字样式elevatedButtonTheme → 按钮统一样式Theme(
data: Theme.of(context).copyWith(
primaryColor: Colors.red,
),
child: AppBar(title: Text('局部主题')),
)
📌 ThemeData 可以在局部覆盖 → 灵活定制部分页面样式
AppBar(
title: Text('自定义 AppBar'),
backgroundColor: Colors.deepPurple,
centerTitle: true,
elevation: 4,
)
ElevatedButton(
onPressed: () {},
child: Text('提交'),
style: ElevatedButton.styleFrom(
primary: Colors.green,
onPrimary: Colors.white,
textStyle: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
)
TextField(
decoration: InputDecoration(
labelText: '用户名',
labelStyle: TextStyle(color: Colors.grey[600]),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blue, width: 2),
),
),
)
创建一个 colors.dart 文件:
import 'package:flutter/material.dart';
class AppColors {
static const primary = Color(0xFF2196F3);
static const accent = Color(0xFFFF9800);
static const background = Color(0xFFF5F5F5);
static const textPrimary = Color(0xFF212121);
static const textSecondary = Color(0xFF757575);
}
然后在 ThemeData 和组件中使用:
theme: ThemeData(
primaryColor: AppColors.primary,
accentColor: AppColors.accent,
)
📌 好处:
在 pubspec.yaml 添加自定义字体:
fonts:
- family: Roboto
fonts:
- asset: fonts/Roboto-Regular.ttf
- asset: fonts/Roboto-Bold.ttf
weight: 700
然后在 ThemeData 使用:
theme: ThemeData(
fontFamily: 'Roboto',
)
📌 全局文字风格统一 → App 更专业
ElevatedButtonThemeData 统一按钮样式Card + RoundedRectangleBorder + elevation 提升卡片质感Card(
elevation: 4,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
child: Padding(
padding: EdgeInsets.all(16),
child: Text('卡片内容'),
),
)
❌ 忘记在 MaterialApp 配置 theme → 主题无效 ❌ 多处直接写颜色 / 字体 → 维护困难 ❌ 局部 ThemeData 与全局冲突 → 样式混乱
📌 建议:
你已经学会:
📌 到这里为止:
你的 Flutter App 已经可以看起来像“专业作品”了 ✅
ThemeData + 统一颜色字体 + 组件样式 App 美化统一且易维护
《Flutter 零基础入门(四十二):Flutter 路由与导航进阶 —— 命名路由与参数传递实战》
下一篇我们将学习:
🚀 让你的 App 页面跳转更高效、可维护