DEV Community

NoobCoder
NoobCoder

Posted on • Edited on

3 1

Flutter: Avoid Widget Rebuild by Using const Constructor

Buy me a Coffee: https://www.buymeacoffee.com/noobcoders

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); 

  @override 
  _MyState createState() => _MyState(); 
} 

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

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

  @override 
  Widget build(BuildContext context) { 
    return MaterialApp( 
        title: 'Flutter Demo', 
        theme: ThemeData( 
          primarySwatch: Colors.blue, 
        ), 
        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

Neon image

Build better on Postgres with AI-Assisted Development Practices

Compare top AI coding tools like Cursor and Windsurf with Neon's database integration. Generate synthetic data and manage databases with natural language.

Read more →

Top comments (0)

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay