0

Is there a way to simply turn hintText into an actual value? I'm getting ${widget.message} from another class (previous screen where a person inputs a given value) and then want it to be hardcoded. I tried with using initialValue in TextFormField, but can't get it to work.

When writting initialValue: ${widget.message}, before the controller, I get " Failed assertion: line 196 pos 15: 'initialValue == null || controller == null': is not true."

               TextFormField(
                controller: nameController,
                validator: (value){
                  if(value.isEmpty){
                    return "Enter Valid Name";
                  }else{
                    return null;
                  }
                },
                decoration: InputDecoration(
                  hintText: "${widget.message}",
                  suffixIcon: IconButton(
                    onPressed: () => nameController.clear(),
                    icon: Icon(Icons.clear),
                  ),
                ),
              ),
  • without controller: https://stackoverflow.com/a/51382431/2252830, and if you already have a controller just use its [text](https://api.flutter.dev/flutter/widgets/TextEditingController/text.html) property – pskink May 16 '21 at 09:17
  • I need controller, because it sends data further. Tried TextEditingController nameController = TextEditingController(text: "${widget.message}"); , but also doesn't work. – user14584183 May 16 '21 at 09:23
  • I did as I wrote an example above. – user14584183 May 16 '21 at 09:30

1 Answers1

2

Create a TextEditingController and provide the '${widget.message}' value to it in the initState and then disable the TextFormField by setting the property enabled: false.

For example:

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key key, this.message}) : super(key: key);
  final String message;

  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  final text = TextEditingController();

  @override
  void initState() {
    super.initState();
    text.text = '${widget.message}'; //provide the controller the recived value in initState
  }

  @override
  void dispose() {
    text.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
          child: TextFormField(
            controller: text,
            enabled: false, //Set it to false so they can't further change it
            decoration: InputDecoration(
              border: OutlineInputBorder(),
            ),
          ),
        ),
      ),
    );
  }
}

Deepanshu
  • 890
  • 5
  • 18