flutter中的控件可以成为小部件,继承自StatefulWidget或者StatelessWidget,每个小部件又可以嵌套小部件。本篇文章创建一个不修改数据的小部件。代码如下:
import 'package:flutter/material.dart';
void main()=>runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Text(
'hello world',
textDirection: TextDirection.ltr,
),
);
}
}
创建了一个Center的小部件,里面嵌套了一个Text的小部件。
效果如下:
修改Text的style属性代码如下
import 'package:flutter/material.dart';
void main()=>runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Text(
'hello world',
textDirection: TextDirection.ltr,
style: TextStyle(
fontSize: 40,
fontWeight: FontWeight.bold,
color: Colors.yellow
),
),
);
}
}
效果如下:
进一步修改生成一个materialApp小部件
import 'package:flutter/material.dart';
void main()=>runApp(App());
class App extends StatelessWidget{
@override
Widget build(BuildContext context){
return MaterialApp(
home: Hello(),
);
}
}
class Hello extends StatelessWidget{
@override
Widget build(BuildContext context){
return Center(
child: Text(
'helloworld',
textDirection: TextDirection.ltr,
style: TextStyle(
fontSize: 40.0,
fontWeight: FontWeight.bold,
color: Colors.yellow
),
),
);
}
}
Text部件的属性:
源码:
const Text(this.data, {
Key key,
this.style,
this.textAlign,
this.textDirection,
this.locale,
this.softWrap,
this.overflow,
this.textScaleFactor,
this.maxLines,
this.semanticsLabel,
}) : assert(data != null),
textSpan = null,
super(key: key);
/// Creates a text widget with a [TextSpan].
const Text.rich(this.textSpan, {
Key key,
this.style,
this.textAlign,
this.textDirection,
this.locale,
this.softWrap,
this.overflow,
this.textScaleFactor,
this.maxLines,
this.semanticsLabel,
}): assert(textSpan != null),
data = null,
super(key: key);
效果如下
使用scaffold组件并设置主题:
import 'package:flutter/material.dart';
void main()=>runApp(App());
class App extends StatelessWidget{
@override
Widget build(BuildContext context){
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('hello'),// 设置导航条标题
elevation: 0,// 设置导航条底部的阴影,默认4.0
),
body: Hello(),
),
theme: ThemeData(// 设置主题色,注意在设置primarySwatch不能设置Colors.white,因为纯的黑和纯白不为MaterialColor,需要设置primaryColor
primarySwatch: Colors.yellow,
// primaryColor: Colors.white
),
);
}
}
class Hello extends StatelessWidget{
@override
Widget build(BuildContext context){
return Center(
child: Text(
'helloworld',
textDirection: TextDirection.ltr,
style: TextStyle(
fontSize: 40.0,
fontWeight: FontWeight.bold,
color: Colors.black54
),
),
);
}
}
效果如下:
参考下面这篇文章写得,这兄弟总结的非常好。
参考地址:https://segmentfault.com/a/1190000020623685?utm_source=tag-newest