Reputation: 33
I've created a class named 'Session' and its provider class 'SessionProvider', in which I've declared and initialize an object named 'currentSession'. But don't know why I can't access currentSession's arguments e.g. name, id anywhere in the tree (just get null on calling them), although I've defined the SessionProvider in the main-class as an ancestor.
Here is my code:
class Session {
int id;
String name;
Session({int id, String name});
}
class SessionProvider with ChangeNotifier {
Session _dummy_currentSession = Session(id: 1, name: 'Spring-16');
Session get currentSession {
return _dummy_currentSession;
}
}
Main Class:
void main(List<String> args) {
// debugPaintSizeEnabled = true;
runApp(MyApp());
}
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
return LayoutBuilder(
builder: (context, constraints) =>
OrientationBuilder(builder: (context, orientation) {
SizeConfig().init(constraints, orientation);
return MultiProvider(
providers: [
ChangeNotifierProvider.value(
value: SessionProvider(),
),
],
child: MaterialApp(
home: LoginPage(),
theme: AppTheme.lightTheme,
),
);
}),
);
}
}
In a screen, where I want to access it:
final sessionTest = Provider.of<SessionProvider>(context, listen: false).currentSession;
print(' session: '+ sessionTest.name);
And here is the error message I get:
Upvotes: 0
Views: 57
Reputation: 750
because sessionTest.name is returning null in print(' session: '+ sessionTest.name);
, the source of the error is in Session class, it should be:
class Session {
int id;
String name;
Session({this.id, this.name}); // <--
}
Upvotes: 1