Flutter 入门与实战:设置 App 的主色调与字体
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// 设置应用的主题样式
final ThemeData theme = ThemeData(
primarySwatch: Colors.blue, // 设置主色调为蓝色
visualDensity: VisualDensity.adaptivePlatformDensity,
);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: theme, // 应用主题
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
style: Theme.of(context).textTheme.headline6, // 使用主题中的字体样式
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4, // 使用主题中的字体样式
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
这段代码继续上一节的内容,展示了如何在Flutter应用中设置主色调和使用主题中定义的字体样式。通过ThemeData
我们定义了主色调和字体样式,并在Text
组件中使用Theme.of(context)
来应用这些样式。这是学习如何在Flutter应用中统一设计样式的一个很好的例子。
评论已关闭