[英]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
}
}
如您所見, id
和username
都不是必需的,但我需要至少其中一個存在。 什么是解決這個問題的好方法?
您可以將構造函數聲明為這些中的任何一個
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),
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.