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