Search code examples
flutterdartflutter-layoutflutter-appbar

Not able to include a widget in the scaffold due to missing preferred size constraint?


Getting the following error when implementing my appbar with Flutter. I can include it elsewhere in the children array of the body Stack, just not with the appBar: under Scaffold.

The argument type 'Widget' can't be assigned to the parameter type 'PreferredSizeWidget?'.

I can add the Widget like this and it works, but not like this and I'm trying to figure out why I can't include my appbar() widget in this manner.

This works ok

class _MainPageState extends State<MainPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Welcome"),
        centerTitle: true,
        backgroundColor: Colors.transparent,
        elevation: 0.0,
      ),
      body: Stack(
        children: <Widget>[

This does not, though by rights it should as it is merely returning the AppBar when called. Wrapping it in a PreferredSize() like so also does not work.

This doesn't work

Widget appBar() {
  return PreferredSize(
        preferredSize: const Size.fromHeight(100),
        child: Container(color: Colors.transparent, child: AppBar(
    title: const Text("Welcome"),
    centerTitle: true,
    backgroundColor: Colors.transparent,
    elevation: 0.0,
  )));
}

This doesn't work

Widget appBar() {
  return AppBar(
    title: const Text("Welcome"),
    centerTitle: true,
    backgroundColor: Colors.transparent,
    elevation: 0.0,
  );
}

Including appBar() below in the Scaffold

class _MainPageState extends State<MainPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar(),
      body: Stack(
        children: <Widget>[

Solution

  • Replace the return type widget to PreferredSize.

      PreferredSize appBar() {
        return PreferredSize(
            preferredSize: const Size.fromHeight(100),
            child: Container(
                color: Colors.transparent,
                child: AppBar(
                  title: const Text("Welcome"),
                  centerTitle: true,
                  backgroundColor: Colors.transparent,
                  elevation: 0.0,
                )));
      }
    

    Also, can be done like appBar: appBar() as PreferredSize but better to do change return type,