Flutter 学习(四) 基础控件

前面几篇文章咱们学些了Flutter 开发的dart语言基础 ,接下来的文章将开始介绍在flutter 中咱们经常使用的控件 以及控件的属性 动画 以及自定义控件方式...ios

Widget

MaterialApp

主页面根布局bash

//页面主布局
  MaterialApp(
      //内容脚手架 显示标题 内容 drawLayout 底部导航
      home: Scaffold(
      //标题
         appBar: AppBar(
        title: Text('MD 主题'),
        //居中
        centerTitle: true,
        //图标
        leading: Icon(Icons.star),
        //阴影
        elevation: 0.0,
        actions: <Widget>[
          Icon(Icons.search),
          Icon(Icons.more_horiz),
        ],
       ),
        //显示的Ui
        body: Center()
        )

复制代码

1. container : 容器

能够当作是个viewgroup 对要展现的控件进行修饰,下面这个例子就包裹了一个Text控件.只介绍经常使用的属性 ,其余属性能够自行学习,都不会很难理解.网络

Center(
          child: Container(
             //装饰器 定义控件的背景样式  BoxDecoration   DecorationImage
             decoration: BoxDecoration(
             //背景颜色
              color: Colors.black,
              //高斯模糊背景
              boxShadow: [BoxShadow(color: Colors.green, blurRadius: 5.0)],
              //渐变色  也能够设置 扇形渐变 原型渐变
              gradient: LinearGradient(colors: [Colors.black]),
              //形状 BoxShape.circle 能够做为圆形头像进行配置
              shape: BoxShape.circle,
              //图片背景
              image: DecorationImage(
                    //本地资源设置  能够是网络 等其它方式 须要替换AssetImage
                  image: AssetImage("assets/images/ic_avatar_default.png")),
                //边界线条
              border: Border.all(color: Color(0xffff0000), width: 10.0),
              //边界圆角弧度
              borderRadius: const BorderRadius.all(const Radius.circular(30.0)),
            ),
            //约束 宽高约束 通常不用这么设置,直接设置 Container的 height  width就能够
            constraints: BoxConstraints.expand(
              width: 200,
              height:
                  Theme.of(context).textTheme.display1.fontSize * 1.1 + 100.0,
            ),
            //内边距 后边必需要EdgeInsets.all(8.0) 这种形式,也能够单独设置上下左右间距
            padding: EdgeInsets.all(8.0),
            //对齐方式 居中 居左 居上.....
            alignment: Alignment.center,
            //图形变换对这个控件 进行旋转 位移...
            transform: Matrix4.rotationZ(0.1),
            //包裹子控件
            child: Text('Hello World',
                style: Theme.of(context)
                    .textTheme
                    .display1
                    .copyWith(color: Colors.white)),
           
          ),
        ),
        ),
复制代码

2. Text 文字显示

Android上的TextView ,用于文字显示app

Text(
                //文字展现
                'text使用案例 ,的价格哈接口上的干哈接口的规划局考试大纲还以为黄金卡好贵收到货撒金龟换酒后视镜的客观化科技好四大皆空更好看 ',
                //最大行数
                maxLines: 1,
                // 设置成false 超出显示区域的文字不会在现实 只显示一行文字
                softWrap: true,
                //文字对齐方式
                textAlign: TextAlign.center,
                //显示方式 下面这个显示不了的字 后面会加上...
                overflow: TextOverflow.ellipsis,
                //文字样式
                style: TextStyle(
                    //字体颜色
                    color: Colors.green,
                    //加粗
                     fontWeight: FontWeight.bold,
                    //字体大小
                    fontSize:25,
                    //字体样式 斜体 直体
                    fontStyle: FontStyle.normal,
                    //字符间距
                    letterSpacing: 15,
                    //基线对齐
                    textBaseline: TextBaseline.ideographic,
                    //单词间距
                    wordSpacing: 12,
                    //上划线 下划线 中划线
                    decoration: TextDecoration.lineThrough,
                    //线条样式 虚线 直线
                    decorationStyle: TextDecorationStyle.dashed),
              ),
复制代码

3. RichText 富文本

富文本基本属性相似 Textasync

RichText(
                text: TextSpan(
                    text: 'textgjdgasdjkg',
                    style: TextStyle(color: Colors.red).apply(),
                    //富文本须要一段一段设置
                    children: <TextSpan>[
                    //第一条文案的样式若是不设置耿直外层的样式
                      TextSpan(text: '121345654654'),
                      TextSpan(
                        //手势识别器,点击事件捕获
                          recognizer: TapGestureRecognizer()
                            ..onTap = () async {
                              String url = "http://www.baidu.com";
                              if (await canLaunch(url)) {
                                launch(url);
                              } else {
                                throw ('请求地址{$url}');
                              }
                            },
                          text: '百度',
                          style: TextStyle(
                              color: Colors.yellow,
                              decoration: TextDecoration.lineThrough,
                              decorationStyle: TextDecorationStyle.dashed)),
                    ]),
              ),
复制代码

4. BoxSize

盒子类型,用于控件之间的间距ide

SizedBox(
                height: 30,
                width: 30,
              ),
复制代码

5. Center

居中控件可配置子控件居中显示布局

6. Column Row

横向纵向显示学习

Column(
             //副轴对齐  也就是内部空间左右对齐方式
            crossAxisAlignment: CrossAxisAlignment.start,
            //主轴对齐 上下方向的对齐方式
            mainAxisAlignment: MainAxisAlignment.start,
            )

复制代码

7. Expanded

这个控件通常会在Row 里使用当第一个Text控件内容超出显示区域 会出现警告,能够用这个控件包裹下,而后折行显示字体

8. Button

能够设置按钮颜色 等其余属性动画

  • IconButton 图标按钮
IconButton(
              //图标
                icon: Icon(Icons.http),
                //点击事件
                onPressed: () {},
              ),
复制代码
  • RaisedButton 能够显示本身的样式的按钮 而且会显示海拔样式
RaisedButton(
                child: Text('raisedButton'),
                onPressed: () {},
              ),
            
复制代码
  • FlatButton /铺平的按钮
FlatButton(
                child: Text('FlatButton'),
                onPressed: () {},
              ),
  
复制代码
  • FlatButton.icon //图标加控件的按钮
FlatButton.icon(
                  onPressed: () {},
                  icon: Icon(Icons.build),
                  label: Text('FlatButton.icon'))
复制代码

9. Icon

图标显示

Icon(Icons.contact)
复制代码

10. Image

图片加载方式

  • Image.network("www.baidu.com") //网络加载
  • Image.asset( 'assets/images/tzd.jpg'),//asset加载
  • MemoryImage(bytes) //内存加载 须要先获取bytes
rootBundle.load('assets/images/tzd.jpg').then((data) {
      if (mounted) {
        setState(() {
          bytes = data.buffer.asUint8List();
        });
      }
复制代码
  • Image.file(file) //文件加载

11.form

表单提交 相似Android上的输入框 ,下面这个是登录案例 ,须要咱们先获取惟一索引_loginState 而后去获取当前状态去作验证合法性,以及存储数据

void _login() {
    var state = _loginState.currentState;
    if (state.validate()) {
      state.save();
      Scaffold.of(state.context).showSnackBar(SnackBar(
          content: Text('_userName====$_userName+++_password=====$_password')));
    }
  }
复制代码
child: Column(
              children: <Widget>[
                Form(
                    //位移索引
                    key: _loginState,
                    child: Column(
                      children: <Widget>[
                        TextFormField(
                          decoration: InputDecoration(labelText: '请输入用户名'),
                          //保存方法
                          onSaved: (value) {
                            print('onSave');
                            _userName = value;
                          },
                          //提交监听
                          onFieldSubmitted: (value) {
                            print('onFieldSubmitted');
                          },
                        ),
                        TextFormField(
                          decoration: InputDecoration(labelText: '请输入密码'),
                          onSaved: (value) {
                            print('onSave');
                            _password = value;
                          },
                          onFieldSubmitted: (value) {
                            print('onFieldSubmitted');
                          },
                          //模糊文字.隐藏明文
                          obscureText: true,
                          //验证输入的正确性
                          validator: (value) {
                            return value.length < 6 ? '密码最少6位' : null;
                          },
                        ),
                        Container(
                          margin: EdgeInsets.only(top: 50),
                          width: 300,
                          height: 45,
                          child: RaisedButton(
                            child: Text('登录'),
                            onPressed: () {
                              _login();
                            },
                          ),
                        )
                      ],
                    ))
              ],
复制代码

12. ListView

列表展现使用方式分几种

  • ListView.builder()方式 能够设置条目数量 条目显示控件
ListView.builder(
             //滑动方向 纵向 横向
                scrollDirection: Axis.horizontal,
                //数量
              itemCount: 40,
              //条目布局
              itemBuilder: (context, index) {
                if (index.isOdd) {
                  return Divider();
                }
                return ListTile(
                    leading: Icon(Icons.ac_unit),
                    title: Text('$index主标题'),
                    subtitle: Text('副标题'),
                    trailing: Icon(Icons.arrow_forward_ios));
              })
复制代码
  • List.generate方式
ListView(
      scrollDirection: Axis.horizontal,
      children: List.generate(50, (index) {
        return Text(
          '$index',
          style: TextStyle(fontSize: 30),
        );
      }),
    )
复制代码
  • ListView children 控件集合方式 不灵活
ListView(
      children: <Widget>[
        Divider(),
        ListTile(
          leading: Icon(Icons.ac_unit),
          title: Text('主标题'),
          subtitle: Text('副标题'),
          trailing: Icon(Icons.arrow_forward_ios),
        ),
        Divider(),
        ListTile(
          leading: Icon(Icons.ac_unit),
          title: Text('主标题'),
          subtitle: Text('副标题'),
          trailing: Icon(Icons.arrow_forward_ios),
        ),
        Divider(),
      ],
    )
复制代码

13. GridView

  • GridView.builder()
GridView.builder(
            //数量
            itemCount: 50,
            //显示方式 crossAxisCount 一行个数  crossAxisSpacing,mainAxisSpacing 主轴副轴间距
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,crossAxisSpacing: 6, mainAxisSpacing: 6),
                  //条目控件
              itemBuilder: (context, index) {
                return Container(
                    color: Colors.red,
                    child: Text('$index条目'));
              }) //buildGridViewCount(),
          ),
复制代码
  • GridView.count
GridView.count(
    //一行数量
      crossAxisCount: 5,
      //条目的长宽比
      childAspectRatio: 3 / 4,
      //滑动方向
      scrollDirection: Axis.vertical,
      //总数量 个条目控件设置
      children: List.generate(50, (index) {
        return Container(
            margin: EdgeInsets.all(10),
            color: Colors.red,
            child: Text('$index条目'));
      }),
    )
复制代码

14 ListTile

系统封装好的 标题 描述 图标 箭头 控件

ListTile(
          leading: Icon(Icons.ac_unit),
          title: Text('主标题'),
          subtitle: Text('副标题'),
          trailing: Icon(Icons.arrow_forward_ios),
        )
复制代码

15. Card

卡片布局

Card(
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.all(Radius.circular(10.0))),
      child: Column( )
    )

复制代码

16.Padding

Padding(
                padding: const EdgeInsets.all(15.0),
                child: Icon(Icons.contact_mail),
              )
复制代码

17. Scaffold 脚手架

  • AppBar标题
appBar: AppBar(
        title: Text('MD 主题'),
        //居中
        centerTitle: true,
        //图标
        leading: Icon(Icons.star),
        //阴影
        elevation: 0.0,
        //菜单
        actions: <Widget>[
          Icon(Icons.search),
          Icon(Icons.more_horiz),
        ],
      ),
复制代码
  • floatingActionButton
floatingActionButton: FloatingActionButton(
          child: Icon(Icons.access_alarm),
          <!--背景色-->
          backgroundColor: Colors.yellow,
          <!--这个能够给图片添加颜色-->
          foregroundColor: Colors.red,
          tooltip: '长按',
//          shape: RoundedRectangleBorder(),
          onPressed: () {
          //跳转操做 后续会介绍
            Navigator.pushNamed(context, "/newPager");
          }),
复制代码
  • BottomNavigationBar
bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        items: <BottomNavigationBarItem>[
          BottomNavigationBarItem(icon: Icon(Icons.list), title: Text('主页')),
          BottomNavigationBarItem(icon: Icon(Icons.save), title: Text('通信录')),
          BottomNavigationBarItem(icon: Icon(Icons.print), title: Text('订单')),
          BottomNavigationBarItem(icon: Icon(Icons.launch), title: Text('个人')),
        ],
        currentIndex: _currentIndex,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
      ),
复制代码
  • drawer
Drawer(
//        elevation: 30,
      child: ListView(
        children: <Widget>[
        //显示标题描述  头像 图标 北京
          UserAccountsDrawerHeader(
            accountName: Text(
              "刘泽",
              style: TextStyle(color: Colors.black),
            ),
            accountEmail: Text(
              '835052259@qq.com',
              style: TextStyle(color: Colors.black),
            ),
            //头像
            currentAccountPicture: CircleAvatar(
              backgroundImage: NetworkImage(
                  "https://img5.duitang.com/uploads/item/201411/18/20141118201614_8Bjax.thumb.700_0.jpeg"),
            ),
            otherAccountsPictures: <Widget>[Icon(Icons.camera)],
            /背景
            decoration: BoxDecoration(
                image: DecorationImage(
                    fit: BoxFit.fill,
                    image: NetworkImage(
                        "http://img.jituwang.com/uploads/allimg/150109/258940-15010922123023.jpg"))),
          ),
        //这个能够弹出关于的弹框提示
          AboutListTile(
            child: Text('关于'),
            icon: Icon(Icons.add_box),
            applicationName: "版本升级",
            applicationVersion: '1.0.0',
            applicationIcon: Icon(Icons.launch),
            applicationLegalese: '描述',
            aboutBoxChildren: <Widget>[
              Text('按钮1'),
              Text('按钮2'),
              Text('按钮3'),
            ],
          )
        ],
      ),
    )
复制代码

18. CircleAvatar

圆形头像控件

未完待续

下一篇文章将介绍 dialog 关于位置的控件 以及 在ios风格下 Cupertino 的应用

相关文章
相关标签/搜索