问题
At the picture i tried to display:
- 1-1 - how looks error.
2-2 - how I solved it.
But it only works by pressing both button (at first DELETE and then RANDOM)
It will be better to make only one action, but I havent done it.
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();
});
}),
],
),
),
);
回答1:
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();
});
},
来源:https://stackoverflow.com/questions/58167577/how-to-insert-two-action-at-one-button-onpress-delete-widget-and-create-it-by