1
votes

So imagine I have an app (standard material scaffold) with a drawer, app bar, body etc.

I'm now thinking what is the correct way to implement it, given I essentially don't want any state in the widgets (i.e. I want to keep state (data) in dedicated model/store/controller classes and keep widgets only responsible for UI/pixels).

I could make the top-level, root app widget stateful and then setState((){}) (note the dummy callback, which I'd use just to trigger the rebuild) whenever the controller(s) tell me to. The child widgets would then get rebuilt and would read the values they're interested in from the stores/models/...

I could make the top-level widget stateless and only mark the leafs as stateful.

Given Flutter claims to be optimized for frequent Widget rebuilds, is one option significantly better than the other? I'd bet the leaf approach might be more performant, but it's much more verbose (2x the classes).

1

1 Answers

0
votes

I'm now thinking what is the correct way to implement it, given I essentially don't want any state in the widgets (i.e. I want to keep state (data) in dedicated model/store/controller classes and keep widgets only responsible for UI/pixels).

The correct way to implement it imo is how the flutter team designed the state class to be used. You are injecting a state object into your UI class when you do this:

class HomePage extends StatefulWidget {
    @override
      _HomePageState createState() => new _HomePageState();
}
class _HomePageState extends State<HomePage> {...}

I.e only state data relevant to the widget and/or its direct child widgets are stored in the widget's state.

It's a bad idea (complexity) wise to track state in only 1 (the topmost) widget. Seeing that the framework has a lot of ground to cover when comparing previous to current state on setState() when the state object is big. It seems like a waste to not make use of smaller state objects that change independently. Also, from a maintenance point of view it's easy to get context for what you're looking at when the state object is relevant to only the current widget.

It seems to me that you are fighting the framework, can you elaborate on a specific reason/example why you wouldn't want any state in widgets?