If I have this screen contain some widgets :
@override
Widget build(BuildContext context) {
return Column(children :[
TextFieldWidget(),
ClearButton(),
])
}
the textfield widget is stateless widget return textfild with controller called "color".
the ClearButton widget return elevated button, I want when press on ths button the textfield text clear. How can I do that.
CodePudding user response:
you can try this
class CustomApp extends StatelessWidget {
CustomApp({ Key? key }) : super(key: key);
final TextEditingController controller = new TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
CustomTextFieldWiget(controller: controller),
CustomButton(
onPressed: () {
controller.text = "";
},
)
],
),
);
}
}
class CustomButton extends StatelessWidget {
final VoidCallback? onPressed;
const CustomButton({Key? key, this.onPressed}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: onPressed,
child: Text("Button"),
);
}
}
class CustomTextFieldWiget extends StatelessWidget {
final TextEditingController? controller;
const CustomTextFieldWiget({Key? key, this.controller}) : super(key: key);
@override
Widget build(BuildContext context) {
return TextField(
controller: controller,
);
}
}
CodePudding user response:
You can play with it.
class TestWidget extends StatelessWidget {
TestWidget({Key? key}) : super(key: key);
final TextEditingController controller = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
TextFiledWidget(controller: controller),
ClearButton(
callback: () {
controller.clear();
},
)
],
));
}
}
class ClearButton extends StatelessWidget {
const ClearButton({
Key? key,
required this.callback,
}) : super(key: key);
final VoidCallback callback;
@override
Widget build(BuildContext context) {
return ElevatedButton(onPressed: callback, child: Text("clear"));
}
}
class TextFiledWidget extends StatelessWidget {
const TextFiledWidget({
Key? key,
required this.controller,
}) : super(key: key);
// you can also use callback method
final TextEditingController controller;
@override
Widget build(BuildContext context) {
return TextField(
controller: controller,
);
}
}
CodePudding user response:
Try this,
Create a variable
var _controller = TextEditingController();
And your TextField:
TextField(
controller: _controller,
decoration: InputDecoration(
hintText: 'Enter a message',
suffixIcon: IconButton(
onPressed: _controller.clear,
icon: Icon(Icons.clear),
),
),
)
There is an icon
which on press clear the textfield