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>[
CodePudding user response:
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,
CodePudding user response:
The issue is in the return type. appBar in scaffold will require a PreferredSize widget.. You can mark the return like this
AppBar appBar() {
return AppBar(
title: const Text("Welcome"),
centerTitle: true,
backgroundColor: Colors.transparent,
elevation: 0.0,
);
}