0

I've watched Pragmatic state management video from google io19, about package:provider/provider.dart and its way to manage state. It looks pretty simple, but I have question about getting access to state in class's methods.

Say somewhere in class I need to update state:

_onTap(data) {
    appState.data = data;
}

In class's build method I'm getting state:

this._appState = Provider.of<AppState>(context);

Now I need setter, so I'm doing:

set _appState(newValue) {
   appState = newValue;
}

And in the end I need state field in my class:

class Tapable extends StatelessWidget {
  var appState;

  _onTap(data) {
    appState.data = data;
  }

  set _appState(newValue) {
    appState = newValue;
  }

  @override
  Widget build(BuildContext context) {
    this._appState = Provider.of<AppState>(context);
    return SomeWidget(
       onTap: () { _onTap(data) }
    )
  }
}

Surprisingly it works, but this code smells for me, so I doubt that this is the correct way.

Thanks.

ivanesi
  • 1,603
  • 2
  • 15
  • 26

1 Answers1

0

If you have state, such that changing state should update your widget, you should use a StatefulWidget, and use setState() to trigger the rebuild. StatelessWidget is for widgets that are essentially "view only".

Randal Schwartz
  • 39,428
  • 4
  • 43
  • 70