简体   繁体   中英

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

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. 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

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),
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM