Search code examples
flutterdartnullconditional-operator

How to Conditionally Return a Widget Depending if Some Variable is null in Dart/Flutter Using a Fancy Operator?


In Flutter, is there a way to do this:

  Widget build(BuildContext context) {
    if (someVar != null) {
      return WidgetA();
    } else {
      return WidgetB();
    }
  }

In a nice syntactically sugary way?

I could try this:

  Widget build(BuildContext context) {
    return someVar !?? WidgetA() : WidgetB();
  }

... but I know it won't work.


Solution

  • You wrote:

      Widget build(BuildContext context) {
        someVar !?? WidgetA() : WidgetB();
      }
    

    It should be ? and : for the ternary operator. And in case you don't want to show anything, you can use an empty SizedBox.

    So it could be something like:

    Container(
      child: _hasName ? Text(name) : SizedBox(),
    )
    

    Or if you are writing the build method, don't forget to use the return keyword:

      Widget build(BuildContext context) {
        return someVar ? WidgetA() : WidgetB();
      }