Flutter pass a function to TextEditingController(text)

Viewed 765

I have this function

String test() => 'test'; 

and I'd like to pass it to the text argument of TextEditingController just like this one.

final TextEditingController _form1 = TextEditingController(text: test() );

but I got this error message.

"The instance member 'Test' can't be accessed in an initializer.
 Try replacing the reference to the instance member with a different expression"

How can I fix it? also, why is this happening? Thanks!

Updated


I moved the function out to Class level and it works. At least with the example.

String test() => 'test';

class SecondScreen extends StatefulWidget {
  @override
  _SecondScreenState createState() => _SecondScreenState();
}


class _SecondScreenState extends State<SecondScreen> {
  Future _signOut() async {
    await FirebaseAuth.instance.signOut();
  }
  final TextEditingController _form1 = TextEditingController(text: test() );
  ...

That example works perfectly. Thing is that my let's called test() function, isn't as simple as return a String, but this one.

 String uid2str(String uid) {
    FirebaseFirestore.instance
        .collection('Usuarios')
        .doc(uid)
        .get()
        .then((DocumentSnapshot documentSnapshot) {
      if (documentSnapshot.exists) {
        Map<String, dynamic> data = documentSnapshot.data()['InfoUser'];
        return '${data['Nombre']} ${data['Apellido']}';
      } else {
        return 'undefined';
      }
    });
  }
final TextEditingController _form1 = TextEditingController(text: uid2str(userID) );

For this case, it doesn't work, I tried using await/async but it seems text can't get a type which isn't not String. So Future can't be used.

I also can't use initialValue in my TextFieldForm because I have already a controller, and it seems I can't have both of them.

1 Answers

Scince test() is a function, it can return dynamic values. So it cant be accessed in an initializer. There are several ways to replace it:

  1. Add this code to your constructor or initState.

    final TextEditingController _form1 = TextEditingController(text: test() );
    
  2. If the String is always the same,

     final TextEditingController _form1 = TextEditingController(text: 'test' );
    
  3. Use a textFormField instead of textField,

     TextFormField(
       //your code
       initialValue = test(),
     )
    
  4. set the test in your constructor,

     _form1.text = test();
    

There may be other possible ways too!

Related