Search code examples
flutterdart-null-safety

The argument type 'Widget' can't be assigned to the parameter type 'PreferredSizeWidget?' in null safety


Scaffold(
  appBar: _buildAppBar(),
)

Here's the function:

Widget _buildAppBar() => AppBar(); // Error

This code was working fine until I migrated my code to null safety.


Solution

  • Dart null safety doesn't allow downcasting, so you can't assign a Widget to PreferredSizeWidget just like you can't assign an Object to a String (which was possible before null safety).

    You should change your function and return AppBar or PreferredSizeWidget from it.

    AppBar _buildAppBar() => AppBar();
    

    or

    PreferredSizeWidget _buildAppBar() => AppBar();