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

Time:07-30

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 ?

CodePudding user response:

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.

CodePudding user response:

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