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