我正在将我的应用程序重构为 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