Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compile time const methods in Flutter

Is there a way to create compile-time methods in Dart/Flutter? I want to create a helper method to return DataTable headers. The old code looks as follows:

DataTable(
  columns: const [
    DataColumn(label: Row(children: [Icon(Icons.foo1), Text('Bar 1')])),
    DataColumn(label: Row(children: [Icon(Icons.foo2), Text('Bar 2')])),
    DataColumn(label: Row(children: [Icon(Icons.foo3), Text('Bar 3')])),
    DataColumn(label: Row(children: [Icon(Icons.foo4), Text('Bar 4')])),
  ],
  // ...

To make the code more readable and uniform, I created a helper method:

static Row _generateTableHeader(IconData icon, String text) {
  return Row(children: [Icon(icon), Text(text)],);
}

I now lost the ability to declare the columns array as const. Is there a way to declare the _generateTableHeader method as a compile-time method so that I can still use the constant declaration of the coluns array and still profit from that performance boost?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Or should I create a StatelessWidget instead? Or a class inheriting from Row?

>Solution :

Yes, you should create a StatelessWidget instead. This way, you can take advantage of using the const constructor, and the widget is now reusable. See this answer to learn more about why classes are preferred over functions to make reusable widget-tree.

class TableHeader extends StatelessWidget {
  const TableHeader(this.icon, this.text, {super.key});

  final IconData icon;
  final String text;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [Icon(icon), Text(text)],
    );
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading