Flutter 常用 Widget 介绍

avatar
Android @奇舞团Android团队

级别:★☆☆☆☆
标签:「Flutter 常用 Widget」「SafeArea」「Expanded」「Wrap」「FutureBuilder」
作者: ITWYW
审校: aTaller团队

前言

笔者最近在看 Flutter Widget of the Week!,并落地了代码 FlutterLearningRecord。在本文中,笔者将分享几个 Widget 的使用场景及使用方式。在本文中,笔者会介绍如下Widget:SafeArea、Expanded、Wrap、AnimatedContainer、Opacity、FutureBuilder、在底部AppBar居中的 FloatingActionButton。

首先给大家展示下目前笔者做的常用 Widget 的效果。

一、常用 Widget Demo 效果

commonUsedWidget.gif

笔者上方的常用 Widget Demo 效果图,展示了SafeArea、Expanded、Wrap、AnimatedContainer、Opacity、FutureBuilder、在底部AppBar居中的 FloationgActionButton的使用场景及使用效果。

Widget 使用场景
SafeArea 用于带头帘、下巴的设备
Expanded 用于Row、Column中的子Widget布局完后,撑开剩余空间
Wrap 用于包裹可能子Widget可能越过屏幕边界的场景,使子Widget可以换行
AnimatedContainer 用于给子Widget做动画效果
Opacity 用于对子Widget做不透明度处理
AnimatedOpacity 用于给子Widget的不透明度变化过程做动画
FutureBuilder 用于耗时任务,耗时执行完后返回请求到的数据
FloationActionButton 可以在BottomAppBar底部居中,一定程度适用发布视频文章,也可在屏幕中其他位置悬浮

下边给大家简单介绍下上边的Widget的使用方式。

二、常用 Widget 使用方式

1. SafeArea

1.1 不带SafeArea 示意图

01noSafeArea.png

1.2 带SafeArea 示意图

01SafeAreaEnable.png

使用 SafeArea 作为 body 的子 Widget,原来的子 Widget 作为 SafeAreade 的子 Widget;

1.3 SafeArea 示例代码
@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: ListView(
          children: <Widget>[
            _randomColorContainer(),
          ],
        ),
      ),
    );
  }

####2. Expanded

2.1 左右 Expanded(黄色部分Widget) 分别占剩余空间的2:1

Expanded.png

Expanded 会显然同级的其他 Widget 先布局,之后剩余的空间,Expanded 才会去占用。

当有多个Expanded时,Expanded的 flex 参数,用于指定要占空白的空间的比例。

2.2 Expaned 示例代码
Row _expandedRow3() {
    return Row(
      children: <Widget>[
        Text(
          '3.LeftText',
          style: TextStyle(fontSize: 32.0, backgroundColor: Colors.greenAccent),
        ),
        Expanded(
            flex: 2,
            child: Container(
              height: 20.0,
              color: Colors.yellow,
            )),
        Container(
          color: Colors.blue,
          width: 100.0,
          // width: 10.0,
          height: 50.0,
          child: Text(
            'C',
            style:
                TextStyle(fontSize: 32.0, backgroundColor: Colors.greenAccent),
          ),
        ),
        Expanded(
            flex: 1,
            child: Container(
              height: 20.0,
              color: Colors.yellow,
            )),
        Container(
          width: 100.0,
          height: 50.0,
          child: Text(
            'Right',
            style:
                TextStyle(fontSize: 32.0, backgroundColor: Colors.greenAccent),
          ),
        ),
      ],
    );
  }

####3. Wrap

3.1 Wrap Demo 示意图

Wrap.png

3.2 Wrap 示例代码
Wrap horizontalWrap(int index) {
    return Wrap(
      // 默认主轴为水平方向
      // direction: Axis.horizontal,
      children: <Widget>[
        horizontalRandomColorWrapContainer(index++),
        horizontalRandomColorWrapContainer(index++),
        horizontalRandomColorWrapContainer(index++),
        horizontalRandomColorWrapContainer(index++),
      ],
    );
  }

####4. AnimatedContainer

4.1 AnimatedContainer 执行动画前示意图

AnimatedContainer1.png

4.2 AnimatedContainer 执行动画后示意图

AnimatedContainer2.png

AnimatedContainer 执行前后,改变了 Widget 的背景色、宽度、高度、子 Widget 的对齐方式。

AnimatedContainer 示例代码
AnimatedContainer(
  onEnd: () {
    print('动画结束');
  },
  child: DecoratedBox(
    child: FlutterLogo(size: halfContainerWH,),
    decoration: BoxDecoration(
    //TODO: borderRadius 效果
    borderRadius: selected ? BorderRadius.all(Radius.circular(25.0)) : BorderRadius.all(Radius.circular(0)),
  )),
  duration: Duration(seconds: 2),
  curve: Curves.linearToEaseOut,
  width: selected ? halfContainerWH : containerWH,
  height: selected ? containerWH : halfContainerWH,
  alignment: selected ? Alignment.topCenter : Alignment.center,
  color: selected ? Colors.purpleAccent : Colors.blueGrey),

####5. Opacity

5.1 Opacity 的不透明度

Opacity.png

5.2 Opacity 示例代码
Opacity(
  opacity: 1.0,
  child: Container(
    decoration: BoxDecoration(color: Colors.blue),
    child: Text(
      'Opacity: 1.0',
      style: TextStyle(
          color: Colors.white,
          backgroundColor: Colors.blue,
          fontSize: 24.0),
    ),
  ),
  // child: Text('Opacity:1.0'),
),

6. AnimatedOpacity

6.1 AnimatedOpacity 改变透明度前

AnimatedOpacity.png

6.2 AnimatedOpacity 改变透明度后

AnimatedOpacity2.png

6.3 AnimatedOpacity 示例代码
AnimatedOpacity(
  onEnd: () {
    print('动画结束');
  },
  opacity: animatedOpacityValue,
  duration: Duration(seconds: 2),
  curve: Curves.fastOutSlowIn,
  child: FlutterLogo(size: 100.0),
),

####7. FutureBuilder

7.1 FutureBuilder 效果图

FutureBuilder.gif

7.2 FutureBuilder 示例代码
FutureBuilder(
future: Dio().get('https://api.github.com/orgs/flutterchina/repos'),
builder: (BuildContext context, AsyncSnapshot snapshot) {
  if (snapshot.connectionState == ConnectionState.done) {
    Response response = snapshot.data;
    // 请求结果有误,显示错误信息
    if (snapshot.hasError) {
      return Text(snapshot.error.toString());
    }
    // 显示请求结果
    return ListView(
      children: response.data
          .map<Widget>((obj) => ListTile(
              title: Text(obj["name"]),
              subtitle: Text(obj["full_name"])))
          .toList(),
    );
  } else if (snapshot.connectionState == ConnectionState.waiting) {

  } else if (snapshot.connectionState == ConnectionState.none) {

  }
  // 请求过程中返回进度指示器
  return CircularProgressIndicator(
    strokeWidth: 10.0,
    semanticsLabel: '请稍候...',
  );
}),

####8. FloationgActionButton

8.1 居中 FloatingActionButton 效果

FloationActionButtonBottomCenter.png

8.2 floationActionButton 居中示例代码
floatingActionButton: FloatingActionButton(
    // child: Text('FAB'),
    child: Icon(Icons.add),
    onPressed: () {
      print('点击FAB');
    },
  ),
  floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
  bottomNavigationBar: BottomAppBar(
    color: Colors.blue,
    child: Container(
      height: 44.0,
    ),
  ),

三、Demo

Demo 下载地址: FlutterLearningRecord

四、参考学习网址


笔者微信:可加并拉入《aTaller技术交流群》。

笔者微信

关注我们的途径有:
aTaller(简书)
aTaller(掘金)
aTaller(微信公众号)

推荐文章:
Flutter 图片加载
Flutter 混合栈复用原理
Flutter Platform Channel 使用与源码分析
Flutter Platform View 使用及原理简析
奇舞周刊