Flutter入门 - 表单

TextField - 文本框

class MyTextField extends StatefulWidget{

  @override
  State createState() {
    // TODO: implement createState
    return MyText();
  }

}

class MyText extends State {
  final textController = TextEditingController();
  @override
  void dispose() {
    super.dispose();
    textController.dispose();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    textController.text = "hi";
    textController.addListener((){
      textController.text = "23";

    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return TextField(
      controller: textController,
      onSubmitted: (value) => {

      },
      decoration: InputDecoration(
          icon: Icon(Icons.add_a_photo),
          hintText: "请输入什么东1西",
          helperText: "什么东西",
          labelText: "呵呵",
//              border: InputBorder.none
          border: OutlineInputBorder()
      ),
    );
  }
}

Form - 表单
TextFormField - 表单输入框
RaisedButton - 表单按钮

class MyFormTextField extends StatefulWidget{
  @override
  State createState() {
    // TODO: implement createState
    return MyField();
  }

}

class MyField extends State {

  final key = GlobalKey();
  bool auto = false;
  String userName,passWord;

  void save(){
    if(key.currentState.validate()){
      key.currentState.save();

      Scaffold.of(context).showSnackBar(
        SnackBar(
        content: Text("hehe"),
        )
      );
    }else{
      auto = true;
    }

  }

  String checkPhone(String value){
    if(value.isEmpty){
      return "enter phone";
    }
  }

  String checkPassword(String value){
    if(value.isEmpty){
      return "enter password";
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Form(
      key: key,
      child: Column(
        children: [
          TextFormField(
            decoration: InputDecoration(
              labelText: "userName"
            ),
            onSaved: (value){
              userName = value;
            },
            validator: checkPhone,
            autovalidate: auto,
          ),
          TextFormField(
            decoration: InputDecoration(
                labelText: "passWord"
            ),
            onSaved: (value){
              passWord = value;
            },
            validator: checkPassword,
            autovalidate: auto,
          ),
          Container(
            margin: EdgeInsets.all(20),
            width: double.infinity,
            child: RaisedButton(
              color: Theme.of(context).primaryColor,
              child: Text("提交"),
              onPressed: save,
            ),
          )
        ],
      ),
    );
  }
}

你可能感兴趣的:(Flutter入门 - 表单)