-1

I was trying to follow solution 1 in @rmtmckenzie's answer to a similar question (Persisting AppBar Drawer across all Pages Flutter but when I try the following code, I get the error The argument type 'SaneAppBar' can't be assigned to the parameter type 'PreferredSizeWidget?'. Since I can assign a non-nullable member to a nullable member (e.g. String? = String), I don't get what I'm doing wrong. Perhaps this is something you can do with a drawer parameter but not with an appBar parameter? If so, I'd appreciate any pointers to how I should have been able to determine this up front. I'm also wondering if the sample code needs to be modified to work in a null-safety environment?

sane_app_bar.dart:

import 'package:flutter/material.dart';
class SaneAppBar extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return AppBar(
        title: const Text('SANE Finder'),
        centerTitle: true,
      );
  }
}

Used this way by my screen widget:

class _WelcomeScreenState extends State<WelcomeScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: SaneAppBar(),
      body: Padding(...
E_net4
  • 27,810
  • 13
  • 101
  • 139
j-vasil
  • 139
  • 1
  • 9

2 Answers2

2

I believe that your problem has nothing to do with null safety. The appBar within a scaffold only accepts a widget of the type PreferredSizeWidget. You can easily add this behaviour to your widget using the method below.


// See that I have added: 'implements PreferredSizeWidget'.
class SaneAppBar extends StatelessWidget implements PreferredSizeWidget {

  // You also need to override the preferredSize attribute. 
  // You can set it to kToolbarHeight to get the default appBar height.
  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);

  @override
  Widget build(BuildContext context) {
    return AppBar(
      title: const Text('SANE Finder'),
      centerTitle: true,
    );
  }
}

Now, your widget should be accepted as a Scaffold's appBar.

1

Did you try setting it as a variable?

AppBar myAppBar = Appbar(...)

or as a return function if you need to pass title as an argument

AppBar myAppBar(String title){
    return AppBar(...)
 }

if you still want to use a stateful or stateless widget you need to add with PreferredSizeWidget to the class, but you will need to override one thing :

class SaneAppBar extends StatelessWidget with PreferredSizeWidget{
     @override         
     Size get preferredSize => Size(screen.width, 75); 
}
Khalil Ktiri
  • 181
  • 1
  • 6