Jus*_*s10 5 dart flutter inherited-widget
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?
请参阅上面的Günter提供的链接。如果您有三十分钟的时间观看Brian Egan的DartConf 18演示文稿,请保持简洁,状态。还看到Brian的示例代码在这里。他展示了使用InheritedWidget和Controller以及Flutter Redux编码的相同应用。
这是来自我的一个简单应用程序的单个InheritedWidget的示例...
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我作为孩子传入了我的MaterialApp。然后,如果StateContainer可以访问数据和方法,则很大一部分树将变为无状态。您可以将它们视为模型和控制器合二为一。树中的构建方法通常以...开始
@override
Widget build(BuildContext context) {
final StateContainer container = StateContainer.of(context);
Run Code Online (Sandbox Code Playgroud)
来访问他们。
没错,单个InheritedWidget很快就会变得笨拙-您可以在其中投资探索Redux-请参阅讲座的最后10分钟。以我的经验,最混乱的地方是在比较所有成员变量时的updateShouldNotify方法。(在这个简单的示例中,只有一个成员变量,并且setState仅在其更改时才被调用,因此它总是很小。)
| 归档时间: |
|
| 查看次数: |
4393 次 |
| 最近记录: |