sg717
sg717

Reputation: 53

How to build widget that depends on the value of Text Field?

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 ?

Upvotes: 0

Views: 347

Answers (4)

awaik
awaik

Reputation: 12287

Thanks to https://github.com/lgjenero for the cool trick - update widgets depending on TextField state without setState.

  child: AnimatedBuilder(
    animation: _textEditController,
    builder: (context, child) {
      return Text(
        'Create',
        style: _textEditController.text.isEmpty ? styleOne : styleTwo,
      );
    },
  ),

Upvotes: 1

Ayyaz Shair
Ayyaz Shair

Reputation: 620

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
   ]

Upvotes: 1

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
   ]

Upvotes: 0

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63569

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?

Upvotes: 1

Related Questions