Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to use const in Flutter

const constructors
flutter-const-keyword

Refere here
art-const-and-final-keyword

When we use setState() Flutter calls the build method and rebuilds every widget tree inside it. The best way to avoid this is by using const costructors.

Use const constructors whenever possible when building your own widgets or using Flutter widgets. This helps Flutter to rebuild only widgets that should be updated.

So if you have a StatefulWidget and you are using setState((){}) to update that widget and you have widgets like:

Dart const Keyword
The const keyword is used to make variables immutable. We can make the variables compile-time constant with the help of the const keyword.

Implementation of const Keyword
We can use the const keyword as follows.

Syntax:

// This syntax can be used when the data type is not known
const variable_name
Code:

void main(){
  const ninja_batch = "Computer Science";

  print("Ninja batch: " + ninja_batch);

  // ninja_batch = "Electrical";
  // If we uncomment the above line, it would throw an error
}
Enter fullscreen mode Exit fullscreen mode

Output:

Ninja batch: Computer Science
Dart final Keyword
The final keyword is used to create objects of immutable nature. The key difference between the final and const keyword lies in their usage. The const keyword is a compile-time constant, whereas the final keyword is a run-time constant.

Implementation of Final Keyword
We can use the final keyword as follows.

Syntax:

// This syntax can be used when the data type is not known
final variable_name

// This syntax can be used when the data type is known
final [data_type] variable_name
Code:

// Dart program to demonstrate final keyword

void main(){
  final String ninja_name = "Mr X"; // a variable declared as final
  print("Ninja name: " + ninja_name);

  // ninja_name = "Mr John X";
  // If we uncomment the above statement, this will throw an error
  // As the value of final variables cannot be changed

  final int total_marks = get_total_marks(); // Getting the value of a final variable at runtime

  print("Total marks obtained by the ninja: ${total_marks}");
}
Enter fullscreen mode Exit fullscreen mode

// Demo function, just return the sum of marks in three subjects

int get_total_marks(){
  int PHYSICS = 50;
  int CHEMISTRY = 70;
  int MATHS = 90;
  return PHYSICS + CHEMISTRY + MATHS;
}
Enter fullscreen mode Exit fullscreen mode
class _MyWidgetState extends State<MyWidget> {

  String title = "Title";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Column(
        children: <Widget>[
          const Text("Text 1"),
          const Padding(
            padding: const EdgeInsets.all(8.0),
            child: const Text("Another Text widget"),
          ),
          const Text("Text 3"),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: () {
          setState(() => title = 'New Title');
        },
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

** Where we can use const**

   icon: const Icon(Icons.save),
Enter fullscreen mode Exit fullscreen mode
   label: const Text("Save"),
Enter fullscreen mode Exit fullscreen mode
const Text("Text 1"),
Enter fullscreen mode Exit fullscreen mode
 const Padding(
            padding: const EdgeInsets.all(8.0),
            child: const Text("Another Text widget"),
          ),
Enter fullscreen mode Exit fullscreen mode
 title: const Text("Holidaylandmark"),
Enter fullscreen mode Exit fullscreen mode
   const   Tab(text: "Events" ),
Enter fullscreen mode Exit fullscreen mode
const Center(child: CircularProgressIndicator()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)