Home > Enterprise >  Is it ok to use const everywhere?
Is it ok to use const everywhere?

Time:03-24

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(),
      },
    );
  }
}

CodePudding user response:

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.

  • Related