参数类型 'widget' 无法分配给参数类型 'PreferredSizeWidget?'

the argument type 'widget' can't be assegned to the parameter type 'PreferredSizeWidget?'

参数类型'widget'无法赋值给参数类型'PreferredSizeWidget?'

class home_screen extends StatelessWidget {
  const home_screen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: myAppBar(),
    );
  }
}

Widget myAppBar() {
  return AppBar(
    backgroundColor: Colors.red,
    elevation: 0,
  );
}

虽然 AppBar 是一个 Widget,但 Scaffold 需要 PreferredSizeWidget 才能工作。好吧,AppBar 确实实现了 PreferredSizeWidget,但您的方法隐藏了这一事实。由于您知道它是一个 AppBar,因此没有必要对其进行概括,只需将您的函数 return 设为:

AppBar myAppBar() { 
  return AppBar( 
    backgroundColor: Colors.red,
    elevation: 0,
  );
}

AppBar 实现 PreferredSizeWidgetScaffold 期望 appBar 属性 的类型为 PreferredSizeWidget

只需执行:

PreferredSizeWidget myAppBar() {
  return AppBar(
    backgroundColor: Colors.red,
    elevation: 0,
  );
}

更改您的 myAppBar 函数类型,然后它将起作用。

PreferredSizeWidget myAppBar() {
        return AppBar(
          backgroundColor: Colors.red,
          elevation: 0,
        );
      }