[英]How can I change a Textfield to another widget onSubmitted?
I have a Textfield and after the input I want to convert the Textfield widget into a simple Textwidget (eg input your name => displays your name).我有一个 Textfield,在输入之后我想将 Textfield 小部件转换为一个简单的 Textwidget(例如输入您的姓名 => 显示您的姓名)。
I tried doing this with a conditional statement in this code below (it's just a quick sample code to display the problem, didn't want to post my whole code):我尝试在下面的代码中使用条件语句执行此操作(它只是显示问题的快速示例代码,不想发布我的整个代码):
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final TextEditingController hello1 = TextEditingController();
int counter = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
hello1.text == ''
? TextField(
controller: hello1, onSubmitted: (_) => print(hello1.text))
: Text(hello1.text),
RaisedButton(onPressed: () {
setState(() {
counter++;
});
})
],
),
),
);
}
}
So when I enter the text into the Textfield and submit it, the widget will not convert into a text widget.因此,当我将文本输入 Textfield 并提交时,该小部件不会转换为文本小部件。 Unless I rerender something else on the screen, that's why I added the RaisedButton and the counter variable.
除非我在屏幕上重新渲染其他内容,这就是我添加 RaisedButton 和计数器变量的原因。
So what can I do to convert it immediately into a text widget.那么我该怎么做才能立即将其转换为文本小部件。 Feel free to point me to some fundamental logic I might be missing here, thank you!
请随意指出我在这里可能遗漏的一些基本逻辑,谢谢!
It's because you don't call the setState() method.这是因为你没有调用 setState() 方法。
Changing the value of the TextEditingController won't rebuild your widget.更改 TextEditingController 的值不会重建您的小部件。 SetState() method does.
SetState() 方法可以。
children: <Widget>[
hello1.text == ''
? TextField(
controller: hello1,
onSubmitted: (_) {
print(hello1.text);
setState(() {});
},
)
: Text(hello1.text),
RaisedButton(
onPressed: () {
setState(() {});
},
)
],
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.