[英]Dart/Flutter widget with optional parameters but at least one required
I'm trying to create a Flutter widget that can be initialized by various parameters, something like this我正在尝试创建一个可以通过各种参数初始化的 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
}
}
As you can see, neither of id
and username
are required, but I would need that at least one of them present.如您所见,
id
和username
都不是必需的,但我需要至少其中一个存在。 What would be a good way to approach this?什么是解决这个问题的好方法?
You can declare the constructor as anyone of these您可以将构造函数声明为这些中的任何一个
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
And you can also use Assert Statement to check values at runtime have a look您还可以使用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),
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.