您的解决方案可以通过使用setState() 并在 WidgetTwo 的构造函数中传递您的状态函数来实现。我在下面做了一个例子,这个例子的主要思想是我有 MyHomePage 作为我的主要小部件和 MyFloatButton (我想自定义为另一个StatefulWidget),所以当按下 FAB 我需要在 MyHomePage 中调用增量计数器功能。让我们看看下面我是如何做到的。
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
//Consider this function as your's _onNotification and important to note I am using setState() within :)
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(
widget.title,
style: TextStyle(color: Colors.white),
),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'You have pushed the button $_counter times:',
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
),
],
),
),
floatingActionButton: new MyFloatButton(_incrementCounter),//here I am calling MyFloatButton Constructor passing _incrementCounter as a function
);
}
}
class MyFloatButton extends StatefulWidget {
final Function onPressedFunction;
// Here I am receiving the function in constructor as params
MyFloatButton(this.onPressedFunction);
@override
_MyFloatButtonState createState() => new _MyFloatButtonState();
}
class _MyFloatButtonState extends State<MyFloatButton> {
@override
Widget build(BuildContext context) {
return new Container(
padding: EdgeInsets.all(5.0),
decoration: new BoxDecoration(color: Colors.orangeAccent, borderRadius: new BorderRadius.circular(50.0)),
child: new IconButton(
icon: new Icon(Icons.add),
color: Colors.white,
onPressed: widget.onPressedFunction,// here i set the onPressed property with widget.onPressedFunction. Remember that you should use "widget." in order to access onPressedFunction here!
),
);
}
}
现在将 MyHomePage 视为您的 WidgetOne,将 MyFloatButton 视为您的 WidgetTwo,将 _incrementCounter 函数视为您的 _onNotification。希望你能实现你想要的:)
(我做了一般性的例子,所以任何人都可以根据他们所面临的情况来理解)