在Flutter中自定义组件其实就是一个类,这个类需要继承StatelessWidget/StatefulWidget 。
StatelessWidget 是无状态组件,状态不可变的widget
StatefulWidget 是有状态组件,持有的状态可能在 widget生命周期改变
前期我们都继承StatelessWidget。
StatelessWidget是一个抽象类,里面有一个抽象方法build 返回Widget组件
import 'package:flutter/material.dart';
// void main() => runApp(new MyApp() ; new hougong());
void main() {
return runApp (new MyApp() ) ;
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: '欢迎来到雍正年间',
home: new Scaffold(
appBar: new AppBar(
title: new Text('四大爷'),
),
body: new Center(
child: new Text('最近宫里冷冷清清 是时候招一批秀女了'),
),
),
);
}
}
Text组件(简单样式文本框组件)用于显示简单的样式文本,它的常用属性如下表所示。
const Text(
String this.data, {//显示的文本
Key? key,
this.style,//文本的样式,包括字体、颜色、大小
this.strutStyle,
this.textAlign,//对齐方式,左对齐、右对齐
this.textDirection,//文本方向,从左到右、从右到左
this.locale,
this.softWrap,//是否自动换行
this.overflow,//文本的截取方式
this.textScaleFactor,
this.maxLines,//显示的最大行数
this.semanticsLabel,
this.textWidthBasis,
this.textHeightBehavior,
}) : assert(
data != null,
'A non-null String must be provided to a Text widget.',
),
textSpan = null,
super(key: key);
Text组件中的style属性表示文本的样式,类型为TextStyle
class TextStyle with Diagnosticable {
/// Creates a text style.
///
/// The `package` argument must be non-null if the font family is defined in a
/// package. It is combined with the `fontFamily` argument to set the
/// [fontFamily] property.
const TextStyle({
this.inherit = true,
this.color,//字体颜色
this.backgroundColor,
this.fontSize,//字体大小
this.fontWeight,//字体加粗。FontWeight normal(默认)、FontWeight bold (加粗)
this.fontStyle,
this.letterSpacing,
this.wordSpacing,
this.textBaseline,
this.height,
this.leadingDistribution,
this.locale,
this.foreground,
this.background,
this.shadows,
this.fontFeatures,
this.decoration,
this.decorationColor,
this.decorationStyle,
this.decorationThickness,
this.debugLabel,
修改字体的颜色、大小
import 'package:flutter/material.dart';
// void main() => runApp(new MyApp() ; new hougong());
void main() {
return runApp (new MyApp() ) ;
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: '甄嬛传',
home: new Scaffold(
appBar: new AppBar(
title: new Text(
'四大爷',
style:TextStyle(
fontSize:40.0,
color:Colors.red,
// color:Color.fromRGBO(12, 215, 111, 0) //自定义颜色,输入rgb的值和透明度
),
),
),
body: new Center(
child: new Text('最近宫里冷冷清清 是时候招一批秀女了'),
),
),
);
}
}