Home > Enterprise >  This is the case for column in my StatelessWidget in Flutter:
This is the case for column in my StatelessWidget in Flutter:

Time:03-25

Flutter

class MyCard extends StatelessWidget {
    Widget ?title;
    Widget ?icon;
    MyCard({Key? key, this.title, this.icon});

    @ override
      Widget build(BuildContext context) {
        return Container(
          child: Card(
            child: Column(
              children: <Widget>[
                title,
                icon
              ],
            ),
          ),
        );
      }
}

I get the following error: A value of type 'Widget?' can't be assigned to a variable of type 'Widget' because 'Widget?' is nullable and 'Widget' isn't.

How can I resolve this issue?

CodePudding user response:

Because your title and icon can be null at runtime but Column() does not allow you to add Widgets in children that are going to be null.

You can add a null check on your title like this title! and the same for icon to icon! or you can give a constant Widget to your title and icon when they comes as null at runtime. Something like this

Column(
  children: <Widget>[
    title ?? const Offstage(),
    icon ?? const Offstage(),
  ],
),
  • Related