1

我正在尝试创建一个可以通过各种参数初始化的 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必需的,但我需要其中至少一个存在。什么是解决这个问题的好方法?

4

2 回答 2

2

您可以将构造函数声明为这些中的任何一个


  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');
  
于 2021-06-08T11:31:18.883 回答
2
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),
    );
  }
}
于 2021-06-08T11:42:07.203 回答