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

Issue

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 have written in the Textfield it’s must be has text value.

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.

for more explain:
i neet to print the text of TextField
by button in another widget

it’s can work if i added static for _name
like this 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

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.

Solution

Change this

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

to

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

Answered By – Naveen Avidi

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.