Home > Back-end >  How to edit text field and save in controller?
How to edit text field and save in controller?

Time:07-01

I have edit form where some data in text fields controller from database but when I edit or change the test of any text field it doesn't change the value of text field give it me same value which comes from database i can't change the textfiled value.

Here is my code:-

class Edit extends StatefulWidget {

Edit({Key? key}) : super(key: key);

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


class _Edit extends State<Edit>{

 var UsrID = Auth.prefs?.getString('usrid');

 var data;

 RangeValues? _currentRangeValues;

@override
 void initState() {
 super.initState();
 getData();
}

getData() async{
 var res = await http.get(Uri.https('www.*******.com', 
 '/index.php',{'act':'profile','UsrID': '${UsrID}'}));
 data = jsonDecode(res.body);
 print(data);
 setState(() {});
 print(res.body);
}

TextEditingController _name = TextEditingController();
TextEditingController _email = TextEditingController();
TextEditingController _phone = TextEditingController();

var name = "";
var email = "";
var phone = "";
var user = "";

@override
 Widget build(BuildContext context){


return Scaffold(
Container(
      child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
      Padding(
      padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
       child: Text("Name",
           style: TextStyle(color: Colors.black,),
               ),
       ),
       addVerticalSpace(10),
       TextField(
         controller: _name..text = '${data[0]['name']}',
         keyboardType: TextInputType.text,
         obscureText: false,
         decoration: InputDecoration(
         hintText: 'Zeo Saldana',
           ),
          )
          ],
          ),
          ),
         addVerticalSpace(20),
         Container(
            child: Column(
                   crossAxisAlignment: CrossAxisAlignment.start,
              children: [
              Padding(
              padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
              child: Text("Email",
                     style: TextStyle(color: Colors.black,),
                     ),
              ),
              addVerticalSpace(10),
              TextField(
              controller: _email..text = '${data[0]['email']}',
              keyboardType: TextInputType.text,
              obscureText: false,
              decoration: InputDecoration(
               hintText: '[email protected]',
              ),
              )],
              ),),
              addVerticalSpace(20),
              Container(
              child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
               children: [
               Padding(padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
               child: Text("Phone Number",
                      style: TextStyle(color: Colors.black,),
                      ),
                     ),
               addVerticalSpace(10),
               TextField(
               controller: _phone..text = '${data[0]['mobile']}',
               keyboardType: TextInputType.text,
               obscureText: false,
               decoration: InputDecoration(
                hintText: ' 1 94526 12547',
              
                   ),
                )
               ],),
               )
         addVerticalSpace(30),
              ElevatedButton(
                      child: const Text(
                                  'SAVE',
                                  style: TextStyle(
                                    fontSize: 18,
                                  ),
                                ),
                      onPressed: () async{
                         name = _name.text;
                         email = _email.text;
                         phone = _phone.text;
                         user = '${UsrID}';

                          final body = null;
                          final url = Uri.https('www.*******.net', '/index.php',{'act':'profileupdate','name': name, 'email': email, 'phone': phone, 'user': user});
                           final response = await http.post(
                               url,
                               headers: {'Content-Type': 'application/json'},
                               body: body
                               );
                            print(url);
                                 int statusCode = response.statusCode;
                                  //var responseBody = json.decode(response.body);

                                  Map<String, dynamic> responseBody = jsonDecode(response.body);
                                  setState(() {});

                                  var list = responseBody['error'];
                                  var stringList = list.join("\n");
                                  print(stringList); //Prints "in new line"
                                 

                                  var statusRes = responseBody['status'];
                                  var UserID = responseBody['usrid'];

                                  if(statusRes == 'success'){
                                    print('success: ' statusRes);
                                    print(UserID);
                                  } else {
                                    print('error: ' statusRes);
                                  }

                                  print(responseBody);
                                  //print(allerror);


                                  setState(() {});

                                },
                              )
      }

when I change the value of any field it doesn't save and when printing the post API so it shows the old data any data can't change and save.
Please help how I edit all field controller data and post it to API to save in the database.

CodePudding user response:

Issue comes from here

  controller: _name..text = '${data[0]['name']}',

It forces the controller to have the same value. You can use TextEditingController.fromValue to assign for the 1st time.

late TextEditingController _name = TextEditingController.fromValue(TextEditingValue(text: data[0]['name']));

Repeat the same for others fields. More about TextEditingController

CodePudding user response:

Hey issue is here controller: _name..text = '${data[0]['name']}', because every time setState called it's rebuild widget again and assign old value to controller.

You can set value to controller like Yeasin describe to you or you can provide controller value in getData method like below -

getData() async{
 var res = await http.get(Uri.https('www.*******.com', 
 '/index.php',{'act':'profile','UsrID': '${UsrID}'}));
 data = jsonDecode(res.body);
 // assign value to controller here
 _name.text = data[0;

 setState(() {});
 print(res.body);
}
  • Related