我对您的前几节课进行了稍微的重组:
import 'package:flutter/material.dart';void main() => runApp(InheritedStateWidget());class InheritedStateWidget extends StatefulWidget { @override InheritedStateWidgetState createState() => InheritedStateWidgetState();}class InheritedStateWidgetState extends State<InheritedStateWidget> { String _userName; // Getter methods String get tasks => _userName; void changeUserName(String name) { setState(() { _userName = name; }); } @override Widget build(BuildContext context) { return new MyInheritedWidget( data: this, child: MyApp(), ); }}class MyInheritedWidget extends InheritedWidget { final InheritedStateWidgetState data; MyInheritedWidget({Key key, this.data, Widget child}) : super(key: key, child: child); static MyInheritedWidget of(BuildContext context) => context.inheritFromWidgetOfExactType(MyInheritedWidget); @override bool updateShouldNotify(MyInheritedWidget old) => true;}class MyApp extends StatelessWidget { // in MyApp and below you can refer to MyInheritedWidget.of(context).data @override Widget build(BuildContext context) { return new MaterialApp( title: 'App One', home: new MyHomePage(), ); }}
我喜欢像这样加强State和InheritedWidget之间的接口,但这只是一个建议…
void main() => runApp(new Controller());class Controller extends StatefulWidget { @override State<StatefulWidget> createState() => ControllerState();}typedef void VoidIntFunction(int i);class ControllerState extends State<Controller> { String someString = ''; void someFunction(int v) { print('function called with $v'); } @override Widget build(BuildContext context) { return StateContainer( someString: someString, someFunction: someFunction, child: new ExampleApp(), ); }}class StateContainer extends InheritedWidget { final String someString; final VoidIntFunction someFunction; const StateContainer({ this.someString, this.someFunction, Widget child, }) : super(child: child); static StateContainer of(BuildContext context) => context.inheritFromWidgetOfExactType(StateContainer); @override bool updateShouldNotify(StateContainer oldWidget) => true;}
现在使用InheritedWidget的任何子级都具有对状态(
someString)的读取权限,并且必须通过调用方法(
someFunction)对其进行修改。涉及更多样板。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)