Dart/Flutter 带有可选参数但至少需要一个参数的小部件

Dart/Flutter widget with optional parameters but at least one required

我正在尝试创建一个可以通过各种参数初始化的 Flutter 小部件,就像这样

class MyWidget extends StatefulWidget {
  final int? id;
  final String? username;

  MyWidget({this.id, this.username});

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

class _MyWidgetState extends State<MyWidget> {

  @override
  void initState() {
    super.initState();
    if (widget.id != null) {
      // init based on id
    } else if (widget.username != null) {
      // init based on username
    } else {
      // this should never happen
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(); // build some widget
  }
}

如您所见,idusername 都不是必需的,但我需要至少其中之一存在。解决这个问题的好方法是什么?

您可以将构造函数声明为以下任何一个


  MyWidget(this.id,{this.username});//ID is required. Usage will be MyWidget(1,usename:'test');
  MyWidget(this.username,{this.id});//username is required Usage will be MyWidget('test',id:1);
  MyWidget({required this.id, this.username}); //id required
  MyWidget({this.id, required this.username});//username required
  MyWidget({requried this.id, required this.username});//both required

您还可以使用Assert Statement在运行时检查值看看

MyWidget({this.id, this.username}):assert(id != null && username != null,'Both parameters cannot be null');
  
class TestWidget extends StatelessWidget {
  final String id;
  final String name;

  const TestWidget.name({this.id, @required this.name});
  const TestWidget.id({@required this.id, this.name});

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text(id ?? name),
    );
  }
}