park
park

Reputation: 11

Why rebuild is called when Flutter TextFiled keyboard comes up?

Hello I am a beginner flutter developer.

What I'm curious about is the part where the build is called a lot when clicking on another TextField Widget after opening the calendar.

From what I searched, I know that when the TextField keyboard comes up, build is called due to the widget size problem.

To solve this, I found out that there is a way to not use MediaQuery in Scaffold Widget, resizeToAvoidBottomInset: false or Widget.

But it still doesn't solve the rebuild problem. The following is the code and screen currently being rebuilt.

I want to know the solution to rebuild as shown in the image when I click the TextField after loading it by clicking the button.

enter image description here

class HomeScreen extends StatelessWidget {
  const HomeScreen({Key? key}) : super(key: key);
  @overide
  Widget build(BuildContext context) {
    print('HomeScreen build');
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: SafeArea(
        child: Center(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: () {
                  showCupertinoDialog(
                    context: context,
                    barrierDismissible: true,
                    builder: (BuildContext context) {
                      return Align(
                        alignment: Alignment.bottomCenter,
                        child: Container(
                          color: Colors.white,
                          height: 300.0,
                          child: CupertinoDatePicker(
                            mode: CupertinoDatePickerMode.date,
                            initialDateTime: DateTime.now(),
                            onDateTimeChanged: (DateTime date) {},
                          ),
                        ),
                      );
                    },
                  );
                },
                child: const Text('calendar button'),
              ),
              const TextField(
                  decoration: InputDecoration(hintText: 'Text Field')),
            ],
          ),
        ),
      ),
    );
  }
}

Upvotes: 1

Views: 245

Answers (1)

BambinoUA
BambinoUA

Reputation: 7100

You should use StatefulWidget instead of StatelessWidget for your HomeScreen. Having HomeScreen you forced it to be redrawn on each outside event as it does not keep state.

Upvotes: 1

Related Questions