Flutter中如何将Theme内的颜色设置为主题主色?
Flutter主题中动态引用主色设置文本颜色
当然可以,你可以通过定义ColorScheme来统一管理主题主色,然后在TextTheme中直接引用该主色,这样主色变更时文本颜色会自动同步。下面是两种可行的实现方式:
方法一:预定义ColorScheme并直接引用
先创建ColorScheme指定主色,再在TextTheme中引用它的primary属性,这是最直接的全局配置方式:
import 'package:flutter/material.dart'; void main() { // 定义颜色方案,这里的seedColor就是你的主色,修改它会同步所有引用的地方 final colorScheme = ColorScheme.fromSeed( seedColor: Colors.blue, brightness: Brightness.light, ); runApp(MaterialApp( theme: ThemeData( useMaterial3: true, colorScheme: colorScheme, // 直接引用colorScheme的primary作为titleLarge的颜色 textTheme: TextTheme( titleLarge: TextStyle(color: colorScheme.primary), ), ), home: const MyHomePage(), )); } class MyHomePage extends StatelessWidget { const MyHomePage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text('ok', style: Theme.of(context).textTheme.titleLarge), ), ); } }
方法二:继承默认样式并修改颜色
如果想保留titleLarge的默认字体大小、权重等样式,只修改颜色,可以用copyWith方法:
textTheme: TextTheme( titleLarge: ThemeData.light().textTheme.titleLarge?.copyWith( color: colorScheme.primary, ), ),
这样只要你修改colorScheme中的seedColor,所有引用colorScheme.primary的元素颜色都会自动更新,无需逐个修改硬编码值。
内容的提问来源于stack exchange,提问作者Andrey
相关产品推荐
相关产品推荐

