Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: spread operator for constructor

In my flutter app, I have widgets like below:

Container(
  decoration: BoxDecoration(
    border: Border.all(
      color: Colors.red,
      width: 2,
      style: BorderStyle.solid,
    ),
  ),
  child: Text('Container 1'),
)
Container(
  decoration: BoxDecoration(
    border: Border(
      top: BorderSide(
        color: Colors.red,
        width: 2,
        style: BorderStyle.solid,
      ),
    ),
  ),
  child: Text('Container 2'),
)

Both use the same properties for their borders. So I was wondering if there's a spread-operator-like way of inserting the same properties for both widgets? Maybe like:

const borderBase = (
  color: Colors.red,
  width: 2,
  style: BorderStyle.solid,
)

Container(
  decoration: BoxDecoration(
    border: Border.all(
      ...borderBase,
    ),
  ),
  child: Text('Container 1'),
)

Container(
  decoration: BoxDecoration(
    border: Border(
      top: BorderSide(
        ...borderBase,
      ),
    ),
  ),
  child: Text('Container 2'),
)
like image 845
Giraldi Avatar asked Mar 07 '19 10:03

Giraldi


2 Answers

There is no such thing.

A spread operator is in development, but it is only for lists, not classes (https://github.com/dart-lang/language/issues/47)

like image 146
Rémi Rousselet Avatar answered Sep 23 '22 23:09

Rémi Rousselet


You can do something like this:

const BorderSide borderBase = BorderSide(
  color: Colors.red,
  width: 2,
  style: BorderStyle.solid,
);

Container(
  decoration: BoxDecoration(
    border: Border.all(
      color: borderBase.color,
      width: borderBase.width,
      style: borderBase.style,
    ),
  ),
  child: Text('Container 1'),
)

Container(
  decoration: BoxDecoration(
    border: Border(
      top: borderBase,
    ),
  ),
  child: Text('Container 2'),
)

Not the best but still some reuse.

like image 25
Daniel P Avatar answered Sep 22 '22 23:09

Daniel P