Ваше решение может быть возможно с помощью 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.Надеюсь, вы добьетесь того, чего хотите :)
(я сделал пример в общем, чтобы каждый мог понять, согласно сценарию, с которым они сталкиваются)