Is there a way to specify function parameters and return value as const in dart?

1.2k Views Asked by At

I wrote an extension function to add SizedBox between every child in Column or Row to add space between child, instead of putting SizedBox between every child, for which I didn't find any other way around.

Column(
   children: [
      // widgets
   ].setSpace(height: 10),
)

Row(
   children: [
      // widgets
   ].setSpace(width: 10),
)

So here List<Widget> setSpace({double? height, double? width}) takes height or width for the SizedBox used between child. But since height and width are not const I cannot use const SizedBox. So is there any way in dart to say that both the parameters and the return type will ALWAYS be cosnt? like const List<Widget> setSpace({const double? height, const double? width}) like C/C++?

3

There are 3 best solutions below

5
il_boga On

I don't think that's possible, mostly because const can be applied only on constructors and fields, not on generic functions. Maybe you can achieve that by creating your own widget that adds the SizedBox in its build method, and create a const constructor.

EDIT: here's a piece of code of mine of a custom widget with a const constructor.

class UnlockPage extends StatefulWidget {
  final String pcData;
  const UnlockPage({Key? key, required this.pcData}) : super(key: key);


  @override
  Widget build(BuildContext context) {
  [...]
  }
}

EDIT 2: here's a piece of code tested in DartPad. I don't think it can get better than this.

class SpacedColumn extends StatelessWidget {
  final double height;
  final List<Widget> children;

  const SpacedColumn({required this.height, required this.children});

  @override
  Widget build(BuildContext context) {
    var actualChildren = <Widget>[];
    for (var child in children) {
      actualChildren.add(child);
      actualChildren.add(SizedBox(height: height));
    }

    return Column(
      children: actualChildren,
    );
  }
}
1
Usama Karim On

In Dart language const doesn't mean the same as in other languages. You should use final if you don't want to change the values later.

0
Alaindeseine On

You can't. As you pass a value this one can be different from one call to others.

Notice that const as not the same signification on Flutter than on other languages.

With Flutter it indicates to the rendering engine that the widget or the method is always the same and that the rendering engine is not obliged to rebuild this Widget when rebuilding the screen.

The keyword that act as const in other languages is final