gpt4 book ai didi

android - Flutter 将文本 onchange 值分配给变量

转载 作者:行者123 更新时间:2023-12-04 10:53:14 25 4
gpt4 key购买 nike

我正在学习 flutter 教程并遇到了一个问题。它应该从 textfield onChanged 函数中获取一个值并将其分配给一个变量。但是它不起作用。因为它是在 iphone 上显示的,我想它在 android 上的工作方式可能有点不同。

@override
Widget build(BuildContext context) {
String newTaskTitle;
return Container(
color: Color(0xff757575),
....

TextField(
autofocus: true,
textAlign: TextAlign.center,
onChanged: (newText) {
newTaskTitle = newText;
},
),
FlatButton(
child: Text(
'Add',
style: TextStyle(
color: Colors.white,
),
),
color: Colors.lightBlueAccent,
onPressed: () {
print(newTaskTitle);
},

最佳答案

Kalev,尝试使用 StatefulWidget和刷新状态,当你想要新文本时,如下所示,

class MyApp extends StatefulWidget {
@override
MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
String text = 'Original text';
String newTaskTitle;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(text),
TextField(
autofocus: true,
textAlign: TextAlign.center,
onChanged: (newText) {
newTaskTitle = newText;
},
),
FlatButton(
child: Text(
'Add',
style: TextStyle(
color: Colors.white,
),
),
color: Colors.lightBlueAccent,
onPressed: () {
setState(() {
text = newTaskTitle;
});
}),
],
),
),
));
}
}

demo


您可以添加 setState((){}) 直接在里面 onChanged 像这样
onChanged: (newText) {
newTaskTitle = newText;
setState((){});
},

关于android - Flutter 将文本 onchange 值分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59363658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com