Reputation: 1697
I have a statefulwidget, a custom FlowState class to keep track of data across multiple widget views, a custom Job model that lives in the FlowState and is accessed in these widget views.
I am using Provider to get the FlowState instance, and from there get the job instance. I can access the FlowState instance in the widget build function because I have the context available:
@override
Widget build(BuildContext context) {
Job job = Provider.of<FlowState>(context).job as Job;
But I would like to avoid this, because I have a lot of logic (async http calls for example) that needs to be done when the job is retrieved, and this should only be done once, and not everytime the widget is rebuilt (when setState() is called).
So instead of getting the FlowState/job inside the Widget, I can get it in the initState() method in the State with a 'sad' future hack:
class WidgetTest extends StatefulWidget {
const WidgetTest({Key? key}) : super(key: key);
@override
State<WidgetTest> createState() => _WidgetTestState();
}
class _WidgetTestState extends State<WidgetTest> {
Job? job;
@override
void initState() {
Future.delayed(Duration.zero, () {
job = Provider.of<FlowState>(context, listen: false).job as Job;
functionThatUsesJobToGatherOtherData();
});
super.initState();
}
functionThatUsesJobToGatherOtherData() {
print('Gathering data from job properties so it can be used in the widget tree');
setState(() {});
}
@override
Widget build(BuildContext context) {
return Column(children: [
Text('I would like to avoid a null test here: ' + job!.id.toString()),
]);
}
}
The problem with this approach is that I use the nullable job instance in the widget tree alot. And because the widget tree is built before the future returns, I have to check if the job instance is null many many times in the tree which I would like to avoid. I could initialize the job instance with an empty job (this would cause other problems). Or maybe a FutureBuilder would work? - But is this really necessary, or is there a simpler solution for this kind of problem?
Upvotes: 0
Views: 194
Reputation: 178
I don't have sure if I have a clear understanding of your question therefore can you fetch the FlowState
after initializing the build method no?
For example:
WidgetsBinding.instance.endOfFrame.then(
(_) async {
// do something
},
);
Upvotes: 0