Flutter : clear textfield from another widget or screen

Issue

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.

Solution

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

Answered By – Yeasin Sheikh

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.