Data update on Get.back () getx

0

Problem with updating data when going back.

Transition scheme:

ProfileView -> FollowingPersonalView -> ProfilePublicController -> FollowingPersonalView -> ProfilePublicController -> FollowingPersonalView

When going from ProfilePublicController -> FollowingPersonalView, I somehow managed to make the data update, although I'm not entirely sure I did it right.

But when you go back FollowingPersonalView -> ProfilePublicController -> FollowingPersonalView, the data at the last stage is not updated

Logically, they should be picked up from ProfileView

ProfileController

class ProfileController extends GetxController
    with SingleGetTickerProviderMixin {
  var isLoading = true.obs;
  var countPage = 0.obs;
  var profileData = UserModel().obs;
  TabController tabController;

  @override
  void onInit() {
    tabController = new TabController(length: 3, vsync: this);
    Future.wait([
      _apiGetProfile(),
    ]);
    super.onInit();
  }

  Future _apiGetProfile() async {
    try {
      isLoading(true);
      var profile = await RemoteServices.fetchProfile();
      if (profile != null) {
        profileData.value = profile;
      }
    } finally {
      isLoading(false);
    }
    update();
  }

  @override
  void onClose() {
    super.onClose();
  }
}

ProfileView

class ProfileView extends StatelessWidget {
  final _profileController = Get.put(ProfileController());

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      if (_profileController.isLoading.value) {
        return Center(child: CircularProgressIndicator());
      } else {
        return Scaffold(
            appBar: AppBar(
              leading: Obx(
                    () =>
                    Container(
                        margin: EdgeInsets.only(left: 13, top: 15),
                        alignment: Alignment.bottomLeft,
                        child: IconButton(
                          icon: Icon(MyFlutterApp.favorite_active,
                              color: Color(0xFFFE4E6A)),
                          onPressed: () {
                            Get.toNamed('/profile/favorites',
                                id: MainRoutesContext.Profile.index);
                          },
                        )
                    ),
              ),
              elevation: 0,
              backgroundColor: Color(0xFFFFFFFF),
              title: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Obx(
                        () =>
                        Text(
                          _profileController.profileData.value.userName
                              .toUpperCase(),
                          style: TextStyle(
                              fontFamily: 'Gilroy',
                              color: Color(0xFF333333),
                              fontWeight: FontWeight.w700,
                              fontStyle: FontStyle.normal,
                              height: 2.9,
                              fontSize: 18,
                              letterSpacing: 0.82),
                        ),
                  ),
                  Obx(() =>
                  _profileController.profileData.value.isConfirmed
                      ? Container(
                    margin: EdgeInsets.only(top: 17, left: 4),
                    child: Icon(MyFlutterApp.confirmed,
                        size: 14, color: Color(0xFF4CB3F5)),
                  )
                      : Container()),
                ],
              ),
              centerTitle: true,
              bottom: PreferredSize(
                  child: Container(
                    color: Color(0xFFE4E6EA),
                    height: 1.0,
                  ),
                  preferredSize: Size.fromHeight(1.0)),
            ),
            body: Container());
      }
    });
  }
}

FollowingController

class FollowingController extends GetxController {
  var isLoading = true.obs;
  var username;
  var data = [].obs;

  static FollowingController get to => Get.find();

  FollowingController() {
    apiGetFollowing();
  }

  @override
  void onInit() {
    super.onInit();
  }

  void apiGetFollowing() async {
    print(Get.previousRoute);
    try {
      username = Get
          .find<ProfilePublicController>()
          .profileData
          .value
          .userName;
    } catch (e) {
      username = Get
          .find<ProfileController>()
          .profileData
          .value
          .userName;
    }
    try {
      isLoading(true);
      Request request = Request(
          url: urlPublicFollowingsList.replaceAll('{username}', username),
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + box.read('token')
          });
      request.get().then((value) {
        Map<String, dynamic> map = json.decode(value.body);
        List response = map['data'];
        data.clear();
        data.assignAll(response.map((job) => UserModel.fromJson(job)).toList());
        data.refresh();
      }).catchError((onError) {});
    } finally {
      isLoading(false);
    }
    update();
  }

  @override
  void onClose() {
    super.onClose();
  }
}

FollowingPersonalView

class FollowingPersonalView extends StatelessWidget {


  final _followingController = Get.put(FollowingController());

  @override
  Widget build(BuildContext context) {
    double width = Get.width;
    return Scaffold(
        appBar: AppBar(
          leading: IconButton(
            tooltip: 'Previous choice',
            icon: Icon(MyFlutterApp.left, size: 20, color: Color(0xFFFE4E6A)),
            onPressed: () {
              Get.back(id: MainRoutesContext.Profile.index);
            },
          ),
          elevation: 0,
          backgroundColor: Color(0xFFFFFFFF),
          title: Obx(
                () =>
                RichText(
                    text: TextSpan(children: [
                      TextSpan(
                        text:
                        _followingController.data.length.toString() +
                            ' Following ',
                        style: TextStyle(
                          fontFamily: 'PTRoot',
                          fontSize: 18,
                          color: Color(0xFF254552),
                          fontStyle: FontStyle.normal,
                          letterSpacing: 0.53,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                      TextSpan(
                        text: _followingController.username,
                        style: TextStyle(
                          fontFamily: 'PTRoot',
                          fontSize: 18,
                          color: Color(0xFFFE4E6A),
                          fontStyle: FontStyle.normal,
                          letterSpacing: 0.53,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ])),
          ),
          centerTitle: true,
        ),
        body:
        new GestureDetector(
          onTap: () {
            FocusScope.of(context).requestFocus(new FocusNode());
          },
          child: Container(
            constraints: BoxConstraints.expand(),
            color: Color(0xFFFFFFFF),
            width: width,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Container(
                  height: 36,
                  margin: EdgeInsets.only(left: 20, right: 20, top: 9),
                  child: TextField(
                    controller: _followingController.searchController,
                    onSubmitted: (value) {},
                    decoration: InputDecoration(
                      filled: true,
                      fillColor: Color(0xFFF2F3F4),
                      labelText: 'Search for contests and other content',
                      labelStyle: TextStyle(
                        fontFamily: 'PTRoot',
                        fontSize: 16,
                        color: Color(0xFF929292),
                        fontStyle: FontStyle.normal,
                        letterSpacing: 0.13,
                        fontWeight: FontWeight.w400,
                      ),
                      suffixIcon: Icon(
                        MyFlutterApp.search,
                        size: 20,
                        color: Color(0xFF929292),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide:
                        BorderSide(color: Colors.transparent, width: 1.0),
                        borderRadius: BorderRadius.circular(6.0),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide:
                        BorderSide(color: Colors.transparent, width: 1.0),
                        borderRadius: BorderRadius.circular(6.0),
                      ),
                    ),
                  ),
                ),
                Expanded(
                    child: Obx(() =>
                        ListView.builder(
                            itemCount: _followingController.data.length,
                            itemBuilder: (context, index) =>
                                Container(
                                    margin: EdgeInsets.only(top: 20),
                                    child: Row(
                                      children: [
                                        Container(
                                          margin: EdgeInsets.only(left: 20),
                                          width: 40,
                                          height: 40,
                                          child: CircleAvatar(
                                            backgroundImage: NetworkImage(
                                                _followingController.data[index]
                                                    .image),
                                            radius: 50,
                                          ),
                                        ),
                                        InkWell(
                                          onTap: () {
                                            _followingController.username =
                                                _followingController
                                                    .data[index].userName;
                                            Get.toNamed('/profile/public',
                                                id: MainRoutesContext.Profile
                                                    .index);
                                          },
                                          child: Column(
                                            crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                            mainAxisAlignment: MainAxisAlignment
                                                .start,
                                            children: [
                                              Container(
                                                margin: EdgeInsets.only(
                                                    left: 10),
                                                child: Text(
                                                  _followingController
                                                      .data[index].userName,
                                                  style: TextStyle(
                                                    fontFamily: 'PTRoot',
                                                    fontSize: 18,
                                                    color: Color(0xFF333333),
                                                    fontStyle: FontStyle.normal,
                                                    letterSpacing: 0.53,
                                                    fontWeight: FontWeight.w500,
                                                  ),
                                                ),
                                              ),
                                              Container(
                                                  margin: EdgeInsets.only(
                                                      left: 10),
                                                  child: Text(
                                                    'Blogger',
                                                    style: TextStyle(
                                                      fontFamily: 'PTRoot',
                                                      fontSize: 14,
                                                      color: Color(0xFF777777),
                                                      fontStyle: FontStyle
                                                          .normal,
                                                      letterSpacing: 0.41,
                                                      fontWeight: FontWeight
                                                          .w500,
                                                    ),
                                                  )),
                                            ],
                                          ),
                                        ),
                                        Spacer(),
                                        Container(
                                            margin: EdgeInsets.only(right: 20),
                                            decoration: BoxDecoration(
                                              border: Border.all(
                                                  color: Color(0xFFF7537E),
                                                  width: 1),
                                              borderRadius: BorderRadius
                                                  .circular(8),
                                              color: Color(0xFFFE4E6A),
                                            ),
                                            width: width * 0.25,
                                            height: 37,
                                            child: new Row(
                                                crossAxisAlignment:
                                                CrossAxisAlignment.center,
                                                mainAxisAlignment:
                                                MainAxisAlignment.center,
                                                children: <Widget>[
                                                  Text(
                                                    'Following',
                                                    style: TextStyle(
                                                        fontFamily: 'PTRoot',
                                                        fontSize: 16,
                                                        fontStyle: FontStyle
                                                            .normal,
                                                        fontWeight: FontWeight
                                                            .w500,
                                                        color: Color(
                                                            0xFFFFFFFF)),
                                                  ),
                                                ])),
                                      ],
                                    )))))
              ],
            ),
          ),
        ));
  }
}

ProfilePublicController

    class ProfilePublicController extends GetxController
        with SingleGetTickerProviderMixin {
      var isLoading = true.obs;
      var profileData = UserModel().obs;
      var creatorData = List<CreatorListModel>().obs;
      var blogData = List<BlogModel>().obs;
      TabController tabController;
    
      @override
      void onInit() {
        tabController = new TabController(length: 4, vsync: this);
        try {
          Future.wait([
            _apiGetPublicProfile(Get
                .find<FollowerController>()
                .username),
          ]);
        } catch (e) {
          Future.wait([
            _apiGetPublicProfile(Get
                .find<FollowingController>()
                .username),
          ]);
        }
        super.onInit();
      }
    
      Future _apiGetPublicProfile(username) async {
        try {
          isLoading(true);
          var profile = await RemoteServices.fetchPublicProfile(username);
          if (profile != null) {
            profileData.value = UserModel.fromJson(profile['user']);
            List responseBlog = profile['blog']['data'];
            blogData.value =
                responseBlog.map((job) => BlogModel.fromJson(job)).toList();
            List responseChallenges = [profile['challenges']];
            creatorData.value = responseChallenges
                .map((job) => CreatorListModel.fromJson(job))
                .toList();
            await Get.find<BlogCardController>().apiGetBlogList();
            // List responseParticipant = [profile['participant']];
            // List responseJudge = [profile['judge']];
          }
        } finally {
          isLoading(false);
        }
        update();
      }
    
      @override
      void onClose() {
        super.onClose();
      }
    }

**PublicProfileView**

class PublicProfileView extends StatelessWidget {
  final _profilePublicController = Get.put(ProfilePublicController());

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      if (_profilePublicController.isLoading.value) {
        return Center(child: CircularProgressIndicator());
      } else {
        return Scaffold(
            appBar: AppBar(
              leading: Container(
                margin: EdgeInsets.only(left: 13, top: 15),
                alignment: Alignment.bottomLeft,
                child: IconButton(
                  icon: Icon(MyFlutterApp.left,
                      size: 18, color: Color(0xFFFE4E6A)),
                  onPressed: () {
                    Get.back(
                        id: MainRoutesContext.Profile.index, canPop: false);
                  },
                ),
              ),
              elevation: 0,
              backgroundColor: Color(0xFFFFFFFF),
              title: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Obx(
                        () =>
                        Text(
                          _profilePublicController.profileData.value.userName
                              .toUpperCase(),
                          style: TextStyle(
                              fontFamily: 'Gilroy',
                              color: Color(0xFF333333),
                              fontWeight: FontWeight.w700,
                              fontStyle: FontStyle.normal,
                              height: 2.9,
                              fontSize: 18,
                              letterSpacing: 0.82),
                        ),
                  ),
                  Obx(() =>
                  _profilePublicController.profileData.value.isConfirmed
                      ? Container(
                    margin: EdgeInsets.only(top: 17, left: 4),
                    child: Icon(MyFlutterApp.confirmed,
                        size: 14, color: Color(0xFF4CB3F5)),
                  )
                      : Container()),
                ],
              ),
              centerTitle: true,
              bottom: PreferredSize(
                  child: Container(
                    color: Color(0xFFE4E6EA),
                    height: 1.0,
                  ),
                  preferredSize: Size.fromHeight(1.0)),
            ),
            body: Container());
      }
    });
  }
}

How do I update the data on Get.back ()?

P.S. Is it possible to completely control the launch of the data retrieval function when opening the FollowingPersonalView page?

get: ^4.1.3 Flutter 2.0.4

flutter
getx
asked on Stack Overflow Apr 6, 2021 by Meekey

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0