Home > Net >  How to move a variable outside build?
How to move a variable outside build?

Time:05-12

How do I move a variable that uses a context outside of the build method so that it is created once?

class _EventListState extends State<EventList> {
  @override
  Widget build(BuildContext context) {
    final eventNotifier = EventInherited.of(context).eventNotifier;
    ...

CodePudding user response:

You can use the late modifier.

class _EventListState extends State<EventList> {
  late final eventNotifier = EventInherited.of(context).eventNotifier;
  @override
  Widget build(BuildContext context) {
    ...

CodePudding user response:

make

eventNotifier

class variable and connect it to the getter function.

class _EventListState extends State<EventList> {
 var? eventNotifier;
@override
  Widget build(BuildContext context) {
    eventNotifier = EventInherited.of(context).eventNotifier;
}

Dynamic get getEventNotifier => this.eventNotifier;

CodePudding user response:

You can use the didChangeDependencies() method. The context is available at that point.

@override
void didChangeDependencies(){
    super.didChangeDependencies();
    final eventNotifier = EventInherited.of(context).eventNotifier;
}

This method will be called again in certain scenarios, so be careful about what you are initializing.

This thread has more information on when it is recalled, but in general it is okay to use for initialing listeners. Understanding Flutter didChangeDependencies mechanics

  • Related