Flutter中如何升级ThemeData的accentColor并修复相关错误?
原始代码
主题配置代码
theme: ThemeData( primarySwatch: Colors.purple, accentColor: Colors.deepOrange, fontFamily: 'Lato', pageTransitionsTheme: PageTransitionsTheme( builders: { TargetPlatform.android: CustomPageTransitionBuilder(), TargetPlatform.iOS: CustomPageTransitionBuilder(), }, ), ),
报错代码及提示
第一行报错代码:
TextStyle( color: Theme.of(context).accentTextTheme.title.color,),
错误提示:
The getter 'title' isn't defined for the type 'TextTheme'. Try importing the library that defines 'title', correcting the name to the name of an existing getter, or defining a getter or field named 'title'.
第二行报错代码:
TextStyle( color: Theme.of(context).primaryTextTheme.title.color,),
错误提示:
The getter 'title' isn't defined for the type 'TextTheme'. Try importing the library that defines 'title', correcting the name to the name of an existing getter, or defining a getter or field named 'title'.
已知accentColor已废弃,需同步升级代码解决上述错误。
修复方案
1. 替换废弃的accentColor
Flutter新版本中accentColor已被废弃,改用ColorScheme中的secondary颜色配置。修改后的主题代码如下:
theme: ThemeData( primarySwatch: Colors.purple, fontFamily: 'Lato', // 用ColorScheme替代accentColor colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.purple) .copyWith(secondary: Colors.deepOrange), pageTransitionsTheme: PageTransitionsTheme( builders: { TargetPlatform.android: CustomPageTransitionBuilder(), TargetPlatform.iOS: CustomPageTransitionBuilder(), }, ), ),
2. 修复TextTheme.title不存在的错误
Flutter的TextTheme结构已更新,原title属性被更语义化的命名替代,同时accentTextTheme/primaryTextTheme的使用方式也可简化,以下是两种报错代码的修复方式:
修复第一行代码(原accentTextTheme.title)
若需保留原title的文本样式(字体大小、权重等),同时使用原accentColor对应的secondary颜色:
TextStyle( color: Theme.of(context).colorScheme.secondary, fontSize: Theme.of(context).textTheme.titleMedium?.fontSize, fontWeight: Theme.of(context).textTheme.titleMedium?.fontWeight, ),
仅需颜色可简化为:
TextStyle(color: Theme.of(context).colorScheme.secondary),
修复第二行代码(原primaryTextTheme.title)
同理,保留原样式+使用主色:
TextStyle( color: Theme.of(context).colorScheme.primary, fontSize: Theme.of(context).textTheme.titleMedium?.fontSize, fontWeight: Theme.of(context).textTheme.titleMedium?.fontWeight, ),
仅需主色可简化为:
TextStyle(color: Theme.of(context).colorScheme.primary),
补充:TextTheme新命名对应关系
新版本Flutter使用更清晰的语义化命名替代旧属性,常见对应关系:
- 旧
title→ 新titleMedium(或过渡版本的headline6) - 旧
headline→ 新headlineLarge - 旧
subhead→ 新titleSmall - 旧
body1→ 新bodyLarge - 旧
body2→ 新bodyMedium
建议优先使用新命名,提升代码可读性。
内容的提问来源于stack exchange,提问作者best_of_man

