如何将继承的小部件传递到整个Material App

如何将继承的小部件传递到整个Material App,第1张

如何将继承的小部件传递到整个Material App

我对您的前几节课进行了稍微的重组:

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
)对其进行修改。涉及更多样板



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5428091.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存