是的,这是可能的。
最简单的方法是使用
InheritedWidget
你可能记得一个方法
of(context)
,例如:
MediaQuery.of(context).size
Navigator.of(context).pop()
Theme.of(context).canvasColor
这些是继承的小部件。您正在使用
of()
应用程序中的任何地方都可以访问主题,因为它们是继承的。使用
of
方法可以在实现小部件树之后更改小部件树的状态。
因此,您的示例代码应该如下所示:
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
home: MyApp(),
),
);
}
//this is a newly added stateful widget to use inherited widget
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int count = 0;
void incrementer() {
setState(() {
count++;
});
}
void decrementer() {
setState(() {
count--;
});
}
@override
Widget build(BuildContext context) {
return CounterState(
count: count,
incrementer: incrementer,
decrementer: decrementer,
child: HomePage(),
);
}
}
//this is the inherited widget
class CounterState extends InheritedWidget {
CounterState({Key key, this.count, this.incrementer, this.decrementer, Widget child})
: super(key: key, child: child);
final int count;
final Function incrementer;
final Function decrementer;
@override
bool updateShouldNotify(CounterState oldWidget) {
return count != oldWidget.count;
}
static of(BuildContext context) {
return context.inheritFromWidgetOfExactType(CounterState);
}
}
//make below classes stateless(not must but useless)
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
MemberSection(),
AdminSection()
],
),
);
}
}
class MemberSection extends StatelessWidget {
@override
Widget build(BuildContext context) {
final counterState = CounterState.of(context);
return new Text('${counterState.count} member(s)');
}
}
class AdminSection extends StatelessWidget {
@override
Widget build(BuildContext context) {
final counterState = CounterState.of(context);
return new Column(
children: <Widget>[
Text('${counterState.count} admin(s)'),
ButtonBar(
children: <Widget>[
RaisedButton(child: Text('add a member'), onPressed: counterState.incrementer,),
RaisedButton(child: Text('delete a member'), onPressed: counterState.decrementer,),
],
),
],
);
}
}
可以找到一个很好的教程
here
.