Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Refresh the UI in ListView.Builder using flutter GetX when data is changed?

I'm refactoring my app to GetX state management for less boilerplate code. I make the Controller and the API provider (code below). But when I want to refresh the data (Manually too) it won't change.

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() method)

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

I followed this article to make the implementation: getx_pattern

like image 241
J.Maher Avatar asked Oct 07 '20 21:10

J.Maher


3 Answers

After updating manually your list, do:

this._goalsList.refresh()

After that your UI will be updated

like image 98
Eduardo Florence Avatar answered Sep 18 '22 12:09

Eduardo Florence


Just Wrap the ListView.builder list with Obx or Getx. For widgets that are not in the list, you can wrap them individually with obx or getx.

Example:

Obx(() => ListView.builder(
            physics: const NeverScrollableScrollPhysics(),
            itemCount: item.length,
            shrinkWrap: true,
            itemBuilder: (BuildContext context, int index) {
              return Card()...
            },
          ),
        ),
like image 34
Huseyin Ozsoy Avatar answered Sep 16 '22 12:09

Huseyin Ozsoy


Obs Getx variables are only observed within an Obx or Getx as stated above. You need to wrap them up. Just be careful not to use Obx / Getx when there are no variables observed inside, as it will generate an error.

like image 32
Eduardo Rodrigues Avatar answered Sep 16 '22 12:09

Eduardo Rodrigues