1// 文本、字体样式 2 3 4import 'package:flutter/material.dart'; 5 6 7class TextFontStyle extends StatelessWidget { 8 // 声明文本样式 9 TextStyle textStyle = const TextStyle(fontFamily: 'MyFont', fontSize: 30, ); 10 11 @override 12 Widget build(BuildContext context) { 13 return Scaffold( 14 appBar: AppBar( 15 title: Text('Text Font Style'), 16 ), 17 body: Container( 18 child: Column( 19 children: <Widget>[ 20 21 // textAlign:文本的对齐方式;可以选择左对齐、右对齐还是居中。 22 // 注意,对齐的参考系是Text widget本身。 23 Text('Hello world!', 24 textAlign: TextAlign.left, 25 ), 26 27 // maxLines、overflow:指定文本显示的最大行数,默认情况下,文本是自动折行的,如果指定此参数,则文本最多不会超过指定的行。 28 // 如果有多余的文本,可以通过overflow来指定截断方式,默认是直接截断。 29 // 本例中指定的截断方式TextOverflow.ellipsis,它会将多余文本截断后以省略符“...”表示; 30 Text('Hello World! hhhhh'*5, 31 maxLines: 1, 32 overflow: TextOverflow.ellipsis, 33 ), 34 35 // textScaleFactor:代表文本相对于当前字体大小的缩放因子,相对于去设置文本的样式style属性的fontSize,它是调整字体大小的一个快捷方式。 36 Text('Hello world!', 37 textScaleFactor: 1.5, 38 ), 39 40 // TextStyle用于指定文本显示的样式如颜色、字体、粗细、背景等。 41 Text('Hello world!', 42 style: TextStyle( 43 color: Colors.blue, 44 // fontSize:该属性和Text的textScaleFactor都用于控制字体大小。但是有两个主要区别: 45 // * fontSize可以精确指定字体大小,而textScaleFactor只能通过缩放比例来控制。 46 // * textScaleFactor主要是用于系统字体大小设置改变时对Flutter应用字体进行全局调整,而fontSize通常用于单个文本,字体大小不会跟随系统字体大小变化。 47 fontSize: 18.0, 48 // height:该属性用于指定行高,但它并不是一个绝对值,而是一个因子,具体的行高等于fontSize*height。 49 height: 1.2, 50 fontFamily: 'Courier', 51 background: Paint()..color = Colors.yellow, 52 decoration: TextDecoration.underline, 53 decorationStyle: TextDecorationStyle.dashed, 54 ) 55 ), 56 57 // 需要对一个Text内容的不同部分按照不同的样式显示,这时就可以使用TextSpan,它代表文本的一个“片段”。 58 Text.rich(TextSpan( 59 children: [ 60 TextSpan( 61 text: 'Home:', 62 ), 63 TextSpan( 64 text: 'www.baidu.com', 65 style: TextStyle( 66 color: Colors.blue, 67 fontSize: 20, 68 ), 69 // 点击链接后的一个处理器,手势识别的内容 70// recognizer: _tap 71 ), 72 ] 73 )), 74 75 // 在Widget树中,文本的样式默认是可以被继承的(子类文本类组件未指定具体样式时可以使用Widget树中父级设置的默认样式), 76 // 因此,如果在Widget树的某一个节点处设置一个默认的文本样式,那么该节点的子树中所有文本都会默认使用这个样式, 77 // 而DefaultTextStyle正是用于设置默认文本样式的。 78 DefaultTextStyle( 79 // 设置文本默认样式 80 style: TextStyle( 81 color: Colors.red, 82 fontSize: 20.0, 83 ), 84 textAlign: TextAlign.start, 85 child: Column( 86 crossAxisAlignment: CrossAxisAlignment.start, 87 children: <Widget>[ 88 // 继承默认样式 89 Text('Hello world'), 90 Text('I am Hhh'), 91 // 不继承默认样式 92 Text('I am Hhh', 93 style: TextStyle( 94 inherit: false, 95 color: Colors.grey, 96 ), 97 ), 98 ], 99 ), 100 ), 101 102 // 在Flutter中使用字体分两步完成。 103 // 1. 在pubspec.yaml中声明它们,以确保它们会打包到应用程序中。 104 // 2. 通过TextStyle属性使用字体。 105 // 使用本地字体 106 Text('你好吗hello', 107 style: textStyle, 108 ), 109 Text('你好吗hello', 110 style: TextStyle( 111 fontSize: 30, 112 ), 113 ), 114 115 ], 116 ), 117 ), 118 ); 119 } 120 121}
Flutter 基础组件:文本、字体样式
Stella981
2021-10-11
1249 0 0
点赞
收藏
评论区
加载中...