Make Function parameter optional in custom widget flutter

Saman picture Saman · Jan 30, 2019 · Viewed 31k times · Source

I try to create some custom widgets with some parameters in the constructor. This widget has some optional and required parameters.

how can make Function type parameter optional in my Widget.

class TextInputWithIcon extends StatefulWidget {
  final String iconPath;
  final String placeHolder;
  final Function(bool) onFocusChange;
  const TextInputWithIcon(
      {Key key,
      @required this.iconPath,
      this.placeHolder = "",
      this.onFocusChange})
      : super(key: key);

  @override
  _TextInputWithIconState createState() => _TextInputWithIconState();
}

class _TextInputWithIconState extends State<TextInputWithIcon> {
@override
  Widget build(BuildContext context) {
    return MY_WIDGET;
   }
}

Answer

Umair M picture Umair M · Jan 30, 2019

Optional parameters can be either positional or named, but not both.

Named parameters are optional by default so you don't have to assign the default value.

If a parameter is optional but can’t be null, provide a default value.

With null safety

class TextInputWithIcon extends StatefulWidget {
  final String iconPath;
  final String placeHolder;
  final Function(bool)? onFocusChange; // nullable and optional
  
  const TextInputWithIcon(
      {Key? key,
      required this.iconPath, // non-nullable and required
      this.placeHolder = "", // non-nullable but optional with a default value
      this.onFocusChange, // nullable and optional
      })
      : super(key: key);

  @override
  _TextInputWithIconState createState() => _TextInputWithIconState();

}

Without null safety

const TextInputWithIcon(
      {Key key,
      @required this.iconPath,
      this.placeHolder = "",
      this.onFocusChange
})
      : super(key: key);

Usage:

void _focusChanged(bool value) {

    // using null-aware operator (for both with and without null safety)
    onFocusChange?.call(value);
    
    // or without null-aware operator 
    
    // with null safety
    if(onFocusChange != null) {
      onFocusChange!(value);
    }

    // without null safety
    if(onFocusChange != null) {
      onFocusChange(value);
    }

  }

Have a look at Optional Parameters to understand better.

Edit: Thank you Jonah Williams to clarification.