【问题标题】:Why my value is not updating in GetX Flutter为什么我的值没有在 GetX Flutter 中更新
【发布时间】:2021-12-20 04:22:59
【问题描述】:

我在 GetX 中制作了两个非常简单的页面来学习它。我为它创建了三个变量,一个是柜台,另一个是目的地和出发城市。计数器变量正在完美更新,而其他变量没有改变它们的值。它们只有在我热重载时才会改变。

如果您认为我遗漏了某些内容,或者这种疑问很常见,并且您已经看到了与我的非常相似的示例,请分享它的链接或更正代码。

这是我的课:

import 'package:get/get.dart';

class Controller extends GetxController {
  var count = 0.obs;
  var des = "Delhi".obs;
  var dep = "Agra".obs;
  void increment() {
    count.value++;
    update();
  }

  void updateDes(String input) {
    des = input.obs;
  }

  void updateDep(String input) {
    dep = input.obs;
  }
}

这是第一页(您可以查看第 14、30-52 行)-

import 'package:flutter/material.dart';
import 'package:flutter_application_firebase_noti_basics/my_controller.dart';
import 'package:flutter_application_firebase_noti_basics/new_home.dart';
import 'package:get/get.dart';

class Sample extends StatefulWidget {
  const Sample({Key? key}) : super(key: key);

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

class _SampleState extends State<Sample> {
  final my_controller = Get.put(Controller());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: EdgeInsets.all(20.0),
        child: Center(
          child: Container(
            width: 300,
            height: 300,
            color: Colors.grey[400],
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Obx(
                  () => InkWell(
                    child: Text("${my_controller.des}"),
                    onTap: () {
                      Get.to(NewHome(
                        num: 1,
                      ));
                    },
                  ),
                ),
                const SizedBox(
                  height: 20,
                ),
                Obx(
                  () => InkWell(
                    child: Text('${my_controller.dep}'),
                    onTap: () {
                      Get.to(NewHome(
                        num: 2,
                      ));
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

这里是城市选择页面(您可以查看线路:32、93-103、121-125)-

import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'my_controller.dart';

class NewHome extends StatefulWidget {
  int? num = 0;

  NewHome({
    Key? key,
    this.num,
  }) : super(key: key);

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

class _NewHomeState extends State<NewHome> {
  final List<Map<String, dynamic>> _allCities = [
    {"id": 1, "city": "Delhi", "state": ""},
    {"id": 2, "city": "Agra", "state": "UP"},
    {"id": 3, "city": "Mumbai", "state": "Maharashtra"},
    {"id": 4, "city": "Jaipur", "state": "Rajasthan"},
    {"id": 5, "city": "Jodhpur", "state": "Rajasthan"},
    {"id": 6, "city": "Ranchi", "state": "Jharkhand"},
    {"id": 7, "city": "Dhanbad", "state": "Jharkhand"},
    {"id": 8, "city": "Kanpur", "state": "UP"},
    {"id": 9, "city": "Chandigarh", "state": "Punjab"},
    {"id": 10, "city": "Meerut", "state": "UP"},
  ];

  final controller = Get.put(Controller());

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        backgroundColor: const Color(0xffEEEDEF),
        body: Column(
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 10.0),
              child: Row(
                children: [
                  IconButton(
                    icon: const Icon(Icons.arrow_back),
                    color: Colors.orange,
                    onPressed: () {
                      Navigator.pop(context);
                    },
                  ),
                  Container(
                    width: MediaQuery.of(context).size.width * 0.85,
                    height: 50.0,
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius:
                            const BorderRadius.all(Radius.circular(5.0)),
                        border: Border.all(color: Colors.blueAccent)),
                    child: TextField(
                      decoration: InputDecoration(
                        hintText: "Enter Origin",
                        border: InputBorder.none,
                        contentPadding: const EdgeInsets.only(left: 10.0),
                        hintStyle: TextStyle(
                          fontSize: 15.0,
                          color: Colors.grey[500],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Align(
              alignment: Alignment.centerLeft,
              child: Padding(
                padding: EdgeInsets.only(
                    left: MediaQuery.of(context).size.width * 0.04, top: 3.0),
                child: Text(
                  'Popular Searches:',
                  style: TextStyle(
                      color: Colors.grey[500],
                      fontSize: MediaQuery.of(context).size.width * 0.035),
                ),
              ),
            ),
            Expanded(
              child: ListView.builder(
                itemCount: _allCities.length,
                itemBuilder: (context, index) {
                  return InkWell(
                    onTap: () {
                      controller.increment();
                      if (widget.num == 1) {
                        controller.updateDes(_allCities[index]['city']);
                        Get.back();
                      } else if (widget.num == 2) {
                        controller.updateDep(_allCities[index]['city']);
                        Get.back();
                      } else {
                        Get.back();
                      }
                    },
                    child: Padding(
                      padding: const EdgeInsets.only(
                          left: 18.0, top: 10.0, bottom: 15.0),
                      child: Text(
                        _allCities[index]['city'],
                        style: const TextStyle(
                          color: Colors.black,
                          fontSize: 15.0,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
            Obx(
              () => Text("${controller.count} cities are selected",
                  style: const TextStyle(fontSize: 20.0)),
            )
          ],
        ),
      ),
    );
  }
}

【问题讨论】:

  • 使用 GetBuilder 代替 Obx

标签: android flutter dart flutter-getx


【解决方案1】:

那是因为您没有正确更新值。使用响应式 (obs) 变量时,您需要更新变量的 value 属性。

此外,您不应将 update 与 obs 变量一起使用,因为它们会自动更新。所以你的控制器将是:

class Controller extends GetxController {
  var count = 0.obs;
  var des = "Delhi".obs;
  var dep = "Agra".obs;

  void increment() {
    count.value++;
    // removed update()
  }

  void updateDes(String input) {
    // changing from des = input.obs
    des.value = input;
  }

  void updateDep(String input) {
    // changing from dep = input.obs
    dep.value = input;
  }
}

【讨论】:

    【解决方案2】:

    您需要从代码中删除更新,并从字符串值中删除 .obs,如下所示:

    import 'package:get/get.dart';
    
    class Controller extends GetxController {
      var count = 0.obs;
      var des = "Delhi".obs;
      var dep = "Agra".obs;
      void increment() {
        count.value++;
     // remove this --->   update();
      }
    
      void updateDes(String input) {
    des=input
      // remove this--->  des = input.obs;
    
      }
    
      void updateDep(String input) {
       // remove this--->    dep = input.obs;
    dep=input
      }
    }
    

    【讨论】:

      【解决方案3】:
          import 'package:get/get.dart';
      
      class Controller extends GetxController {
        var count = 0.obs;
        var des = "Delhi".obs;
        var dep = "Agra".obs;
        void increment() {
          count.value++;
          
        }
      
        void updateDes(String input) {
          des = input.obs;
        }
      
        void updateDep(String input) {
          dep = input.obs;
        }
      }
      

      在您的第一页代码中,您需要删除 updated() 函数,因为如果您使用的是 obs,则无需使用 update()。

         import 'package:flutter/material.dart';
          import 'package:get/get.dart';
          
          import 'my_controller.dart';
          
          class NewHome extends StatefulWidget {
            int? num = 0;
          
            NewHome({
              Key? key,
              this.num,
            }) : super(key: key);
          
            @override
            _NewHomeState createState() => _NewHomeState();
          }
          
          class _NewHomeState extends State<NewHome> {
            final List<Map<String, dynamic>> _allCities = [
              {"id": 1, "city": "Delhi", "state": ""},
              {"id": 2, "city": "Agra", "state": "UP"},
              {"id": 3, "city": "Mumbai", "state": "Maharashtra"},
              {"id": 4, "city": "Jaipur", "state": "Rajasthan"},
              {"id": 5, "city": "Jodhpur", "state": "Rajasthan"},
              {"id": 6, "city": "Ranchi", "state": "Jharkhand"},
              {"id": 7, "city": "Dhanbad", "state": "Jharkhand"},
              {"id": 8, "city": "Kanpur", "state": "UP"},
              {"id": 9, "city": "Chandigarh", "state": "Punjab"},
              {"id": 10, "city": "Meerut", "state": "UP"},
            ];
          
           
          
            @override
            Widget build(BuildContext context) {
            Get.lazyPut(() => Controller());// this line you need to add in your second file
              return SafeArea(
                child: Scaffold(
                  backgroundColor: const Color(0xffEEEDEF),
                  body: Column(
                    children: [
                      Padding(
                        padding: const EdgeInsets.symmetric(vertical: 10.0),
                        child: Row(
                          children: [
                            IconButton(
                              icon: const Icon(Icons.arrow_back),
                              color: Colors.orange,
                              onPressed: () {
                                Navigator.pop(context);
                              },
                            ),
                            Container(
                              width: MediaQuery.of(context).size.width * 0.85,
                              height: 50.0,
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius:
                                      const BorderRadius.all(Radius.circular(5.0)),
                                  border: Border.all(color: Colors.blueAccent)),
                              child: TextField(
                                decoration: InputDecoration(
                                  hintText: "Enter Origin",
                                  border: InputBorder.none,
                                  contentPadding: const EdgeInsets.only(left: 10.0),
                                  hintStyle: TextStyle(
                                    fontSize: 15.0,
                                    color: Colors.grey[500],
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Align(
                        alignment: Alignment.centerLeft,
                        child: Padding(
                          padding: EdgeInsets.only(
                              left: MediaQuery.of(context).size.width * 0.04, top: 3.0),
                          child: Text(
                            'Popular Searches:',
                            style: TextStyle(
                                color: Colors.grey[500],
                                fontSize: MediaQuery.of(context).size.width * 0.035),
                          ),
                        ),
                      ),
                      Expanded(
                        child: ListView.builder(
                          itemCount: _allCities.length,
                          itemBuilder: (context, index) {
                            return InkWell(
                              onTap: () {
                                controller.increment();
                                if (widget.num == 1) {
                                  controller.updateDes(_allCities[index]['city']);
                                  Get.back();
                                } else if (widget.num == 2) {
                                  controller.updateDep(_allCities[index]['city']);
                                  Get.back();
                                } else {
                                  Get.back();
                                }
                              },
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    left: 18.0, top: 10.0, bottom: 15.0),
                                child: Text(
                                  _allCities[index]['city'],
                                  style: const TextStyle(
                                    color: Colors.black,
                                    fontSize: 15.0,
                                    fontWeight: FontWeight.normal,
                                  ),
                                ),
                              ),
                            );
                          },
                        ),
                      ),
                      Obx(
                        () => Text("${controller.count.value} cities are selected",
                            style: const TextStyle(fontSize: 20.0)),
                      )
                    ],
                  ),
                ),
              );
            }
          }
      

      请检查第二页代码,我现在做了一些更正,可能会正常工作。

      现在在第三页根据第二页可以更改。

      关于 Get-X 状态管理的主要内容:-

      1. 如果您使用的是 obx,则无需使用 update() 函数。
      2. 当您访问任何成员变量的值时,您需要使用.value。比如controller.count.value。
      3. 您需要在要使用 GetX 控制器类的任何屏幕中添加此行:- Get.lazyPut(() => Controller());此行将添加到 Scaffold return 语句之前。
      4. 仅使用 Obx() 包装您要在其中添加观察的小部件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-27
        • 1970-01-01
        • 1970-01-01
        • 2022-08-19
        相关资源
        最近更新 更多