IBlackVikingl
IBlackVikingl

Reputation: 1243

Flutter: How to pass data between widgets located in different files

In home page i have 2 widgets in Stack ListWidget() witch located in its own file and displays list of item in home page. Second widget is TextWidget() witch is Text in Container and this widget is in the HomePage file. In ListWidget() i use ListTile with onTap to open other page like this

Navigator.of(context).push(
  MaterialPageRoute(
   builder: (context) => ListItemPressed(),
  ),
);

Both of this widget is used in same page, but ListWidget() in in other file. What i want to achieve is instead of opening new page with OnTap i want to change TextWidget's text to pressed list items title

Basically, i want to get data from ListWidget() to TextWidget without opening any pages. My code is to large, so here is basic logic of my app:

HomePage{
 Scaffold
  Stack
   StreamBuilder<NavOption> // Home page display widget based on NavOption, in this case ListWidget
    ListWidget() // I want data from here... widget located in lib/ListWidget.dart
   TextWidget() // ...in here, widget located in this file HomePage.dart
}

Upvotes: 0

Views: 1481

Answers (1)

kzrfaisal
kzrfaisal

Reputation: 1443

Here's how you can achieve it

  • Declare a function and a variable in your Home Page.
     dataFromListWidget;
     onListItemPressed(data) {
      setState(() => dataFromListWidget = data);
     }
    
  • Pass this function as argument to ListWidget and variable to TextWidget.
    [
      ListWidget(onListItemPressedFunc: onListItemPressed),
      TextWidget(data: dataFromListWidget )
    ]
    
    
  • Call this function from ListWidget and provide the data that you want to display in text widget.
     ListWidget({@required this.onListItemPressedFunc}) // ListWidget Contructor
     final Function onListItemPressedFunc;
     ...
     onListItemPressedFunc(data); // Call it When List Item is pressed and pass the data.
    
    

However I would suggest you to use an observer based state management package like getx etc, it will become much easier.

Upvotes: 1

Related Questions