Does an empty const constructor matter?

Viewed 434

This is a follow-up question to

So far from what I've read about const constructors in Dart, it ensures that only one object of the class in question is allocated. In theory, this can save allocation space and execution time. It's even recommended to apply it wherever possible when following Effective Dart design.

Now, say we have a stateless widget Foo:

import 'package:flutter/material.dart';

class Foo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text("Hello world");
  }
}

Without defining an explicit const constructor, this widget cannot be used in a const context. In other words, the following snippet

import 'package:flutter/material.dart';

class Bar extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const Foo();
  }
}

is illegal. But is there even a benefit to adding a const Foo(); to the Foo class if it doesn't (and won't have) any fields in the foreseeable future?

1 Answers

Yes, there is a benefit. You should declare as const if possible.

According to the Flutter doc:

Use const widgets where possible, and provide a const constructor for the widget so that users of the widget can also do so.

The benefits are the same as having a default vs const constructor:

  1. Performance (see)
  2. Your code is consistent and sound
  3. Are used as annotations
  4. Can use in compile switch

You can enable const by default using Lint

Related