flutterdarttextformfieldflutter-textformfield

Rebuilding issue when I declare MediaQuery within the build function


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(),
],
),
);
}
}
  1. Create a normal stateless widget.
  2. Write MediaQuery within the build function.
  3. The MediaQuery is final Size size = MediaQuery.of(context).size;
  4. Write a log within the build function log('Build function called');.
  5. Write a column on the body of the Scaffold.
  6. Set mainAxisAlignment to center.
  7. Create a textformfiled.
  8. 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.


Solution

  • From Flutter 3.10 and above,

    Replace:

    final size = MediaQuery.of(context).size;
    

    with

    final size = MediaQuery.SizeOf(context);
    

    By calling MediaQuery.of(context).size, the widget will rebuild when any of the MediaQuery properties change (less performant). By calling MediaQuery.sizeOf(context) the widget will rebuild only when the property changes, avoiding unnecessary rebuilds.

    For more insight, see this issue where it is well explained.