Home > Mobile >  How a const widget works with its children?
How a const widget works with its children?

Time:09-27

Let's say I have this HomePage widget:

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(),
    );
  }
}

I am able to use a const constructor at the root (MaterialApp widget) because all children do have const constructors too.

If I add the AppBar widget, I will have to remove the const constructor from the root, because AppBar does not have a const constructor.

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp( // no const anymore
      home: Scaffold(
        appBar: AppBar(...),
      ),
    );
  }
}

But why am I able to use the HomePage widget with a const constructor ? See code below:

class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) {
    return const HomePage(); // using a const constructor
  }
}

I thought it would be impossible because of the AppBar child widget.

CodePudding user response:

Because the HomePage class is immutable. The build function implementation doesn't affect it.

The const keyword can be used when the object is immutable. A Compiler allocates the same portion of memory for all objects.

For more info, reference the Using constructors: Dart doc

  • Related