DEV Community

NoobCoder
NoobCoder

Posted on

Flutter: Avoid Widget Rebuild by Using const Constructor

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

Discussion (0)