How to update hook value from another widget - Flutter

177 views Asked by At

I'm facing an issue with a HookWidget and a StatelessWidget in a Flutter app. I'm passing values from both hooks to the stateless widget. The problem I'm encountering is that the value of useTextEditingController (controller) does not update as expected.

here is an example :

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CustomHookWidget(),
    );
  }
}

class CustomHookWidget extends HookWidget {
  const CustomHookWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    final controller = useTextEditingController();
    final customHook = useState(0);

    return Scaffold(
      body: Column(
        children: [
          TextField(
            controller: controller,
          ),
          TheStatelessWidget(
            hook: customHook,
            text: controller.text,
          ),
        ],
      ),
    );
  }
}

class TheStatelessWidget extends HookWidget {
  final ValueNotifier<int> hook;
  final String text;

  const TheStatelessWidget({
    Key? key,
    required this.hook,
    required this.text,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        if (text.isEmpty) {
          print('empty');
          print(text);
        } else {
          hook.value += 1;
        }
      },
      child: Text('Change Value'),
    );
  }
}

1

There are 1 answers

0
Md. Yeasin Sheikh On BEST ANSWER

The initial TextEditingController's text is empty, that's why you are getting empty string all the time. You can pass the controller instead to get updated value.

class CustomHookWidget extends HookWidget {
  const CustomHookWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final controller = useTextEditingController();
    final customHook = useState(0);
  

    return Scaffold(
      body: Column(
        children: [
          TextField(
            controller: controller,
          ),
          Text('Value: ${customHook.value}'),
          TheStatelessWidget(
            hook: customHook,
            controller: controller,
          ),
        ],
      ),
    );
  }
}

class TheStatelessWidget extends HookWidget {
  final ValueNotifier<int> hook;
  final TextEditingController controller;

  const TheStatelessWidget({
    Key? key,
    required this.hook,
    required this.controller,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        if (controller.text.isEmpty) {
          print('empty');
          print(controller.text);
        } else {
          hook.value += 1;
        }
      },
      child: Text('Change Value'),
    );
  }
}