8

我正在将我的应用程序重构为 GetX 状态管理,以减少样板代码。 我制作了控制器和 API 提供者(代码如下)。但是当我想刷新数据(手动)时它不会改变。

home_page.dart

class HomeUI extends GetView<HomeController> {
...
GetX<HomeController>(
                          initState: (state) => Get.find<HomeController>().getAll(),
                          builder: (_) {
                                    return _.goalList.length < 1 ||
                                            _.goalList == null
                                        ? Center(
                                            child: Column(
                                            mainAxisAlignment:
                                                MainAxisAlignment.center,
                                            children: [
                                              CircularProgressIndicator(),
                                              Text('0 goals found, please wait',
                                                  style: Theme.of(context)
                                                      .textTheme
                                                      .headline6
                                                      .copyWith(
                                                          color: kTextColor))
                                            ],
                                          ))
                                        : ListView.builder(
                                            itemBuilder: (context, index) {
                                            GoalModel goalModel =
                                                GoalModel.fromMap(
                                                    _.goalList[index]);

                                            return ListTile(
                                              title: Text(goalModel.text),
                                              subtitle:
                                                  Text(goalModel.updated_at),
                                            );
                                          });
}                                                                         

home_controller.dart

class HomeUI extends GetView<HomeController> {
...


class HomeController extends GetxController {
  final MyRepository repository = MyRepository();

  final _goalsList = RxList();
  get goalList => this._goalsList.value;
  set goalList(value) => this._goalsList.value = value;

  getAll() {
    repository.getAll().then((data) {
      this.goalList = data;
      update();
    });
  }

  delete(id) {
    repository.delete(id).then((message) {
      this.goalList;
      return message;
    });
  }

  add(goal) {
    repository.add(goal).then((data) {
      this.goalList = data;
    });
  }

  edit(editedItem, text, achievementDate) {
    repository.edit(editedItem, text, achievementDate).then((data) {
      this.goalList = data;
    });
  }
}                                                                       

目标存储库.dart

class MyRepository {
  final MyApiClient apiClient = MyApiClient();

  getAll() {
    return apiClient.getAll();
  }

  delete(id) {
    return apiClient.deleteGoal(id);
  }

  edit(editedItem, text, achievementDate) {
    return apiClient.updateGoal(editedItem, text, achievementDate);
  }

  add(goal) {
    return apiClient.postGoal(goal);
  }
}                                                                    

api.dart(getAll() 方法)

  getAll() async {
    try {
      var _token = await _sharedPrefsHelper.getTokenValue();

      var response = await httpClient.get(baseUrl, headers: {
        'Authorization': 'Bearer $_token',
      });
      if (response.statusCode == 200) {
        print('json decode response is: ${json.decode(response.body)}');

        return json.decode(response.body);
      } else
        print('erro -get');
    } catch (error) {
      print(error);
    }
  }

我按照这篇文章进行了实现: getx_pattern

4

4 回答 4

14

手动更新列表后,请执行以下操作:

this._goalsList.refresh()

之后,您的 UI 将被更新

于 2020-10-08T18:45:27.940 回答
7

只需使用ObxGetx包装ListView.builder列表。对于不在列表中的小部件,您可以使用 obx 或 getx 单独包装它们。

例子:

Obx(() => ListView.builder(
            physics: const NeverScrollableScrollPhysics(),
            itemCount: item.length,
            shrinkWrap: true,
            itemBuilder: (BuildContext context, int index) {
              return Card()...
            },
          ),
        ),
于 2020-12-25T19:23:02.980 回答
3

Obs Getx 变量仅在 Obx 或 Getx 中观察到,如上所述。你需要把它们包起来。请注意,当内部没有观察到变量时,不要使用 Obx / Getx,因为它会产生错误。

于 2020-12-29T18:58:20.513 回答
2

这个答案是针对@mjablecnik的评论:

class Other extends StatelessWidget {
  final Counter c = Get.find();
  final _chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
  final Random _rnd = Random();
  /* ---------------------------------------------------------------------------- */
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Obx(() => ListView.builder(
          scrollDirection: Axis.vertical,
          padding: EdgeInsets.all(10),
          itemCount: c.testList.length,
          itemBuilder: (context, index) => Card(
            color: Colors.amber[600],
            child: Padding(
              padding: const EdgeInsets.all(10),
              child: Center(
                child: Text('${c.testList[index]}'),
              ),
            ),
          ),
        )),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () => c.addToList(getRandomString(15)),
      ),
    );
  }
  /* ---------------------------------------------------------------------------- */
  // source: https://stackoverflow.com/questions/61919395/how-to-generate-random-string-in-dart
  String getRandomString(int length) => String.fromCharCodes(Iterable.generate(
      length, (_) => _chars.codeUnitAt(_rnd.nextInt(_chars.length))
    )
  );
}

更新1:

我做的另一个小改动是控制器:

class Counter extends GetxController {
  var count = 0.obs;
  var testList = <String>['test1', 'test2'].obs;
  /* ---------------------------------------------------------------------------- */
  void incremenent() => count++;
  /* ---------------------------------------------------------------------------- */
  void addToList(String item) {
    print('adding: $item');
    testList.add(item);
  }
}
于 2020-12-29T17:33:25.920 回答