import 'package:bug_fix/home_screen.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@OverRide
Widget build(BuildContext context) {
return const MaterialApp(
home: HomeScreen(),
);
}
}
import 'dart:developer';
import 'package:flutter/material.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@OverRide
Widget build(BuildContext context) {
log('Building home screen');
// Variable to find the size of the device screen.
final Size size = MediaQuery.of(context).size;
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextFormField(),
],
),
);
}
}
- Create a normal stateless widget.
- Write MediaQuery within the build function.
- The MediaQuery is final Size size = MediaQuery.of(context).size;
- Write a log within the build function log(‘Build function called’);.
- Write a column on the body of the Scaffold.
- Set mainAxisAlignment to center.
- Create a textformfiled.
- Open/ Focus the textformfiled then the build function will rebuild multiple times.
I understood that it is because, of a change in the size of the device screen when I open the textformfiled.
2
Answers
The issue you’re experiencing, where the build function of your widget is being called multiple times when you open/focus the
TextFormField
, is expected behavior in Flutter. The build method is called whenever the widget needs to be rebuilt, which can happen for various reasons, including changes in the widget’s state or changes in the widget tree.In your case, when you open/focus the
TextFormField
, it might trigger a rebuild of its parent widget because the size of the device screen may change when the keyboard is displayed. This is why you see the "Building home screen" log message multiple times.If you want to avoid unnecessary rebuilds of the HomeScreen widget, you can consider using a StatefulWidget and managing the widget’s state. By doing this, you can control when the rebuild should occur.
Here is a possible solve of it:
By using a StatefulWidget, the build method will only be called when you explicitly call setState, allowing you to control when you want the widget to rebuild.
There are few issues to fix:
The
@OverRide
annotations are incorrect. They should be@override
(with a lowercase ‘o’).While debugging it should show the error???
The
super.key
in the constructor parameters is not needed. You can remove it.You have a
typo
in the MyApp class constructor. Instead ofconst MyApp({super.key});
, it should beconst MyApp({Key? key}) : super(key: key);
.