简体   繁体   English

尝试从另一个小部件打印 Textfield 的文本并始终在 flutter 中打印空(仅 I/flutter ( 9049): )

[英]Trying to print the text of Textfield from another widget and always print empty ( just I/flutter ( 9049): ) in flutter

TextEditingController _name = TextEditingController();

Future<String> randomFun() async{
  return _name.text;
}

and in another class:在另一堂课中:

print(await(theFirstClass.randomFun()));

and it's just always print I/flutter ( 9049):它总是打印 I/flutter ( 9049 ):

I have written in the Textfield it's must be has text value.我已经在 Textfield 中写了它必须具有文本值。

I printed it in the same class and work this problem when print from another class it's cant see the value of _name i don't know why.我在同一个班级打印它并在从另一个班级打印时解决了这个问题,它看不到 _name 的值,我不知道为什么。

for more explain: i neet to print the text of TextField by button in another widget更多解释:我需要通过另一个小部件中的按钮打印 TextField 的文本

it's can work if i added static for _name like this static TextEditingController _name = TextEditingController();如果我像这样static TextEditingController _name = TextEditingController();那样为 _name 添加静态,它就可以工作static TextEditingController _name = TextEditingController();

but i need way without static但我需要没有静态的方法

my code is like this:我的代码是这样的:

2 stateful widgets in one page the first widget FirstClass the second widget SecondClass FirstClass一个页面中的 2 个有状态小部件 第一个小部件 FirstClass 第二个小部件 SecondClass FirstClass

class FirstClassextends State<First> {
...
  TextEditingController_name = TextEditingController();

  Future<String> randomFun() async{
    return _name.text;
  }
...
  TextField(
  decoration: InputDecoration(labelText: 'Enter your name'),
  controller: _name,
  ),
...
}

secondClass二等舱

class secondClassextends State<second> {
...
  FirstClass firstClass = FirstClass();
...
  IconButton(
    icon: Icon(Icons.person, color: Colors.white,),
    onPressed: ()async{
      print(await(firstClass.randomFun()));
    }
  ),

And again i need to print/get the text of TextField by pressing a button in another widget.我再次需要通过按下另一个小部件中的按钮来打印/获取 TextField 的文本。

Change this改变这个

Future<String> randomFun() async{
    return _name.text;
  }

to

Future<String> randomFun() async {
    return Future.value(_name.text);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM