Make Function parameter optional in custom widget flutter

前端 未结 3 1285
半阙折子戏
半阙折子戏 2021-02-19 15:56

I try to create some custom widget with some parameter in the constructor. This widget has some optional and required parameter. how can make Function type paramete

相关标签:
3条回答
  • 2021-02-19 16:08

    You can use a default value that does nothing:

    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 = _dummyOnFocusChange})
          : assert(onFocusChange != null), super(key: key);
    
      @override
      _TextInputWithIconState createState() => _TextInputWithIconState();
    
      static dynamic _dummyOnFocusChange(bool val) {}
    }
    

    I created a static named function instead of just a closure as default value, because closures are not const and currently default values need to be const.

    I added the assert(...) to ensure that an error is shown when null is passed explicitly.

    0 讨论(0)
  • 2021-02-19 16:17

    Another option if you don't like named parameters (like me :/) is:

    function_name (argument1, [argument2]) {
       // statements
    }
    

    arguments in brackets are optional.

    source

    0 讨论(0)
  • 2021-02-19 16:21

    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.

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

    and when calling the onFocusChange perform a null check:

    if(this.onFocusChange != null) {
        this.onFocusChange(boolValue)
    }
    

    Have a look at Optional Parameters to understand better.

    Edit: Thank you Jonah Williams to clarification.

    0 讨论(0)
提交回复
热议问题