Cristian F. Bustos
Cristian F. Bustos

Reputation: 503

Flutter - TextField validation don't works

What I need to do is when the onPressed is called, I get the Textfield error when I don't enter text.

class _ExampleDialogTextState extends State<ExampleDialogText> {
  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);
      }
    });
  }

TextField(
focusNode: focusNode,
autofocus: true,
controller: textController,
style: TextStyle(
color: Colors.black, fontSize: 14),
decoration: InputDecoration(
counterText: '',
errorText:
noText ? 'Value Can\'t Be Empty' : null,)

RaisedButton(
onPressed: () {
setState(() {
nameList.isEmpty
? noText = true
: noText = false;
});
},)

}

enter image description here

But still, with that code it doesn't work for me. Attached here is the entire class

code Thank you!

Upvotes: 0

Views: 77

Answers (1)

Viren V Varasadiya
Viren V Varasadiya

Reputation: 27207

Your Code is correct but you can not update state in ShowDialog Widget, so you have to return Statetful Widget in ShowDialog.

I added whole code which i change.

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)),
                              ),
                            ),
                          ],
                        ),
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        ));
  }
}

Upvotes: 1

Related Questions