skip to Main Content

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?

2

Answers


  1. 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)],
        );
      }
    }
    
    Login or Signup to reply.
  2. Q: Is there a way to create compile-time methods in Dart/Flutter?
    A: No, but a reference to static method (closure) can be used as a constant value.

    Q: Is there a way to create methods that return compile-time constant value?
    A: No. Outside the method, value will not be considered const and cannot be used as a constant in assignment expressions.

    Q: Is there a way to create compile-time constant values inside a method body from arguments passed as constant values?
    A: No. There is no way to declare this in the method parameter declaration.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search