Is it ok to use const everywhere?

Issue

I heard that const variable will not dispose easily.

So, is it ok to always create widgets as const if it can, even when that widget use only once? Is it consume much memory if there’re many const?

For examples, I create all screen as const.

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: Home.routeName,
      routes: {
        AuthScreen.routeName: (context) => const AuthScreen(),
        Home.routeName: (context) => const Home(),
        OrderScreen.routeName: (context) => const OrderScreen(),
        EmailLoginScreen.routeName:(context) => const EmailLoginScreen(),
      },
    );
  }
}

Solution

Widget tree rebuilds everytime a certain widget changes state. The consequence is that memory will be used a lot and some frames skipped. If you’re sure some widgets don’t need to change, place then as const. This way, they will not be refreshed and speed up the app in the process. As a simple rule, set const all variables, fields, widgets that will not change values once assigned to them.

Answered By – Francis Nduba Numbi

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.