Flutter中AppBarTheme的textTheme弃用问题及替代方案求助
Flutter AppBarTheme textTheme 属性弃用替代方案
问题场景
在Flutter项目中定义主题时,AppBarTheme的textTheme属性被标记为弃用,编译器提示需使用toolbarTextStyle和titleTextStyle替代。相关代码及报错信息如下:
原代码
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; class MyTheme { static ThemeData lightTheme(BuildContext context) => ThemeData( primarySwatch: Colors.deepPurple, fontFamily: GoogleFonts.lato().fontFamily, appBarTheme: const AppBarTheme( color: Colors.white, elevation: 0.0, iconTheme: IconThemeData(color: Colors.black), // textTheme is deprecated textTheme: Theme.of(context).textTheme, ) ); static ThemeData darkTheme(BuildContext context) => ThemeData( brightness: Brightness.dark, ); }
错误信息
'textTheme' is deprecated and shouldn't be used. This property is no longer used, please use toolbarTextStyle and titleTextStyle instead. "textTheme: Theme.of(context).textTheme,"
无效尝试
// titleTextStyle: TextStyle((context).textTheme),
正确解决方案
Flutter将原textTheme拆分为两个独立属性,分别对应AppBar上不同文本的样式:
toolbarTextStyle:控制AppBar工具栏区域的文本样式(如返回按钮旁的辅助文字)titleTextStyle:控制AppBar的主标题文本样式
同时注意:原代码中AppBarTheme使用了const修饰,但Theme.of(context)是非常量表达式,因此必须去掉const关键字,否则会触发编译错误。
修改后的完整代码如下:
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; class MyTheme { static ThemeData lightTheme(BuildContext context) => ThemeData( primarySwatch: Colors.deepPurple, fontFamily: GoogleFonts.lato().fontFamily, appBarTheme: AppBarTheme( color: Colors.white, elevation: 0.0, iconTheme: const IconThemeData(color: Colors.black), // 替换弃用的textTheme toolbarTextStyle: Theme.of(context).textTheme.bodyMedium, titleTextStyle: Theme.of(context).textTheme.headlineSmall, ) ); static ThemeData darkTheme(BuildContext context) => ThemeData( brightness: Brightness.dark, ); }
补充说明
如果需要自定义文本样式,可以通过copyWith方法修改属性,例如:
titleTextStyle: Theme.of(context).textTheme.headlineSmall?.copyWith( color: Colors.deepPurple, fontWeight: FontWeight.bold, ),
内容的提问来源于stack exchange,提问作者Debug
相关产品推荐
相关产品推荐

