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

Viewed 86

the argument type 'widget' can't be assegned to the parameter type '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,
  );
}
3 Answers

An AppBar implements PreferredSizeWidget and Scaffold expect the appBar property to be of type PreferredSizeWidget

Simply do:

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

While the AppBar is a Widget, the Scaffold needs a PreferredSizeWidget to work. Well, an AppBar does implement PreferredSizeWidget, but your method hides that fact. Since you know it's an AppBar, there is no point in generalizing it, just make your function return that type:

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

Change your myAppBar function type then it will work.

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