Reputation: 3600
In the flutter_platform_widgets package, the following declaration appears:
final PlatformAppBar Function(BuildContext context, int index)? appBarBuilder;
I'm sorry for the beginner question, but I am confused by this syntax. I understand the final
and the name of the instance is appBarBuilder
.
I am used to seeing a declaration like:
final Classname? classInstance;
Where in this declaration, the classInstance
can also be null
.
But it seems to see this declaration has two types: PlatformAppBar
and Function(BuildContext context, int index)?
. I don't think something can have two different types, so what is going on here?
My final goal is to pass a null
function.
Here is how I am using it. Some of the pages need an app bar and others do not, which is why I am trying to return a null for some pages.
return PlatformTabScaffold(
appBarBuilder: (context, index) {
if (index == 1) return SearchPage.appBar(context);
if (index == 3) return CalculatorPage.appBar(context);
return null; // Gives error The return type 'Null' isn't a 'PlatformAppBar', as required by the closure's context.
},
// Other parameters...
);
Upvotes: 0
Views: 239
Reputation: 89965
final PlatformAppBar Function(BuildContext context, int index)? appBarBuilder;
declares a variable named appBarBuilder
of type:
PlatformAppBar Function(BuildContext context, int index)?
appBarBuilder
therefore either is null
or is a function that takes arguments of type BuildContext
and int
and that returns a PlatformAppBar
.
Here is how I am using it. Some of the pages need an app bar and others do not, which is why I am trying to return a null for some pages.
return PlatformTabScaffold( appBarBuilder: (context, index) { if (index == 1) return SearchPage.appBar(context); if (index == 3) return CalculatorPage.appBar(context); return null; // Gives error The return type 'Null' isn't a 'PlatformAppBar', as required by the closure's context. }, // Other parameters... );
Your code is not passing null
to appBarBuilder
. You are passing an anonymous function that returns null
when invoked. Consider:
int Function()? f = null;
int? Function()? g = () => null;
print(f == null); // Prints: true
print(g == null); // Prints: false
print(g() == null); // Prints: true
f(); // Throws a runtime exception.
In your case, it does not seem to me that you actually want appBarBuilder
itself to be null
; you instead want invoking it to conditionally do nothing based on index
.
I'm not familiar with package:flutter_platform_widgets
, but I suspect that there might not be a way to do what you want. You probably should contact the package author and ask if there's a preferred way to make the callback do nothing, and if not, perhaps change the declaration of appBarBuilder
to PlatformAppBar? Function(BuildContext context, int index)?
instead so that it allows a null
return value.
Upvotes: 1