I tried to create a form using Flutter. However, after I declared a crazy variable, I was unable to input into the TextFormField. I have had similar experiences in React, but I do not know the best solution. I need crazy and TextFormField.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(
home: MyHomePage(),
));
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State createState() => MyHomePageState();
}
class MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
final formKey = GlobalKey<MyHomePageState>();
var crazy = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
toolbarHeight: 100,
),
body: SingleChildScrollView(
child: Form(
key: formKey,
child: TextFormField(
decoration: const InputDecoration(
labelText: 'Why I can not input?',
),
),
),
),
);
}
}
3
Answers
That’s because you defined your
formKey
in thebuild
method. So when the keyboard starts opening, thebuild
method gets extecuted again which recreates newformKey
again and resets the wholeForm
state to initial. The solution is to initialize theformKey
in state class and not in thebuild
method.You have declared the
formKey
inside the build method. So, whenever you click on the input field, the build method will be rerun, and a newformKey
will be assigned, causing the form to lose its state. You can fix this by declaring the variable outside of the build method.Pull out the
formKey
outside of thebuild
method