如何编辑文本字段并保存在控制器中?

发布于 2025-02-12 07:33:32 字数 5607 浏览 3 评论 0原文

我有编辑表单,其中文本字段中的某些数据来自数据库中的某些数据,但是当我编辑或更改任何文本字段的测试时,它不会更改文本字段的值,从而使我相同的值,该值来自数据库,我无法更改textfiled值。

这是我的代码: -

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(() {});

                                },
                              )
      }

当我更改任何字段的值并未保存的值时,在打印帖子API时,它显示了旧数据,任何数据都无法更改并保存。
请帮助我如何编辑所有现场控制器数据并将其发布到API中以保存在数据库中。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦晓ヶ微光ヅ倾城 2025-02-19 07:33:32

问题来自这里,

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

它迫使控制器具有相同的值。您可以使用textedingcontroller.fromvalue第一次分配。

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

重复其他字段。有关 textededingingcontroller

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

玩世 2025-02-19 07:33:32

嘿问题在这里控制器:_name..text ='$ {data [0] [0] ['name']}',因为每次SetState都称其为重建小部件,并将旧值分配给控制器。

您可以像Yeasin所描述的那样将值设置为控制器,也可以在以下方式中提供控制器值 -

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);
}

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文