Reputation: 77
In this code, I want to be able to access accountID and scopeID of the InheritedWidget class further down the line. To test this, I wrote the following code:
import 'package:flutter/material.dart';
class AdvisorContext extends InheritedWidget {
final int accountId;
final int scopeId;
AdvisorContext({key, this.accountId, this.scopeId, child})
: super(key: key, child: child);
@override
bool updateShouldNotify(AdvisorContext oldWidget) {
return oldWidget.accountId != accountId || oldWidget.scopeId != scopeId;
}
}
class AdvisorListingView extends StatefulWidget {
static AdvisorContext of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType() as AdvisorContext;
const AdvisorListingView({Key key, this.child}) : super(key: key);
final Widget child;
@override
State<StatefulWidget> createState() {
return _AdvisorListingState();
}
}
class _AdvisorListingState extends State<AdvisorListingView> {
int accountId;
int scopeId;
@override
Widget build(BuildContext context) {
return AdvisorContext(
accountId: accountId,
scopeId: scopeId,
child: SafeArea(
child: Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: Color.fromARGB(255, 33, 43, 54),
elevation: 0,
title: Text(
"Chennai",
style: TextStyle(
fontFamily: "Roboto",
fontSize: 16.0,
),
),
),
body: AdvisorBody(),
),
),
);
}
}
class AdvisorBody extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new AdvisorCard();
}
}
class AdvisorCard extends StatelessWidget {
@override
Widget build(BuildContext context) {
final advisorContext = AdvisorContext.of(context);
}
}
I expect that in the AdvisorCard class, I would be able to create the "final advisorContext" variable and then use it to access scopeID and accountID. However, AdvisorContext.of(context) gives the error: "The method 'of' isn't defined for the type AdvisorContext".
How do I get accountID and ScopeID, and when can I assign values to them?
Upvotes: 1
Views: 496
Reputation: 22437
Congratulation! Almost there. Just add below method to your InheritedWidget
:
static AdvisorContext of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<AdvisorContext>();
}
.of(context)
:
The convention is to provide a static
method of on the InheritedWidget
which does the call to BuildContext.dependOnInheritedWidgetOfExactType
. This allows the class to define its own fallback logic in case there isn't a widget in scope. In the example above, the value returned will be null
in that case, but it could also have defaulted to a value.
Please read more here.
Upvotes: 1