I am trying to refactor some repeated code to make it easier to update. The first obvious candidate is my project’s repeated use of the scaffold appBar property, which is identical (or nearly so) in two dozen locations. So, I’d like to turn the appBar into a widget where I can just write appBar: FbAppBar(title: 'Fonts'),
instead of 5 or 6 lines of code in 24 different files.
Here was my first attempt:
class FbAppBar extends StatelessWidget implements PreferredSizeWidget {
FbAppBar({
required String title,
super.key,
});
late String title;
@override
Widget build(BuildContext context) {
return AppBar(
systemOverlayStyle: SystemUiOverlayStyle.dark,
foregroundColor: Colors.grey[800],
backgroundColor: Colors.transparent,
elevation: 0,
title: Text(
title.hardcoded,
style: Theme.of(context).textTheme.titleLarge,
),
actions: [],
);
}
@override
Size get preferredSize => Size.fromHeight(kToolbarHeight);
}
This ^^ got me a "LateInitializationError" on the title variable. So, I revised it to this:
class FbAppBar extends StatelessWidget implements PreferredSizeWidget {
FbAppBar({
required String title,
super.key,
});
String? title;
@override
Widget build(BuildContext context) {
return AppBar(
systemOverlayStyle: SystemUiOverlayStyle.dark,
foregroundColor: Colors.grey[800],
backgroundColor: Colors.transparent,
elevation: 0,
title: Text(
title!.hardcoded,
style: Theme.of(context).textTheme.titleLarge,
),
actions: [],
);
}
@override
Size get preferredSize => Size.fromHeight(kToolbarHeight);
}
This ^^ got me a "Null check used on a null value" error.
Clearly I’m missing something (hopefully simple). The title won’t be null (in practice) since I’m passing a string from the calling code (i.e. appBar: FbAppBar(title: 'Fonts'),
), but I don’t understand why that isn’t working here.
2
Answers
You are missing assignment part (i.e.
this
) to assign thetitle
property, so it should be like:Likely there’s a point in your app state where the title property is null. Additionally,
String
doesn’t have getterhardcoded
unless you have a custom extension created for that.You can change your
FbAppBar
to the one below.