Home > Mobile >  How to pass a variable inside the build method to its parent state in Flutter?
How to pass a variable inside the build method to its parent state in Flutter?

Time:10-25

I have a state that looks like this where I call the method _getData inside the initState

class _DataPageState extends State<DataPage> {
  @override
  void initState() {
    super.initState();
    _selectedEvents = ValueNotifier(_getData(value!));
  }

  @override
  void dispose() {
    _selectedEvents.dispose();
    super.dispose();
  }

  List<dynamic> _getData(DateTime value) {
    //trying to access 'events' variable here
    return events[day] ?? [];
  }
 

And my build method looks likes this

@override
  Widget build(BuildContext context) {
    final _source = toResults(data);
    //'events' variable I'm trying to pass
    final events = LinkedHashMap<DateTime, List<dynamic>>(
      equals: isSameDay,
      hashCode: getHashCode,
    )..addAll(_source);
  }

I'm trying to pass the events variable to my _getData method inside the state to be able to run it inside the initState, is there an appropriate way of doing that?

And if not, is there a way of moving the final variable up without having the issue of "Instance member can't be accessed in an initializer" ?

CodePudding user response:

Your build method should be "pure", meaning it should not have side effects, since Flutter can call it whenever it needs to rebuild the widget tree (e.g. if a keyboard appears, if changing to landscape mode, because a parent rebuilds, etc).

In Dart, if you have a variable that will be initialized before it is first used, but cannot be immediately initialized, you can use the late keyword. Perhaps something like this would work:

class MyState extends State<MyWidget> {
  late LinkedHashMap<DateTime, List<dynamic>> _events;  // late means no initializer needed

  @override
  void initState() {
    super.initState();
    final _source = toResults(data);
    _events = LinkedHashMap<DateTime, List<dynamic>>(
      equals: isSameDay,
      hashCode: getHashCode,
    )..addAll(_source);
  }

  // other stuff
  
}

It's not entirely clear where data is coming from, but if it can be passed in from higher up in the tree, you could make it a property on the Widget class and use widget.data to read it safely inside initState()

  • Related