字体大小有两种定义方式
1) 像 Flutter 新手一样内联设置随机字体大小
Text('item ${++index}', style: TextStyle(
color: Colors.green,
fontSize: 32)
2) 使用来自 Apps Material Theme 的预定义字体大小
这是一个更好的方法。这样你就可以在一个地方定义字体大小,它会自动应用到你的整个应用程序中。
Text('item ${++index}', style: TextStyle(
color: Colors.green,
fontSize: Theme
.of(context)
.textTheme
.headline1?.fontSize?? 32
)
定义全局主题类:
import 'package:flutter/material.dart';
// Global Theme For App
class AppTheme {
ThemeData buildThemeData() {
return ThemeData(
// Global Color Style
primarySwatch: Colors.blueGrey,
primaryColor: Colors.blueGrey[800],
accentColor: Colors.tealAccent,
// Global Text Style
textTheme: TextTheme(
headline1: TextStyle(
fontSize: 72.0,
fontWeight: FontWeight.bold,
fontFamily: 'Cutive',
),
headline6: TextStyle(fontSize: 36.0),
bodyText2: TextStyle(fontSize: 14.0),
));
}
}
现在在 App 的入口点应用它:
import 'package:flutter/material.dart';
import 'theme.dart';
import './widgets/home.dart';
void main() {
runApp(MainApp());
}
// This widget is the root of your application.
class MainApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: AppTheme().buildThemeData(),
home: MyStatelessWidget(),
);
}
}
我使用的第三种方法是定义我将无论如何都用于标题、标签等的组件并重用它们
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
class Header extends StatelessWidget {
Header({
required this.title,
});
final String title;
@override
Widget build(BuildContext context) {
return Text(
title,
style: TextStyle(
fontSize: 32,
foreground: Paint()
..shader = ui.Gradient.linear(
const Offset(0, 10),
const Offset(40, 20),
<Color>[
Colors.red,
Colors.blue,
],
)),
);
}
}
这种方式在所有小部件中设置标题减少到 1 行:
Header(title: "Hello World"),