0

I know curly braces are used for requiring the name of the property during an object's construction, but when I use it around a property name, it makes that property not necessary for the construction of the object.
For example:
At the end of the following code, I created a class called ReusableCard. In the constructor of ReusableCard, when I don't put curly braces around the colour property, my IDE shows errors in the main part of the code where ReusableCard is used, since I have not passed it any values. But when I put the curly braces around colour(as shown below), all the errors are gone. For some reason, the colour property is not a required property anymore. I know that adding '@required' before colour will make this property required, but I would like to know why adding curly braces removes the errors.

import 'package:flutter/material.dart';

class InputPage extends StatefulWidget {
  @override
  _InputPageState createState() => _InputPageState();
}

class _InputPageState extends State<InputPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('BMI CALCULATOR'),
      ),
      body: Column(
        children: [
          Expanded(
            child: Row(
              children: [
                Expanded(
                  child: ReusableCard()   //no error shown even though I have not passed any values.
                Expanded(
                  child: ReusableCard(),  //no error shown
                ),
              ],
            ),
          ),
          Expanded(
            child: Row(
              children: [
                Expanded(child: ReusableCard()),  //no error shown
              ],
            ),
          ),
          Expanded(
            child: Row(
              children: [
                Expanded(
                  child: ReusableCard(),  //no error shown
                ),
                Expanded(
                  child: ReusableCard(),  //no error shown
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class ReusableCard extends StatelessWidget {
  Color colour;
  ReusableCard({this.colour});

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(15.0),
      height: 200.0,
      width: 170.0,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.0),
        color: colour,
      ),
    );
  }
}
rioV8
  • 24,506
  • 3
  • 32
  • 49

2 Answers2

0

Not only does the curly braces make it a named parameter, it also makes it an optional parameter

Ivo
  • 18,659
  • 2
  • 23
  • 35
0

ReusableCard({this.colour}): with curly braces colour is a named parameter.
Named parameters are optional.
If you don't provide a value for colour (like in ReusableCard()), colour is by default null. You don't have to provide a value, that's why your IDE shows no errors.

Norman
  • 2,267
  • 1
  • 11
  • 17