Flutter:列表数据更改时 getx 控制器未更新.我如何确保添加的每个列表,GetX 控制器都知道? [英] Flutter: getx controller not updated when list data changed. How can i make sure with every list added, GetX controller knows that?

查看:29
本文介绍了Flutter:列表数据更改时 getx 控制器未更新.我如何确保添加的每个列表,GetX 控制器都知道?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在 stepper 中有一个表单,其中有两个字段名称和电子邮件.添加按钮工作正常,并按预期将姓名和电子邮件添加到列表中.当我点击保存时,JSON 数据与列表中的所有可用数据一起打印.

I simply have a form in stepper there are two fields Name and Email. The Add button works fine and add name and email to list as expected. When I click on save, The JSON data is printed with all the data available in the list.

[{"Name":"first language","Email":"first value"},{"Name":"second language","Email":"second value"},{"Name":"third language","Email":"third value"},{"Name":"test","Email":"test"}]

但是,当我点击底部的保存按钮时,会打印硬编码列表,而不是我们输入的数据.

But, when i click on save button at the bottom, The hard coded list is printed and not the data we entered.

输出如下.我想在 JSON 中获取所有列表数据.目前,以下没有从列表中手动插入的数据.:

The output is the following. I wanted to get all the list data inside JSON. Currently, the following doesn't have the manually inserted data from list.:

{"User Data":[{"Name":"first language","Email":"first value"},{"Name":"second language","Email":"second value"},{"Name":"third language","Email":"third value"}]}

代码如下:-

  1. model.dart

    class User {
      String name;
      String email;
    
      User({this.name, this.email});
    
      Map toJson() => {
            'Name': name,
            'Email': email,
          };
    }

class JSONGenerate {
  List<User> userData;

  JSONGenerate([this.userData]);

  Map toJson() {
    List<Map> userData = this.userData != null
        ? this.userData.map((i) => i.toJson()).toList()
        : null;

    return {
      'User Data': userData,
    };
  }
} 

  1. 用户.dart

class UserMinor extends StatefulWidget {
  @override
  _UserMinorState createState() => _UserMinorState();
}

class _UserMinorState extends State<UserMinor> {
  final form = GlobalKey<FormState>();
  static var _focusNode = new FocusNode();
  // finding same instance if initialized controller
  final controller = Get.find<UserMinorController>();
  @override
  Widget build(BuildContext context) {
    Widget bodyData() => DataTable(
          onSelectAll: (b) {},
          sortColumnIndex: 0,
          sortAscending: true,
          columns: <DataColumn>[
            DataColumn(label: Text("User Name"), tooltip: "User Name"),
            DataColumn(label: Text("User Email"), tooltip: "User Email"),
          ],
          rows: controller.userList // accessing list from Getx controller
              .map(
                (user) => DataRow(
                  cells: [
                    DataCell(
                      Text(user.name),
                    ),
                    DataCell(
                      Text(user.email),
                    ),
                  ],
                ),
              )
              .toList(),
        );

    return Padding(
      padding: EdgeInsets.all(10.0),
      child: Column(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.all(10.0),
            child: Form(
              key: form,
              child: Container(
                child: Column(
                  children: <Widget>[
                    TextFormField(
                      controller: controller.nameController,
                      focusNode: _focusNode,
                      keyboardType: TextInputType.text,
                      autocorrect: false,
                      maxLines: 1,
                      validator: (value) {
                        if (value.isEmpty) {
                          return 'This field is required';
                        }
                        return null;
                      },
                      decoration: InputDecoration(
                        labelText: 'Name',
                        hintText: 'Name',
                        labelStyle: new TextStyle(
                            decorationStyle: TextDecorationStyle.solid),
                      ),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    TextFormField(
                      controller: controller.emailController,
                      keyboardType: TextInputType.text,
                      autocorrect: false,
                      maxLines: 1,
                      validator: (value) {
                        if (value.isEmpty) {
                          return 'This field is required';
                        }
                        return null;
                      },
                      decoration: InputDecoration(
                          labelText: 'Email',
                          hintText: 'Email',
                          labelStyle: new TextStyle(
                              decorationStyle: TextDecorationStyle.solid)),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Column(
                      children: <Widget>[
                        Center(
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Row(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  TextButton(
                                    child: Text("Add"),
                                    onPressed: () {
                                      if (validate() == true) {
                                        form.currentState.save();
                                        controller.addLanguagetoList(
                                          controller.nameController.text,
                                          controller.emailController.text,
                                        );
                                      }
                                    },
                                  ),
                                  ElevatedButton(
                                      child: Text("Save"),
                                      onPressed: () {
                                        form.currentState.save();
                                        String minorlanguageListJson =
                                            jsonEncode(controller.userList);
                                        print(minorlanguageListJson);
                                      }),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
          // GetBuilder rebuilds when update() is called
          GetBuilder<UserMinorController>(
            builder: (controller) => bodyData(),
          ),
        ],
      ),
    );
  }

  bool validate() {
    var valid = form.currentState.validate();
    if (valid) form.currentState.save();
    return valid;
  }
}

  1. stepper.dart

class StepperBody extends StatefulWidget {
  @override
  _StepperBodyState createState() => new _StepperBodyState();
}

class _StepperBodyState extends State<StepperBody> {
  int currStep = 0;
  static var _focusNode = new FocusNode();
  GlobalKey<FormState> _formKey = new GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
    _focusNode.addListener(() {
      setState(() {});
      print('Has focus: $_focusNode.hasFocus');
    });
  }

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

  List<Step> steps = [
    new Step(
      title: const Text('Technical Language Basics'),
      isActive: true,
      state: StepState.indexed,
      content: UserMinor(),
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Container(
      child: new Form(
        key: _formKey,
        child: new ListView(
          children: <Widget>[
            new Stepper(
              steps: steps,
              type: StepperType.vertical,
              currentStep: this.currStep,
              onStepContinue: () {
                setState(() {
                  if (currStep < steps.length - 1) {
                    currStep = currStep + 1;
                  } else {
                    currStep = 0;
                  }
                });
              },
              onStepCancel: () {
                setState(() {
                  if (currStep > 0) {
                    currStep = currStep - 1;
                  } else {
                    currStep = 0;
                  }
                });
              },
              onStepTapped: (step) {
                setState(() {
                  currStep = step;
                });
              },
            ),
            new ElevatedButton(
              child: new Text(
                'Save details',
                style: new TextStyle(color: Colors.white),
              ),
              onPressed: () {
                var technicalInfo = UserMinorController().userList;
                JSONGenerate jsonGenerate = JSONGenerate(technicalInfo);
                print(
                  jsonEncode(jsonGenerate),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

  1. GetX 控制器类

    class UserMinorController extends GetxController {
      TextEditingController nameController = TextEditingController();
      TextEditingController emailController = TextEditingController();
      int currentIndex = 0;
    
      List<User> userList = [
        User(name: "first language", email: "first value"),
        User(name: "second language", email: "second value"),
        User(name: "third language", email: "third value"),
      ];
    
    
    
      void addLanguagetoList(name, email) {
        userList.add(User(name: name, email: email));
        update();
      }
    }

推荐答案

这是这里的问题:

var technicalInfo = UserMinorController().userList;

在 GetX 中,您需要查找"与 Get.find() 相同的控制器实例.这会找到与您要添加的实际列表相同的实例.你这样做的方式是打印出一个不同的实例 UserMinorController 这就是为什么它只打印出硬编码数据.

In GetX that you need to "find" the same instance of the controller with Get.find<UserMinorController>(). That finds the same instance that has the actual list that you're adding to. The way you were doing it was printing out a different instance UserMinorController which is why it was only printing out the hard coded data.

您的 onPressed 应该如下所示.

Your onPressed should look like this.

 onPressed: () {
   var technicalInfo = Get.find<UserMinorController>().userList;
   JSONGenerate jsonGenerate = JSONGenerate(technicalInfo);
   print(jsonEncode(jsonGenerate));
}

这篇关于Flutter:列表数据更改时 getx 控制器未更新.我如何确保添加的每个列表,GetX 控制器都知道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆