Flutter控件之Text Widgets

负责显示文本和定义显示样式的控件。

  • Text

    显示单一样式的文本

    new Text(
     'Hello, $_name! How are you?',
     textAlign: TextAlign.center,
     overflow: TextOverflow.ellipsis,
     style: new TextStyle(fontWeight: FontWeight.bold),
    )

    如果想让文本控件响应Touch事件,要把该控件放在GestureDetector控件里使用,如果是material design应用,可以考虑直接使用FlatButton实现可Touch的文本。

  • RichText

    显示丰富样式的文本

    new RichText(
     text: new TextSpan(
       text: 'Hello ',
       style: DefaultTextStyle.of(context).style,
       children: <TextSpan>[
         new TextSpan(text: 'bold', style: new TextStyle(fontWeight: FontWeight.bold)),
         new TextSpan(text: ' world!'),
       ],
     ),
    )
  • DefaultTextStyle

    默认文本样式

    Widget build(BuildContext context) {
       return new Container(
         color: Colors.white,
         child: new Directionality(
           textDirection: TextDirection.ltr,
           child: new DefaultTextStyle(
             style: new TextStyle(
               fontSize: 14.0,
               color: Colors.blue,
               decoration: TextDecoration.underline
             ),
             maxLines: 2,
             softWrap: true,
             overflow: TextOverflow.ellipsis,
             child: new Text('+++++++++++++++++++++++++++++++++++我是一段超长的文本++++++++++++++++++++++++++++++++++++++++++++')
           )
         )
       );
     }
  • Directionality

    主要控制文字方向

    Widget build(BuildContext context) {
       return new Container(
         color: Colors.white,
         child: new Directionality(
           textDirection: TextDirection.rtl,
           child: new Text('我是一段文本')
         )
       );
     }

Text控件本身有style、textDirection等属性,之所以独立出DefaultTextStyle控件专门管理样式、Directionality控件专门管理文字方向,是为了方便统一某个模块的样式,继承父控件属性,不需要每个元素都要去设置一遍。

DefaultTextStyle和Directionality是InheritedWidget的子类,InheritedWidget实现了一个发布/订阅的模式,当子控件调用inheritFromWidgetOfExactType方法获取父控件时,同时也把自己加入到InheritedWidget的订阅者列表里面,所以当InheritedWidget属性改变的时候,就会调起子组件didChangeDependencies方法去通知子组件。

猜你喜欢

转载自blog.csdn.net/johnwcheung/article/details/79006562