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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay