Vihanga Randunu
Vihanga Randunu

Reputation: 421

The element type 'Widget?' can't be assigned to the list type 'Widget' - Flutter error

I am implementing a custom app bar and I want to add optional widget to action: [] property in AppBar Widget. But when I insert the widget inside the action widget list I am getting an error which says 👉 The element type 'Widget?' can't be assigned to the list type 'Widget'

summary 👉 I want to create a optional widget to insert inside the action property in AppBar. So I can call that widget in some pages and not in the others

 class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
          final String title;
          final Widget? actionWidget;
        
          const CustomAppBar({
            Key? key,
            required this.title,
            this.actionWidget,
          }) : super(key: key);
        
          @override
          Size get preferredSize => const Size.fromHeight(60);
        
          @override
          Widget build(BuildContext context) {
            return AppBar(
              actions: [actionWidget],
              leading: IosBackArrow(),
              backgroundColor: Colors.transparent,
              elevation: 0.0,
              centerTitle: true,
              title: Text(
                title,
                style: const TextStyle(fontFamily: 'bangers', fontSize: 22),
              ),
              flexibleSpace: Container(
                decoration: const BoxDecoration(
                    color: Colors.black,
                    borderRadius: BorderRadius.only(bottomRight: Radius.circular(50))),
              ),
            );
          }

    }

Upvotes: 1

Views: 3151

Answers (1)

Wilson Toribio
Wilson Toribio

Reputation: 1126

You should do this, add the ?? to actionWidget so if it comes null you will have an empty SizedBox in it and wont show anything:

class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
  final String title;
  final Widget? actionWidget;

  const CustomAppBar({
    Key? key,
    required this.title,
    this.actionWidget,
  }) : super(key: key);

  @override
  Size get preferredSize => const Size.fromHeight(60);

  @override
  Widget build(BuildContext context) {
    return AppBar(
      actions: [actionWidget ?? const SizedBox()], // add this line, then it will be optional
      leading: IosBackArrow(),   
      backgroundColor: Colors.transparent,
      elevation: 0.0,
      centerTitle: true,
      title: Text(
        title,
        style: const TextStyle(fontFamily: 'bangers', fontSize: 22),
      ),
      flexibleSpace: Container(
        decoration: const BoxDecoration(
            color: Colors.black,
            borderRadius: BorderRadius.only(bottomRight: Radius.circular(50))),
      ),
    );
  }

}

Upvotes: 3

Related Questions