我想创建一个带有两个选项卡的 TabBarView 的应用程序。在第一个选项卡上有一个 Textfield,在另一个选项卡上有一个文本小部件,它应该显示您输入到 Textfield 中的文本,但我总是收到错误消息,因为文本为空。(我是使用 flutter 编程的新手)
我试图在 TextOutput 类中初始化变量,但它不起作用,因为变量是最终的。
TabBarView(
children: <Widget>[
TextCreatePage(), TextOutput()
],
class TextCreatePageState extends State<TextCreatePage> {
String textvalue;
@override
Widget build(BuildContext context) {
return Center(child: TextField(
onChanged: (String value) {
setState(() {
textvalue = value;
TextOutput(textvalue: textvalue,);
});
class TextOutput extends StatelessWidget {
final String textvalue;
TextOutput({this.textvalue});
@override
Widget build(BuildContext context) {
return Text(textvalue);
}
}
Run Code Online (Sandbox Code Playgroud)
Hec*_*ero 10
所以,对于搜索这个并到达这里的任何人,我使用它来管理空字符串变量。
1. 显示空文本
String nullText; //for null-safety change to: String? nullText;
//now, inside of your widget build
Text(nullText ?? '');
Run Code Online (Sandbox Code Playgroud)
2. 不显示 Text Widget
String nullText;
//now, inside of your widget build
if(nullText != null)
Text(nullText);
Run Code Online (Sandbox Code Playgroud)
具有零安全性
String? nullText;
//now, inside of your widget build
if(nullText != null)
Text(nullText!);
Run Code Online (Sandbox Code Playgroud)
你也可以这样显示,但这显示空字
String nullText; //for null-safety change to String? nullText;
//now, inside of your widget build
Text('$nullText');
Run Code Online (Sandbox Code Playgroud)
实时示例https://dartpad.dev/faab5bc3c2df9573c0a75a5ce3d4b4b9
从您在问题中提供的信息尚不清楚是什么代码导致了错误,但我猜是这一行:
return Text(textvalue);
Run Code Online (Sandbox Code Playgroud)
如果你把它改成
return textvalue != null ? Text(textvalue) : Container();
Run Code Online (Sandbox Code Playgroud)
你的错误应该消失。
归档时间: |
|
查看次数: |
10788 次 |
最近记录: |