Flutter-TextField验证无效

时间:2020-02-06 21:03:34

标签: flutter dart

我需要做的是在调用onPressed时,当我不输入文本时出现Textfield错误。

<html>
    <head>
        <title></title>
        <script>
            function showText(){
                var inputs = document.getElementsByTagName('input');
                var box = document.getElementById('show');
                box.value = '';
                for(var i=0; i<inputs.length; i++){
                    box.value += inputs[i].name + ': '+inputs[i].value+'\n';
                }
            }
        </script>
    </head>
    <body>
        <b>Clicking Submit with gather the information above and copy to the box below. </b><br>
        <input type="text" name="test" value="lorem ipsum">
        <button type="button" onClick="showText();">Submit</button><br>
        <p>Show:</p>
        <p><textarea cols=50 rows=10 id="show"></textarea></p>
    </body>
</html>

enter image description here

但是,使用该代码对我来说不起作用。整个课程都附在这里

code 谢谢!

1 个答案:

答案 0 :(得分:1)

您的代码正确,但是您无法在ShowDialog Widget中更新状态,因此您必须在ShowDialog中返回Statetful Widget。

我添加了我更改的整个代码。

import 'package:flutter/material.dart';

class Consts {
  Consts._();

  static const double padding = 16.0;
  static const double buttonPadding = 5.0;
}

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

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

class _DeleteWidgetState extends State<DeleteWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blueAccent,
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          showDialogNameList();
        },
        backgroundColor: Colors.orange,
        child: Icon(
          Icons.add,
          color: Colors.purple,
          size: 40,
        ),
      ),
    );
  }

  showDialogNameList() {
    return showDialog(
        context: context,
        builder: (context) {
          return CustomeDialog1();
        });
  }
}

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

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

class _CustomeDialog1State extends State<CustomeDialog1> {
  FocusNode focusNode = FocusNode();
  final textController = TextEditingController();
  bool noText = false;
  String nameList = "";

  @override
  void initState() {
    super.initState();
    nameList = "";
    focusNode.addListener(() {
      if (!focusNode.hasFocus) {
        setState(() {
          noText = nameList.length == 0;
        });
        FocusScope.of(context).requestFocus(focusNode);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    var screenHeight = MediaQuery.of(context).size.height;

    return Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(Consts.padding),
        ),
        elevation: 0.0,
        child: Container(
          height: screenHeight / 3,
          child: Stack(
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(
                  top: Consts.padding,
                  bottom: Consts.padding,
                  left: Consts.padding,
                  right: Consts.padding,
                ),
                margin: EdgeInsets.only(top: 0),
                decoration: BoxDecoration(
                  color: Colors.white,
                  shape: BoxShape.rectangle,
                  borderRadius: BorderRadius.circular(Consts.padding),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black26,
                      blurRadius: 10.0,
                      offset: const Offset(0.0, 10.0),
                    ),
                  ],
                ),
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: <Widget>[
                      TextField(
                        focusNode: focusNode,
                        autofocus: true,
                        controller: textController,
                        cursorColor: Colors.white,
                        style: TextStyle(color: Colors.black, fontSize: 14),
                        decoration: InputDecoration(
                          counterText: '',
                          errorText: noText ? 'Value Can\'t Be Empty' : null,
                          hintText: 'List Name',
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.black),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: Colors.green),
                          ),
                          labelStyle: TextStyle(
                              color: Colors.white, fontWeight: FontWeight.bold),
                        ),
                        onChanged: (String text) {
                          nameList = text;
                        },
                      ),
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Container(
                              width: 150.0,
                              height: 45.0,
                              child: RaisedButton(
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(10),
                                ),
                                onPressed: () {
                                  setState(() {
                                    nameList.isEmpty
                                        ? noText = true
                                        : noText = false;
                                  });
                                },
                                padding:
                                    EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
                                color: Color(0xFF2DA771),
                                child: Text('Add',
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontFamily: 'Roboto',
                                        fontSize: 16)),
                              ),
                            ),
                          ],
                        ),
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        ));
  }
}