How do you create Services/Providers in Flutter?

核能气质少年 提交于 2019-12-06 03:43:05

问题


Let's say I need a user service which has all my user variables and functions, and another item service with all item variables and functions, etc etc. I want all this data and functions available throughout the project, passing the user data where it's needed, for example.

I suspect it has something to do with inherited widgets, but how does that work? Like, I see how I could use one inherited widget at the root level, but am I supposed to build a bunch of inherited widgets at the root-level for each service? Or just put ALL the data in the one top inherited widget? Seems like that may get messy. I have yet to see an example of this.

... or should I just be using a class with static variables and call on that where I need it?


回答1:


See the link provided by Günter above. If you have thirty minutes watch Brian Egan's DartConf 18 presentation: Keep it Simple, State. Also see Brian's example code here. He shows the same app coded using InheritedWidget with a Controller, and with Flutter Redux.

Here's a example of a single InheritedWidget from a simple app of mine...

class StateContainer extends InheritedWidget {
  final List<Membership> memberships;

  final IntFunction getNextIndex;
  final VoidMembershipFunction updateMembership;
  final VoidIntFunction deleteMembership;

  const StateContainer({
    this.memberships,
    this.getNextIndex,
    this.updateMembership,
    this.deleteMembership,
    Widget child,
  })
      : super(child: child);

  static StateContainer of(BuildContext context) {
    return context.inheritFromWidgetOfExactType(StateContainer);
  }

  @override
  bool updateShouldNotify(StateContainer oldWidget) {
    return true;
  }
}

I pass in my MaterialApp as the child. A high proportion of the tree then becomes stateless as it has access to the data and methods if the StateContainer. You could think of these as your model and controller in one. Build methods in the tree often start with...

  @override
  Widget build(BuildContext context) {
    final StateContainer container = StateContainer.of(context);

to get access to them.

You are right that a single InheritedWidget becomes unwieldy quickly - which is where you might invest in exploring Redux - see the last 10 minutes of the talk. In my experience, the area that gets messiest quickest is the updateShouldNotify method when ends up comparing all the member variables. (In this simple example there is only one member variable, and setState only gets called when it changes, so it's trivially always true.)



来源:https://stackoverflow.com/questions/49684493/how-do-you-create-services-providers-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!