Flutter 入门笔记(Part 2) 基本控件

5 . 文本

  • Text,单一样式. 构造参数分为2类
  • 控制整体文本布局的参数: 对齐方式textAlign,文本排版方向textDirection,文本显示最大行数 maxLines、文本截断规则 overflow 等
  • 控制文本展示样式的参数: 统一封装到style参数中,字体名称fontFamily,字体大小fontSize,文本颜色color,文本阴影shadows等
Text(
  '文本是视图系统中的常见控件,用来显示一段特定样式的字符串,就比如Android里的TextView,或是iOS中的UILabel。',
  textAlign: TextAlign.center,//居中显示
  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20, color: Colors.red),//20号红色粗体展示
);
  • TextSpan,可展示混合样式.(类似SpannableString)

TextStyle blackStyle = TextStyle(fontWeight: FontWeight.normal, fontSize: 20, color: Colors.black); //黑色样式

TextStyle redStyle = TextStyle(fontWeight: FontWeight.bold, fontSize: 20, color: Colors.red); //红色样式

Text.rich(
    TextSpan(
        children: <TextSpan>[
          TextSpan(text:'文本是视图系统中常见的控件,它用来显示一段特定样式的字符串,类似', style: redStyle), //第1个片段,红色样式 
          TextSpan(text:'Android', style: blackStyle), //第1个片段,黑色样式 
          TextSpan(text:'中的', style:redStyle), //第1个片段,红色样式 
          TextSpan(text:'TextView', style: blackStyle) //第1个片段,黑色样式 
        ]),
  textAlign: TextAlign.center,
);

6 . 图片

  • Image

  • 加载本地资源图片,如 Image.asset(‘images/logo.png’);

  • 加载本地(File 文件)图片,如 Image.file(new File(’/storage/xxx/xxx/test.jpg’));

  • 加载网络图片,如 Image.network('http://xxx/xxx/test.gif')

  • 填充模式fit,拉伸 centerSlice,重复模式repeat

  • Image通过内部ImageProvider根据缓存状态,触发异步加载流程,通知_imageState(Image这种控件肯定不是静态的撒,得需要一个State)刷新UI.

  • FadeInImage,可以提供占位图,加载动画等.

FadeInImage.assetNetwork(
  placeholder: 'assets/loading.gif', //gif占位
  image: 'https://xxx/xxx/xxx.jpg',
  fit: BoxFit.cover, //图片拉伸模式
  width: 200,
  height: 200,
)
  • 图片默认缓存到内存,LRU(最近最少使用),如需缓存到本地则需要使用第三方的CachedNetworkImage(还提供了错误展示图片)控件

    7 . 按钮

  • FloatingActionButton 圆形按钮

  • RaisedButton,凸起的按钮,和Android默认的Button长得一样丑

  • FlatButton,扁平的按钮,默认透明背景,被点击后呈现灰色背景

FloatingActionButton(onPressed: () => print('FloatingActionButton pressed'),child: Text('Btn'),);
FlatButton(onPressed: () => print('FlatButton pressed'),child: Text('Btn'),);
RaisedButton(onPressed: () => print('RaisedButton pressed'),child: Text('Btn'),);
  • onPressed参数用于设置回调,如果参数为空,则按钮会被禁用
  • child参数用于控制控件长什么样子
  • 其他丰富api
FlatButton(
    color: Colors.yellow, //设置背景色为黄色
    shape:BeveledRectangleBorder(borderRadius: BorderRadius.circular(20.0)), //设置斜角矩形边框
    colorBrightness: Brightness.light, //确保文字按钮为深色
    onPressed: () => print('FlatButton pressed'), 
    child: Row(children: <Widget>[Icon(Icons.add), Text("Add")],)
);
  • Button都是由RawMaterialButton承载视觉,Image都是RawImage,Text是RichText。它们都继承自RenderObjectWidget,而RenderObjectWidget的父类就是Widget。

    8 . ListView

8.1 ListView

  • 同时支持垂直方向和水平方向滚动
  • 创建子视图方式
构造函数名 特点 适用场景 适用频次
ListView 一次性创建好全部子Widget 适用于展示少量连续子Widget的场景
ListView.builder 提供子Widget创建方法,仅在需要展示的时候才创建 适用于子Widget较多,且视觉效果呈现某种规律性的场景
ListView.separated 与ListView.builder类似,并提供了自定义分割线的功能 与ListView.builder场景类似
  • 第一种 ListView 直接构建
ListView(
  children: <Widget>[
    //设置ListTile组件的标题与图标 
    ListTile(leading: Icon(Icons.map),  title: Text('Map')),
    ListTile(leading: Icon(Icons.mail), title: Text('Mail')),
    ListTile(leading: Icon(Icons.message), title: Text('Message')),
  ]);
  • 第二种 ListView.builder.「itemExtent 并不是一个必填参数。但,对于定高的列表项元素,我强烈建议你提前设置好这个参数的值。」
ListView.builder(
    //itemCount,表示列表项的数量,如果为空,则表示 ListView 为无限列表
    itemCount: 100, //元素个数
    itemExtent: 50.0, //列表项高度
    itemBuilder: (BuildContext context, int index) => ListTile(title: Text("title $index"), subtitle: Text("body $index"))
);
  • 第三种 ListView.separated
//使用ListView.separated设置分割线
ListView.separated(
    itemCount: 100,
    separatorBuilder: (BuildContext context, int index) => index %2 ==0? Divider(color: Colors.green) : Divider(color: Colors.red),//index为偶数,创建绿色分割线;index为奇数,则创建红色分割线
    itemBuilder: (BuildContext context, int index) => ListTile(title: Text("title $index"), subtitle: Text("body $index"))//创建子Widget
)

8.2 CustomScrollView

  • CustomScrollView是用来处理多个需要自定义滑动效果的Widget.在CustomScrollView中,这些彼此独立的,可滑动的Widget被统称为Sliver.
  • 比如ListView 的 Sliver 实现为 SliverList,AppBar 的 Sliver 实现为 SliverAppBar
  • 这些Sliver不再维护各自的滚动状态,交由CustomScrollView统一管理,最终实现滑动效果的一致性

CustomScrollView(
  slivers: <Widget>[
    SliverAppBar(//SliverAppBar作为头图控件
      title: Text('CustomScrollView Demo'),//标题
      floating: true,//设置悬浮样式
      flexibleSpace: Image.network("https://xx.jpg",fit:BoxFit.cover),//设置悬浮头图背景
      expandedHeight: 300,//头图控件高度
    ),
    SliverList(//SliverList作为列表控件
      delegate: SliverChildBuilderDelegate(
            (context, index) => ListTile(title: Text('Item #$index')),//列表项创建方法
        childCount: 100,//列表元素个数
      ),
    ),
  ]);

8.3 ScrollController

  • ScrollController用于对ListView进行滚动信息的监听,以及相应的滚动控制.
class MyControllerAppState extends State<MyControllerApp> {
  //ListView控制器
  ScrollController _controller;
  //标识目前是否需要启用top按钮
  bool isToTop = false;

  @override
  void initState() {
    _controller = ScrollController();
    _controller.addListener(() {
      //ListView向下滚动1000 则启用top按钮
      if (_controller.offset > 1000) {
        setState(() {
          isToTop = true;
        });
      } else if (_controller.offset < 300) {
        //向下滚动不足300,则禁用按钮
        setState(() {
          isToTop = false;
        });
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: ListView.builder(
            //将控制器传入
            controller: _controller,
            itemCount: 100,
            itemExtent: 100,
            itemBuilder: (context, index) =>
                ListTile(title: Text('index $index'))),
        floatingActionButton: RaisedButton(
          //如果isToTop是true则滑动到顶部,否则禁用按钮
          onPressed: isToTop
              ? () {
                  //滑动到顶部
                  _controller.animateTo(0.0,
                      duration: Duration(microseconds: 200),
                      curve: Curves.ease);
                }
              : null,
          child: Text('top'),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

}

8.4 NotificationListener

  • NotificationListener是一个Widget,需要将ListView添加到NotificationListener中
class MyListenerApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: NotificationListener<ScrollNotification>(  
          //添加NotificationListener作为父容器
          //注册通知回调
          onNotification: (scrollNotification) {
            //开始滑动
            if (scrollNotification is ScrollStartNotification) {
              //scrollNotification.metrics.pixels 滑动的位置
              print('scroll start ${scrollNotification.metrics.pixels}');
            } else if (scrollNotification is ScrollUpdateNotification) {
              //滑动中
              print('scroll update');
            } else if (scrollNotification is ScrollEndNotification) {
              //滑动结束
              print('scroll end');
            }
            return null;
          },
          child: ListView.builder(
              itemCount: 100,
              itemExtent: 70,
              itemBuilder: (context, index) => ListTile(
                    title: Text('index $index'),
                  )),
        ),
      ),
    );
  }
}

手机扫码阅读