Home > Back-end >  How to build widget that depends on the value of Text Field?
How to build widget that depends on the value of Text Field?

Time:09-17

I want to add a Text widget in column and the value should be TextFormField's input value entered by the user.

Code

String text;
Column(
  children: <Widget>[
    Padding(
      padding: const EdgeInsets.fromLTRB(30, 10, 30, 10),
      child: TextFormField(
        onFieldSubmitted: (value) {
          text= value;
        },
      ),
     Text(text), // want to add text here
   ]

It is throwing an error:

A non-null String must be provided to a Text widget.

What should be the good way to do it ?

CodePudding user response:

1st make nullable text like String? text;

Change based on Submit inside statefullWidget.

 onFieldSubmitted: (value) {
            setState(() {
              text = value;
            });
          },

Secondly, you need to handle null value like

if (text != null) Text(text!), or like Text(text ?? "defaul value"),

Widget will be like

 String? text;

  @override
  Widget build(BuildContext context) {
    return Column(children: <Widget>[
      Padding(
        padding: const EdgeInsets.fromLTRB(30, 10, 30, 10),
        child: TextFormField(
          onFieldSubmitted: (value) {
            setState(() {
              text = value;
            });
          },
        ),
      ),
      if (text != null) Text(text!), // want to add text here
    ]);
  }

does it solve in your case?

CodePudding user response:

Because you have not assigned any value while initializing the "String text" variable and the Text widget can not accept a null string, You may need to either initialize the text like this

String text = "";

or place or null check on the string in the text widget like this

Text(text??""),

or additionally, you can use null-safety like this

String? text;

Your final code will be like

String text = "";
Column(
  children: <Widget>[
    Padding(
      padding: const EdgeInsets.fromLTRB(30, 10, 30, 10),
      child: TextFormField(
        onFieldSubmitted: (value) {
           setState((){
           text= value;
          });
        },
      ),
     Text(text??""), // placed null check
   ]

CodePudding user response:

Update your code:

String? text;
Column(
  children: <Widget>[
    Padding(
      padding: const EdgeInsets.fromLTRB(30, 10, 30, 10),
      child: TextFormField(
        onFieldSubmitted: (value) {
          text = value;
        },
      ),
     Text(text), // want to add text here
   ]
  • Related