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

Issue

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?

Solution

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

Answered By – VasilKanev

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *