Post

三基础组件-3文本及样

介绍文本及样式

1.Text

属性作用其他
textAlign文本对齐方式如TextAlign.left
textScaleFactor对于当前字体大小的缩放因子相对于style属性的fontSize。该属性的默认值可以通过MediaQueryData.textScaleFactor获得,如果没有MediaQuery,那么会默认值将为1.0。
style用于指定文本显示的样式如颜色、字体、粗细、背景等见下表TextStyle

TextStyle

属性作用其他
color字体颜色 
fontFamily字体 
fontSize字体大小 
background背景色 
decoration装饰器如extDecoration.underline
decorationStyle装饰器style如TextDecorationStyle.dashed

2.TextSpan

1
2
3
4
5
6
const TextSpan({
  TextStyle style, //见上TextStyle
  Sting text,
  List<TextSpan> children,
  GestureRecognizer recognizer,//用于对该文本片段上用于手势进行识别处理
});

example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Text.rich(TextSpan(//Text其实就是RichText的一个包装,而RichText是可以显示多种样式(富文本)的widget。
    children: [
     TextSpan(
       text: "Home: "
     ),
     TextSpan(
       text: "https://flutterchina.club",
       style: TextStyle(
         color: Colors.blue
       ),  
       recognizer: _tapRecognizer
     ),
    ]
))

3.DefaultTextStyle(在Widget树中,文本的样式默认是可以被继承的)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
DefaultTextStyle(
  //1.设置文本默认样式  
  style: TextStyle(
    color:Colors.red,
    fontSize: 20.0,
  ),
  textAlign: TextAlign.start,
  child: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: <Widget>[
      Text("hello world"), //继承红色、20号字体
      Text("I am Jack"),   //继承红色、20号字体
      Text("I am Jack",    //不继承
        style: TextStyle(
          inherit: false, //2.不继承默认样式
          color: Colors.grey
        ),
      ),
    ],
  ),
);

4.字体

使用字体分两步

1.在asset中声明。先在pubspec.yaml中声明,然后将字体文件复制到在pubspec.yaml中指定的位置。

1
2
3
4
5
6
7
flutter:
  fonts:
    - family: Raleway
      fonts:
        - asset: assets/fonts/Raleway-Regular.ttf
        - asset: assets/fonts/Raleway-Medium.ttf
          weight: 500

2.通过TextStyle属性使用字体

1
2
3
4
5
6
7
8
9
10
// 声明文本样式
const textStyle = const TextStyle(
  fontFamily: 'Raleway',
);

// 使用文本样式
var buttonText = const Text(
  "Use the font for this text",
  style: textStyle,
);

使用Package中的字体

1
2
3
4
const textStyle = const TextStyle(
  fontFamily: 'Raleway',
    package: 'my_package', //指定包名
  );
This post is licensed under CC BY 4.0 by the author.