Flutter记录的第四天 基础控件

一、Text文本

Text是显示文本的组件,最常用的组件,都没有之一。基本用法如下:

Text("Hello world1",
  maxLines: 1,// 最大显示行数
  //是否自动换行 false文字不考虑容器大小,单行显示,超出屏幕部分将默认截断处理
  softWrap: true,
  //文字超出屏幕之后的处理方式  TextOverflow.clip剪裁   TextOverflow.fade 渐隐  TextOverflow.ellipsis省略号
  overflow: TextOverflow.ellipsis,
  //TextDirection.ltr从左至右,TextDirection.rtl从右至左
  textDirection: TextDirection.rtl,
  //TextAlign.left左对齐,TextAlign.right右对齐,TextAlign.center居中对齐,TextAlign.justfy两端对齐
  textAlign: TextAlign.center,
  style: TextStyle(
      color: Colors.blue,//字体颜色
      fontSize: 18.0,//字体大小
      height: 5.5,//字体高度
      fontFamily: "Courier",
      background: new Paint()..color=Colors.yellow,
      decoration:TextDecoration.underline,//下划线
      decorationStyle: TextDecorationStyle.dashed//下划线  样式
  ),
);

效果如下

 

二、button按钮

///自定义按钮外观
//@required this.onPressed, //按钮点击回调
//this.textColor, //按钮文字颜色
//this.disabledTextColor, //按钮禁用时的文字颜色
//this.color, //按钮背景颜色
//this.disabledColor,//按钮禁用时的背景颜色
//this.highlightColor, //按钮按下时的背景颜色
//this.splashColor, //点击时,水波动画中水波的颜色
//this.colorBrightness,//按钮主题,默认是浅色主题
//this.padding, //按钮的填充
//this.shape, //外形
//@required this.child, //按钮的内容
//this.elevation = 2.0, //正常状态下的阴影
//this.highlightElevation = 8.0,//按下时的阴影
//this.disabledElevation = 0.0,// 禁用时的阴影
///RaisedButton 即"漂浮"按钮,它默认带有阴影和灰色背景。按下后,阴影会变大
var buttonOne = new RaisedButton(
  child: Text("normal"),
  onPressed: () {},
);

///FlatButton即扁平按钮,默认背景透明并不带阴影。按下后,会有背景色
var buttonTow = new FlatButton(
  child: Text("normal"),
  onPressed: () {},
);

///OutlineButton默认有一个边框,不带阴影且背景透明。按下后,边框颜色会变亮、同时出现背景和阴影(较弱)
var buttonThree = new OutlineButton(
  child: Text("normal"),
  onPressed: () {},
);

///IconButton是一个可点击的Icon,不包括文字,默认没有背景,点击后会出现背景
var buttonFour = new IconButton(
  icon: Icon(Icons.thumb_up),
  onPressed: () {},
);

///带图标的按钮
///RaisedButton、FlatButton、OutlineButton都有一个icon 构造函数,通过它可以轻松创建带图标的按钮
var buttonFire1 = RaisedButton.icon(
  icon: Icon(Icons.send),
  label: Text("发送"),
  onPressed: () {},
);
var buttonFire2 = OutlineButton.icon(
  icon: Icon(Icons.add),
  label: Text("添加"),
  onPressed: () {},
);
var buttonFire3 = FlatButton.icon(
  icon: Icon(Icons.info),
  label: Text("详情"),
  onPressed: () {},
);
Column(
          children: <Widget>[
            RaisedButton(
              child: Text("normal"),
              onPressed: () {},
            ),
            FlatButton(
              child: Text("normal"),
              onPressed: () {},
            ),
            OutlineButton(
              child: Text("normal"),
              onPressed: () {},
            ),
            IconButton(
              icon: Icon(Icons.thumb_up),
              onPressed: () {},
            ),
            RaisedButton.icon(
              icon: Icon(Icons.send),
              label: Text("发送"),
              onPressed: () {},
            ),
            OutlineButton.icon(
              icon: Icon(Icons.add),
              label: Text("添加"),
              onPressed: () {},
            ),
            FlatButton.icon(
              icon: Icon(Icons.info),
              label: Text("详情"),
              onPressed: () {},
            ),
            FlatButton(
              color: Colors.blue,
              highlightColor: Colors.blue[700],
              colorBrightness: Brightness.dark,
              splashColor: Colors.grey,
              child: Text(
                "Submit",
              ),
              shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
              onPressed: () {
              },
            )
          ],
        ),

效果图如下:

三、Image图片控件

///在工程根目录下创建一个images目录,并将图片avatar.png拷贝到该目录。
///在pubspec.yaml中的flutter部分添加如下内容:
///assets:
///    - images/avatar.png
///    加载本地图片
var imageView1 = Image(
    image: AssetImage("images/img.png"),
    width: 100.0,
    height: 100.0,
);
var imageView2 = Image.asset(
    "images/img.png",
    width: 100.0,
);

///从网络加载图片
var imageView3 = Image(
    image: NetworkImage(
        "https://avatars2.githubusercontent.com/u/20411648?s=460&v=4"),
    width: 100.0,
);
var imageView4 = Image.network(
    "https://avatars2.githubusercontent.com/u/20411648?s=460&v=4",
    width: 100.0,
);

//const Image({
//...
//this.width, //图片的宽
//this.height, //图片高度
//this.color, //图片的混合色值
//this.colorBlendMode, //混合模式
//this.fit,//缩放模式
//this.alignment = Alignment.center, //对齐方式
//this.repeat = ImageRepeat.noRepeat, //重复方式
//...
//})

四、icon图标

///     ICON
/// Flutter默认包含了一套Material Design的字体图标,在pubspec.yaml文件中的配置如下
///flutter:
///  uses-material-design: true
///Material Design所有图标可以在其官网查看:https://material.io/tools/icons/
// fingerprint: &#xE90D; or 0xE90D or E90D
//icons += " \uE90D";

var icon1 =Text("\uE914 \uE90D",
    style: TextStyle(
        fontFamily: "MaterialIcons",
        fontSize: 24.0,
        color: Colors.green
    ),
);

///Flutter封装了IconData和Icon来专门显示字体图标
var icon2 =Row(
    mainAxisAlignment: MainAxisAlignment.center,
    children: <Widget>[
        Icon(Icons.accessible,color: Colors.green,),
        Icon(Icons.error,color: Colors.green,),
        Icon(Icons.fingerprint,color: Colors.green,),
    ],
);

五、Checkbox选择框

Checkbox是勾选框控件,本身不包含任何状态,改变状态需要通过改变value的值改变。基本用法如下:

var _checkValue = false;
_buildCheckbox(){
  return Checkbox(
    value: _checkValue,
    onChanged: (value){
      setState(() {
        _checkValue = value;
      });
    },
  );
}

效果如下:

value值为bool类型,true表示选择状态。

onChanged为发生变化时回调,即点击控件时回调,方法内的参数为新的值。

activeColor为激活状态下颜色,是矩形区域内的颜色,checkColor是选中后“对勾”的颜色,用法如下:

Checkbox(
  activeColor: Colors.red,
  checkColor: Colors.blue,
  ...
)

效果如下:

#CheckboxListTile

通常情况下,我们不直接使用Checkbox,而是使用CheckboxListTile,因为我们需要Checkbox后面添加说明,用法如下:

Container(
  width: 120,
  child: CheckboxListTile(
    title: Text('老孟'),
    value: _checkValue,
    onChanged: (value){
      setState(() {
        _checkValue = value;
      });
    },
  ),
)

CheckboxListTile默认是充满父组件的,因此需要Container限制其宽度,效果如下:

一般的习惯是将勾选框放在前面,用法如下:

CheckboxListTile(
  controlAffinity: ListTileControlAffinity.leading,
  ...
)

ListTileControlAffinity取值范围说明如下:

  • leading:勾选框在开头位置。
  • trailing:勾选框在结尾位置,
  • platform:根据平台确定

还可以设置其子标题和第二图标,用法如下:

CheckboxListTile(
  subtitle: Text('一枚有态度的程序员'),
  secondary: Icon(Icons.person),
  ...
)

secondary一般放置一个图标,位于勾选框的另一边。效果如下:

 

六、Switch

Switch为material风格的开关组件,基本用法如下:

var _switchValue = false;
_buildSwitch(){
  return Switch(
    value: _switchValue,
    onChanged: (value){
      setState(() {
        _switchValue = value;
      });
    },
  );
}

效果如下:

设置激活状态下thumb及track颜色,用法如下:

Switch(
      activeColor: Colors.red,
      activeTrackColor: Colors.blue,
      ...
    )

效果如下:

注意红色区域为thumb,蓝色区域为track。

thumb区域也可以设置图片,用法如下:

Switch(
  activeThumbImage: AssetImage('images/bird.png',),
  ...
)

效果如下:

有激活状态样式的设置,也有未激活样式的设置,用法如下:

Switch(
  inactiveThumbColor: Colors.black54,
  inactiveThumbImage: AssetImage('images/bird.png',),
  inactiveTrackColor: Colors.blue,
  ...
)

#SwitchListTile

SwitchListTile是Switch和ListTile组合控件,基本用法如下:

var _switchValue = false;
_buildSwitch(){
  return SwitchListTile(
    title:Text('是否允许4G下载'),
    value: _switchValue,
    onChanged: (value){
      setState(() {
        _switchValue = value;
      });
    },
  );
}

效果如下:

所有的属性都是Switch和ListTile属性的组合,可到具体控件查看其属性。

#CupertinoSwitch

CupertinoSwitch是ios风格控件,用法和Switch一样,用法如下:

var _switchValue = false;
_buildSwitch(){
  return CupertinoSwitch(
    value: _switchValue,
    onChanged: (value){
      setState(() {
        _switchValue = value;
      });
    },
  );
}

效果如下:

 

七、TextField 输入框

const TextField({
    Key key,
      //控制正在编辑的文本。通过其可以拿到输入的文本值
      //获取方式 String value=controller.text
    this.controller,           控制器,控制TextField文字
      //控制此小部件是否具有键盘焦点。
    this.focusNode,
      //给TextField设置装饰(形状等)
    this.decoration = const InputDecoration(
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(10.0),
            borderSide: BorderSide(color: Colors.transparent)
          ),
          //输入内容距离上下左右的距离 ,可通过这个属性来控制 TextField的高度
          contentPadding: EdgeInsets.all(10.0),
          fillColor: Colors.white, filled: true,
          // labelText: 'Hello',
          // 以下属性可用来去除TextField的边框
          disabledBorder: InputBorder.none,
          enabledBorder:  InputBorder.none,
          focusedBorder:   InputBorder.none,
    ),    //输入器装饰
    TextInputType keyboardType,   输入的类型 TextInputType.text
      //控制键盘的功能键 指enter键,比如此处设置为next时,enter键
      //显示的文字内容为 下一步
    this.textInputAction,  //TextInputAction.next
      //键盘大小写的显示 Only supports text keyboards  但是好像不起作用?
      //characters 默认为每个字符使用大写键盘
      //sentence 默认为每个句子的第一个字母使用大写键盘
      //word 默认为每个单词的第一个字母使用大写键盘。
      //none 默认使用小写
    this.textCapitalization = TextCapitalization.none,
    this.style,
    this.textAlign = TextAlign.start,   //文字显示位置 
    this.autofocus = false,   //是否自动获得焦点
    this.obscureText = false, //是否是密码
    this.autocorrect = true, //是否自动更正
    this.maxLines = 1,
      //最大长度,设置此项会让TextField右下角有一个输入数量的统计字符串
      //这种情况一般是不符合我们设计的要求的,但是有需要限制其输入的位数
      // 这时候我们可以使用下方的属性来限制
    this.maxLength,  
      // 跟最大长度限制对应,如果此属性设置为false,当输入超过最大长度
      // 限制时,依然会显示输入的内容,为true不会(默认为 true)
    this.maxLengthEnforced = true,
      // 限制输入的 最大长度  TextField右下角没有输入数量的统计字符串
    this.inputFormatters: [LengthLimitingTextInputFormatter(11)],
    //允许的输入格式 下方的模式指只允许输入数字
    this.inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
    this.onChanged,                //内容改变的回调
    this.onEditingComplete,   //按回车时调用
    this.onSubmitted,      //内容提交(按回车)的回调
    this.enabled,
    //光标宽度
    this.cursorWidth = 2.0,
    this.cursorRadius,   //光标圆角弧度
    //光标颜色 
    this.cursorColor,
    this.keyboardAppearance,
    this.scrollPadding = const EdgeInsets.all(20.0),
  })

输入框用法大全

class page extends StatefulWidget {
  page({Key key}) : super(key: key);

  @override
  _PageState createState() => _PageState();
}

class _PageState extends State<page> {

  final controller = TextEditingController();
  FocusNode focusNode1 = new FocusNode();
  FocusNode focusNode2 = new FocusNode();
  FocusScopeNode focusScopeNode;
  var _textFieldValue = '';

  @override
  void initState() {
    super.initState();
    controller.addListener(() {
      print('input ${controller.text}');
    });
  }

  @override
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Container Title",
      home: Scaffold(
        appBar: AppBar(
          title: Text(
            "Container Titlte",
            style: TextStyle(color: Colors.cyan),
          ),
        ),
        body:Column(
          children: <Widget>[
            TextField(
              autofocus: true, //是否自动获得焦点
              obscureText: false,//是否是密码
              maxLines: 5,//最大行数
              minLines: 3,//最小行数
//              keyboardType: TextInputType.text,//指定输入方式为文本输入
              keyboardType: TextInputType.number,//指定唤起软键盘时默认显示数字键盘
              focusNode: focusNode1,//关联focusNode1
              controller: controller, 控制器,控制TextField文字
              //给TextField设置装饰(形状等)
              decoration: InputDecoration(
                border: OutlineInputBorder(//输入边框
                    borderRadius: BorderRadius.circular(10.0),
                    borderSide: BorderSide(color: Colors.transparent)
                ),
                icon: Icon(Icons.person_add),//在控件左方
                prefixIcon: Icon(Icons.person),//在控件中的左方
                labelText: '姓名:',//上方提示文字
                labelStyle: TextStyle(color:Colors.red),
                helperText: '用户名长度为6-10个字母',//下方方提示文字
                helperStyle: TextStyle(color: Colors.blue),
                helperMaxLines: 1,
                hintText: '请输入用户名',//提示文字
                hintStyle: TextStyle(color: Colors.grey),
                hintMaxLines: 1,
//                errorText: '用户名输入错误',//错误提示
//                errorStyle: TextStyle(fontSize: 12),
//                errorMaxLines: 1,
//                errorBorder: OutlineInputBorder(borderSide: BorderSide(color: Colors.red)),
                counterText: '${_textFieldValue.length}/32',//提示字数
                //输入内容距离上下左右的距离 ,可通过这个属性来控制 TextField的高度
                contentPadding: EdgeInsets.all(10.0),
                // 以下属性可用来去除TextField的边框
                disabledBorder: InputBorder.none,
                enabledBorder:  InputBorder.none,
                focusedBorder:   InputBorder.none,
              ),
              textAlign: TextAlign.center, //文字显示位置

              onChanged: (value){//内容改变的回调
                setState(() {
                  _textFieldValue = value;
                });
              },
              onSubmitted: (value){//内容提交(按回车)的回调
                setState(() {
                  _textFieldValue = value;
                });
              },
              onEditingComplete: (){
                print("----------------编辑完成---");
              },
            ),
            TextField(
              focusNode: focusNode2,//关联focusNode2
              decoration: InputDecoration(
                  labelText: "input2"
              ),
            ),
            RaisedButton(
              child: Text("移动焦点"),
              onPressed: () {
                //将焦点从第一个TextField移到第二个TextField
                // 这是一种写法 FocusScope.of(context).requestFocus(focusNode2);
                // 这是第二种写法
                if(null == focusScopeNode){
                  focusScopeNode = FocusScope.of(context);
                }
                focusScopeNode.requestFocus(focusNode2);
              },
            ),
            RaisedButton(
              child: Text("隐藏键盘"),
              onPressed: () {
                // 当所有编辑框都失去焦点时键盘就会收起
                focusNode1.unfocus();
                focusNode2.unfocus();
              },
            ),
          ],
        ),
      ),
    );

  }

  //销毁
  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值