One option is to create & use an InheritedWidget
-style accessor for your State
class and then you can access it from any descendant context
.
import 'package:flutter/material.dart';
class InheritedWidgetPage extends StatefulWidget {
@override
_InheritedWidgetPageState createState() => _InheritedWidgetPageState();
static _InheritedWidgetPageState of(BuildContext context) =>
context.findAncestorStateOfType<_InheritedWidgetPageState>();
}
class _InheritedWidgetPageState extends State<InheritedWidgetPage> {
List<String> plans = ['Plan A', 'Plan B'];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
_InheritedWidgetPageState _state = InheritedWidgetPage.of(context);
return Scaffold(
appBar: AppBar(
title: Text(_state.plans[0]),
),
body: Center(
child: ElevatedButton(
child: Text('Goto ${_state.plans[1]}'),
onPressed: () => Navigator.of(context).push(
MaterialPageRoute(builder: (context) => PlanPage(1))),
),
),
);
}
}
class PlanPage extends StatelessWidget {
final int index;
PlanPage(this.index);
@override
Widget build(BuildContext context) {
_InheritedWidgetPageState _state = InheritedWidgetPage.of(context);
return Scaffold(
appBar: AppBar(
title: Text(_state.plans[index]),
),
body: Center(
child: Text('You are here: ${_state.plans[index]}'),
),
);
}
}
This can be pretty confusing to understand at first, but will make more sense as you get more familiar with Flutter's declarative framework.
For the above example to work, you need to have a MaterialApp
ancestor widget, and your State
class (where you're holding your plans
state object) needs to be its parent. I explain why on a similar question here.
Your other option is to use a State Management package of which there are lots, which can help you simplify access to state objects.