DEV Community


Posted on • Updated on

Flutter: Avoid Widget Rebuild by Using const Constructor

Buy me a Coffee:

As we know that by using the setstate function. Flutter rebuilds the whole UI. Since this is a bad practice and memory intensive.

To Prevent this initialize it with const

// As we Know that stateful Widgets rebuild the whole UI. 
// Which is really bad practice!! 
// To Prevent rebuilding of static components like non changing text 
// Initialize them with const  
// Jump to line 38 
import 'package:flutter/material.dart'; 

void main() => runApp(const MyApp()); 

class MyApp extends StatefulWidget { 
  const MyApp({Key? key}) : super(key: key); 

  _MyState createState() => _MyState(); 

class _MyState extends State<MyApp> { 
  Color _containerColor = Colors.yellow; 

  void changeColor() { 
    setState(() { 
      if (_containerColor == Colors.yellow) { 
        _containerColor =; 
      _containerColor = Colors.yellow; 

  Widget build(BuildContext context) { 
    return MaterialApp( 
        title: 'Flutter Demo', 
        theme: ThemeData( 
        home: Scaffold( 
          // Avoid Widget Rebuild by Using const Constructor 
          appBar: AppBar(title: const Text("A Simple App Stateful Widget")), 
          body: Container(decoration:  BoxDecoration(color: _containerColor)), 
          floatingActionButton: FloatingActionButton( 
            onPressed: changeColor, 
            child: Icon(Icons.add), 
            tooltip: "Book Here", 
Enter fullscreen mode Exit fullscreen mode

See line number 38 here to prevent the Text to be rebuilt. A const was used.

Try It Here

Top comments (0)