如何为Flutter自定义CText组件配置Google Fonts fontFamily
为自定义CText组件配置Google Fonts字体
1. 先添加依赖
在项目的pubspec.yaml里加入google_fonts包:
dependencies: flutter: sdk: flutter google_fonts: ^6.1.0 # 可替换为最新版本号
2. 直接传递Google Fonts字体名
Google Fonts里的字体可以通过GoogleFonts.xxx().fontFamily直接拿到字体名,传给CText的fontFamily参数即可:
// 使用Roboto常规字体 CText(txt: "Hello World", fontFamily: GoogleFonts.roboto().fontFamily); // 使用Lato粗体 CText(txt: "Hello World", fontFamily: GoogleFonts.lato().fontFamily, weight: FontWeight.bold);
3. 优化:给CText加快捷调用方法(可选)
不想每次都写GoogleFonts.xxx()?可以给CText新增几个构造方法,快速调用常用字体:
class CText extends StatelessWidget { // 保留原基础构造方法 const CText( {super.key, this.size, required this.txt, this.color, this.fontFamily, this.weight}); // 新增Roboto快捷构造 const CText.roboto({ super.key, this.size, required this.txt, this.color, this.weight = FontWeight.normal, }) : fontFamily = GoogleFonts.roboto().fontFamily; // 新增Lato快捷构造 const CText.lato({ super.key, this.size, required this.txt, this.color, this.weight = FontWeight.normal, }) : fontFamily = GoogleFonts.lato().fontFamily; final String txt; final String? fontFamily; final double? size; final Color? color; final FontWeight? weight; @override Widget build(BuildContext context) { return Text(txt, style: TextStyle( fontSize: size, color: color, fontWeight: weight, fontFamily: fontFamily, )); } }
使用时直接调用快捷构造:
CText.roboto(txt: "用Roboto字体"); CText.lato(txt: "用Lato粗体", weight: FontWeight.bold);
4. 进阶:用枚举规范可选字体(可选)
怕拼写字体名出错?可以定义枚举来限制可选字体范围:
// 先定义字体枚举 enum AppFont { roboto, lato, openSans } class CText extends StatelessWidget { const CText({ super.key, this.size, required this.txt, this.color, this.font, // 用枚举代替字符串参数 this.weight, }) : fontFamily = _getFontFamily(font); final String txt; final AppFont? font; final String? fontFamily; final double? size; final Color? color; final FontWeight? weight; // 根据枚举返回对应字体名 static String? _getFontFamily(AppFont? font) { switch (font) { case AppFont.roboto: return GoogleFonts.roboto().fontFamily; case AppFont.lato: return GoogleFonts.lato().fontFamily; case AppFont.openSans: return GoogleFonts.openSans().fontFamily; default: return null; // 默认使用系统字体 } } @override Widget build(BuildContext context) { return Text(txt, style: TextStyle( fontSize: size, color: color, fontWeight: weight, fontFamily: fontFamily, )); } }
使用示例:
CText(txt: "用Open Sans字体", font: AppFont.openSans);
5. 离线加载字体(可选)
不想每次从网络拉取字体?可以把Google Fonts的字体文件下载到本地,放到assets/fonts目录,然后在pubspec.yaml中配置:
flutter: assets: - assets/fonts/ fonts: - family: Roboto fonts: - asset: assets/fonts/Roboto-Regular.ttf - asset: assets/fonts/Roboto-Bold.ttf weight: 700
之后直接传字体名即可使用离线字体:
CText(txt: "离线Roboto粗体", fontFamily: "Roboto", weight: FontWeight.bold);
内容的提问来源于stack exchange,提问作者user8
相关产品推荐
相关产品推荐

