无法将元素类型 'Widget?' 分配给列表类型 'Widget' - Flutter 错误

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

我正在实施自定义应用栏,我想将可选的小部件添加到 action: [] 属性 中的 AppBar 小部件。但是当我将小部件插入操作小部件列表中时,我收到一条错误消息 The element type 'Widget?' can't be assigned to the list type 'Widget'

总结我想创建一个可选的小部件以插入 action 属性 in AppBar 中。所以我可以在某些页面中调用该小部件,而不是在其他页面中调用该小部件

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

    }

你应该这样做,添加 ??到 actionWidget,所以如果它为 null,您将在其中有一个空的 SizedBox 并且不会显示任何内容:

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

}