11.表单输入与富文本

声明:Flutter专栏文档均来自慕课网 https://coding.imooc.com/class/321.html

Android、iOS开发者快速上手Flutter-表单输入与富文本

  • 如何获取用户输入?

  • 如何设置输入框的提示文字?

  • 如何显示验证错误信息? ​

如何获取用户输入?

我们知道:

  • 在Android中可以通过EditText获取用户输入;

  • 在iOS中可以通过UITextField获取用户输入;

在Flutter中我们可以使用TextFieldTextFormField,然后通过TextEditingController 来获得用户输入。

class _MyFormState extends State<MyForm> {
  // Create a text controller and use it to retrieve the current value.
  // of the TextField!
  final myController = TextEditingController();

  @override
  void dispose() {
    // Clean up the controller when disposing of the Widget.
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Retrieve Text Input'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: TextField(
          controller: myController,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        // When the user presses the button, show an alert dialog with the
        // text the user has typed into our text field.
        onPressed: () {
          return showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                // 通过TextEditingController获取用户输入
                content: Text(myController.text),
              );
            },
          );
        },
        tooltip: 'Show me the value!',
        child: Icon(Icons.text_fields),
      ),
    );
  }
}

大家可以通过《基于TextField实现顶部SearchBar案例来学习输入框的更多用法和实战技巧,可以通过Flutter Cookbook中的Retrieve the value of a text field获得更多信息。

如何设置输入框的提示文字?

在Flutter 中,你可以通过向 Text widget 的装饰构造器参数设置一个InputDecoration 来展示“小提示”,或是占位符文字。

body: Center(
  child: TextField(
    decoration: InputDecoration(hintText: "This is a hint"),
  ),
)

如何显示验证错误信息?

我们可以TextField的decoration参数为它设置一个InputDecoration,我们借助InputDecoration除了可以添加提示信息外,还可以添加错误信息的提示,具体做法如下:

class _SampleAppPageState extends State<SampleAppPage> {
  String _errorText;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Sample App"),
      ),
      body: Center(
        child: TextField(
          onSubmitted: (String text) {
            setState(() {
              if (!isEmail(text)) {
                _errorText = 'Error: This is not an email';
              } else {
                _errorText = null;
              }
            });
          },
          decoration: InputDecoration(hintText: "This is a hint", errorText: _getErrorText()),
        ),
      ),
    );
  }

  _getErrorText() {
    return _errorText;
  }
  bool isEmail(String emailString) {
    String emailRegexp =
        r'^((<>()[]\.,;:\s@\"+(.<>()[]\.,;:\s@\"+)*)|(\".+\"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$';
    RegExp regExp = RegExp(emailRegexp);
    return regExp.hasMatch(emailString);
  }
}

然而,我们并不想在一开始就显示错误信息,当用户输入的信息不符合规则时我们就可以借助InputDecorationerrorText参数来设置错误提示。

通过学习《基于Flutter1.x开发携程网App获取TextField的更多用法和实战技巧。

image

Last updated