当前位置:网站首页>Flutter Getting Started and Advanced Tour (4) Text Input Widget TextField

Flutter Getting Started and Advanced Tour (4) Text Input Widget TextField

2022-08-09 13:19:00 Xie Dong_

       What we learned together in the previous articleTextwith how to giveTextset the font style andText Widget的一些常用属性Flutter入门进阶之旅(三) Text Widgets,通过对TextWe learn to learnTextis used to display text,If there are some special requirements for the displayed text,比如字体样式,Text color we can passTextStyle去给Text指定styleto do personalization,This is the originalAndroid的TextView非常类似,With text display, there will definitely be text input,今天我们就一起来学习一下FlutterThe text in the inputWidget TextField.

先来看下TextField的构造方法

const TextField({
    Key key,
    this.controller,           控制器,控制TextField文字
    this.focusNode,
    this.decoration = const InputDecoration(),    //输入器装饰
    TextInputType keyboardType,   输入的类型
    this.textInputAction,
    this.textCapitalization = TextCapitalization.none,
    this.style,
    this.textAlign = TextAlign.start,   //文字显示位置
    this.autofocus = false,
    this.obscureText = false,
    this.autocorrect = true,
    this.maxLines = 1,
    this.maxLength,
    this.maxLengthEnforced = true,
    this.onChanged,                //文字改变触发
    this.onEditingComplete,   //当用户提交可编辑内容时调用
    this.onSubmitted,   文字提交触发(键盘按键)
    this.inputFormatters,
    this.enabled,
    this.cursorWidth = 2.0,
    this.cursorRadius,
    this.cursorColor,
    this.keyboardAppearance,
    this.scrollPadding = const EdgeInsets.all(20.0),
  })

Through the above construction method and preview renderings,熟悉androidDo the developers who are developing feel a sense of deja vu?,Flutter的TextField跟原生Android中的EditTextUsage, including some attribute names, are almost the same,比如我们可以通过keyboardTypeTo specify the input mode of arouse the software disk,For example, the two input box property settings in the above figure:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(new MaterialApp(home: new PullToRefreshDemo()));
}

class PullToRefreshDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text("文本输入"),
      ),
      body: new Center(
          child: new Column(
        children: <Widget>[
          new Text("Simple text input box",style: new TextStyle(fontSize: 20.0)),
          new TextField(keyboardType: TextInputType.text,),  //Specify the input method as text input
          new TextField(keyboardType: TextInputType.number,),//Specifies to display the numeric keyboard by default when the soft keyboard is invoked

        ],
      )),
    );
  }
}

Through the above construction method, we notice thatTextField给我提供了onChanged、onSubmitted、OnEditingCompleteThe callback method helps us monitor the content change of the input box、编辑提交、Editing completion and other events,Let's test the binding of the above monitoring method to the input box:

   new TextField(
            onSubmitted: (value){
              print("------------文字提交触发(键盘按键)--");
            },
            onEditingComplete: (){
              print("----------------编辑完成---");
            },
            onChanged: (value){
              print("----------------The content of the input box is:$value--");
            },
            keyboardType: TextInputType.text,
          ), 

Type in the input box after evoking the soft keyboard123456,log控制台打印出:

At this point, you have completely used the basic use of the input boxget到了,But the reality in the development process,Maybe we will need to specify some auxiliary description content for the input box,For example, when the input box has no input content, addhint提示,Or add next to the input boxIcon指示,Or internal text input box to display、背景色等等,These auxiliary settings areFlutterThere is a unifiedInputDecorationdecorator to complete the operation,我们先来看下InputDecoration的构造方法,Then let's simply try a few operations commonly used in daily development.

const InputDecoration({
    this.icon, //输入框左侧添加个图标
    this.labelText,//输入框获取焦点/有内容 会移动到左上角,否则在输入框内labelTex的位置
    this.labelStyle,
    this.helperText,
    this.helperStyle,
    this.hintText, //未输入文字时,输入框中的提示文字
    this.hintStyle,
    this.errorText,
    this.errorStyle,
    this.errorMaxLines,
    this.isDense,
    this.contentPadding,
    this.prefixIcon, //输入框内侧左面的控件
    this.prefix,
    this.prefixText,
    this.prefixStyle,
    this.suffixIcon,//输入框内侧右面的图标
    this.suffix,
    this.suffixText,
    this.suffixStyle,
    this.counterText,
    this.counterStyle,
    this.filled,
    this.fillColor,
    this.errorBorder,
    this.focusedBorder,
    this.focusedErrorBorder,
    this.disabledBorder,
    this.enabledBorder,
    this.border,  //增加一个边框
    this.enabled = true,
    this.semanticCounterText,
  })

Add input auxiliary input description to input box:

 body: new Center(
          child: new TextField(
            decoration: new InputDecoration(
                labelText: "请输入内容",//输入框内无文字时提示内容,有内容时会自动浮在内容上方
                helperText: "随便输入文字或数字", //输入框底部辅助性说明文字
                prefixIcon: new Icon(Icons.print), //input box left icon
                suffixIcon: new Icon(Icons.picture_as_pdf), //Picture on the right side of the input box
                contentPadding: const EdgeInsets.only(bottom:15.0)),
            keyboardType: TextInputType.number,
          ),
        ));

 

通过给InputDecoration设置borderAdd border to input box:

  body: new Center(
          child: new TextField(
            decoration: new InputDecoration(
                border: new OutlineInputBorder(  //添加边框
                  gapPadding: 10.0,
                  borderRadius: BorderRadius.circular(20.0),
                ),
                prefixIcon: new Icon(Icons.print),
                contentPadding: const EdgeInsets.all(15.0)),
            keyboardType: TextInputType.number,
          ),
        ));

 

Other styles and attributes readers can run the experience by themselves,I won't list them one by one.,In short, use the reference documents combined with the experience of native developmentTextField还是比较简单的.I share a complete login belowUI的例子供大家参考:

完整代码:

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(home: new MyApp()));
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    TextEditingController _userPhoneController = new TextEditingController();
    TextEditingController _userPasswordController = new TextEditingController();

    /**
     * 清空输入框内容
     */
    void onTextClear() {
      setState(() {
        _userPhoneController.text = "";
        _userPasswordController.text = "";
      });
    }

    return new Scaffold(
        appBar: new AppBar(
          title: new Text("登录"),
        ),
        body: new Column(
          children: <Widget>[
            new TextField(
              controller: _userPhoneController,
              keyboardType: TextInputType.number,
              decoration: new InputDecoration(
                  contentPadding: const EdgeInsets.all(10.0),
                  icon: new Icon(Icons.phone),
                  labelText: "请输入手机号",
                  helperText: "The mobile phone number entered during registration"),
              onChanged: (String str) {
                //onChanged是每次输入框内每次文字变更触发的回调
                print('手机号为:$str----------');
              },
              onSubmitted: (String str) {
                //onSubmitted是用户提交而触发的回调{当用户点击提交按钮(Input the enter key)}
                print('最终手机号为:$str---------------');
              },
            ),
            new TextField(
              controller: _userPasswordController,
              keyboardType: TextInputType.text,
              decoration: new InputDecoration(
                  contentPadding: const EdgeInsets.all(10.0),
                  icon: new Icon(Icons.nature_people),
                  labelText: "请输入名字",
//                  hintText: "fdsfdss",
                  helperText: "注册名字"),
            ),
            new Builder(builder: (BuildContext context) {
              return new RaisedButton(
                onPressed: () {
                  if (_userPasswordController.text.toString() == "10086" &&
                      _userPhoneController.text.toString() == "10086") {
                    Scaffold.of(context)
                        .showSnackBar(new SnackBar(content: new Text("校验通过")));
                  } else {
                    Scaffold.of(context)
                        .showSnackBar(new SnackBar(content: new Text("校验有问题,请重新输入")));
                    onTextClear(); //Is the input,让用户重新输入
                  }
                },
                color: Colors.blue,
                highlightColor: Colors.deepPurple,
                disabledColor: Colors.cyan,
                child: new Text(
                  "登录",
                  style: new TextStyle(color: Colors.white),
                ),
              );
            })
          ],
        ));
  }
}

下一篇:Flutter入门进阶之旅(五)Image Widget

原网站

版权声明
本文为[Xie Dong_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208091203557140.html