[英]How to get a variable of .dart file to another .dart file in flutter
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. this.dart 文件中的变量“输入”已在无状态小部件中声明,但我怎样才能将此变量传递给另一个.dart 文件。 How to be notified on change of the variable value.
如何通知变量值的变化。
You can do that in two ways你可以通过两种方式做到这一点
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,
)
],
),
);
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.对于干净的方法,如果两个小部件位于树中的不同分支中,您需要一个 state 管理库(如
provider
)在两个小部件之间共享变量。 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.如果使用相同变量的另一个小部件是当前小部件的子小部件,则您可以在每次输入值更改时使用有状态小部件和 setState。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.