更改数据后如何使用Flutter GetX刷新ListView.Builder中的UI?

时间:2020-10-07 21:10:06

标签: flutter dart flutter-dependencies bloc state-management

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

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

goals_repository.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

3 个答案:

答案 0 :(得分: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);
  }
}

答案 1 :(得分:2)

Obs Getx 变量只能在 Obx 或 Getx 中观察到,如上所述。你需要把它们包起来。只是注意不要在内部没有观察到变量的情况下使用Obx / Getx,因为它会产生错误。

答案 2 :(得分:1)

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

this._goalsList.refresh()

之后,您的用户界面将被更新