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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

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

Okay