Solution 1 :
You can do that in two ways
- Use Provider package from pub.dev, and then you can use the variable in any other dart file. This is the preferred way for somewhat complex program.
- You can just declare and initialize the variable outside the widget and than you can just use the variable in another dart file too.
Like this,
String input = "";
class widget_model extends StatelessWidget {
final text;
widget_model(this.text);
@override
Widget build(BuildContext context) {
return Expanded(
child: Row(
children: <Widget>[
Expanded(
child: Column(
children: <Widget>[
Container(
height: 60,
alignment: Alignment.center,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.pink, Colors.purpleAccent])),
child: InkWell(
onTap: () {
print("Pressed one");
print("The text is $input");
input=input+"1";
print("The text after $input");
Navigator.push(context, MaterialPageRoute(builder: (BuildContext)=>Homepage(input)));
},
child: Text(
"$text",
style: TextStyle(color: Colors.white, fontSize: 50),
),
),
),
],
),
),
SizedBox(
height: 10,
width: 5,
)
],
),
);
Solution 2 :
For a clean approach, you need a state management library like provider
to share the variable between two widgets if both widget are in a different branches in the tree. If the other widget that used the same variable is a child of the current one, you can use stateful widget and setState everytime the input value changes.
Problem :
class widget_model extends StatelessWidget {
final text;
widget_model(this.text);
String input = "";
@override
Widget build(BuildContext context) {
return Expanded(
child: Row(
children: <Widget>[
Expanded(
child: Column(
children: <Widget>[
Container(
height: 60,
alignment: Alignment.center,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.pink, Colors.purpleAccent])),
child: InkWell(
onTap: () {
print("Pressed one");
print("The text is $input");
input=input+"1";
print("The text after $input");
Navigator.push(context, MaterialPageRoute(builder: (BuildContext)=>Homepage(input)));
},
child: Text(
"$text",
style: TextStyle(color: Colors.white, fontSize: 50),
),
),
),
],
),
),
SizedBox(
height: 10,
width: 5,
)
],
),
);
}
}
The variable ‘input’ in this .dart file has been declared within the stateless widget but how can I get this variable to another .dart file. How to be notified on change of the variable value.