How to pass data over the tree without changing context?

时间:2019-06-01 14:01:36

标签: flutter

I search an easy solution to pass data with the constructor without changing page. Tried to passe data with constructor like this

My_first_Stful_widget
{
...
  _calendarCarousel = CalendarCarousel<Event>(
      onDayPressed: (DateTime date, List<Event> events) {
        this. setState(() {

          currentDate = date;
       My_second_Stful_widget(currentDate:currentDate) ; // I search to pass and launch currentDate in load_data() who is located in my second stful widget when onDayPressed is press in the first stful widget.
...
}

My_second_Stful_widget
{

this.currentDate


final String currentDate

... 

load_data() async {



    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      pulsions = (prefs.getString('${widget.currentDate},pulsions'))??0;

    });
  }
}

1 个答案:

答案 0 :(得分:0)

我不确定标准,但这将使您的工作完成 因此,我们要做的是将日期从My_first_Stful_widget返回到其父级,在那里您同时拥有My_first_Stful_widget,My_second_Stful_widget并更新父窗口小部件中的currentDate。.因此,当我们更新其状态时,也会将currentDate传递给My_second_Stful_widget已更新。

My_first_Stful_widget
{
Function(DateTime) callback;

...
  _calendarCarousel = CalendarCarousel<Event>(
      onDayPressed: (DateTime date, List<Event> events) {

        widget.callback(date);
        this. setState(() {

          currentDate = date;

...
}

Parent_Widget{

...
String currentDate;

...
callback(date){
   SetState((){
      this.currentDate = date;
})

}

PageView: <Widget>[
My_first_Stful_widget(callback),
My_second_Stful_widget(currentDate:currentDate)

]



}