fluttertexteditflutter-web

How to insert two action at one button OnPress - delete widget and create it by new?


At the picture i tried to display:

It will be better to make only one action, but I havent done it.

in short

and i trying to insert code to delete widget and create it by new at one button action. But its not working. I cannt understand why and how to make it work?

code: https://github.com/develop86229/editTextControl

          FlatButton(
           child: Text("RANDOM"),
                onPressed: () {
                  setState(() {
                    textWidget = Container();
                    textWidget = Form(
                        key: _textKey,
                        child: TextFormField(
                          controller: myTextController,
                        ));
                   myTextController.text = rnd.nextInt(1000000000).toString();
                  });
                  
 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            textWidget,
            FlatButton(
                child: Text("RANDOM"),
                onPressed: () {
                  setState(() {
                    textWidget = Container();
                    textWidget = Form(
                        key: _textKey,
                        child: TextFormField(
                          controller: myTextController,
                        ));
                  });
                  myTextController.text = rnd.nextInt(1000000000).toString();
                }),
            FlatButton(
                child: Text("DELETE"),
                onPressed: () {
                  setState(() {
                    textWidget = Container();
                  });
                }),
          ],
        ),
      ),
    );

Solution

  • This happens because you set a new value in the state, then set another value in it and only then the update happens. This is working as expected.

    However, if you want to delete the item first and only then create a new one, you can delay the second action like this:

                onPressed: () {
                  setState(() {
                    textWidget = Container();
                  });
    
                  Future.delayed(const Duration(milliseconds: 500), () {
                    setState(() {
                        textWidget = Form(
                            key: _textKey,
                            child: TextFormField(
                              controller: myTextController,
                            ));
                    });
                    myTextController.text = rnd.nextInt(1000000000).toString();
                  });
                },