Johntopia
Johntopia

Reputation: 353

Flutter GetX state management with navigation

Summary

I am currently building an app using Flutter with the help of the get package.

I cannot fully explain the current issue with only words, so I will make use of visual aids.

The below image shows the user flow of what's going on, with numbers indicating the order of the interaction/status.

Current status

Code

The below snippets are essential parts of what I think might be the key to a solution.

post_page.dart

class PostPage extends StatelessWidget {
  final pId = Get.parameters['post_id'];
  if(pId != null) {
    return GetX<PostController>(
      init: PostPageController(pId: pId),
      builder: (controller) => InformationAboutPostView(),
    );
  } else {
    return UnknownPostView();
  }
}

post_page_controller.dart

class PostPageController extends GetxController {
  final String pId;
  PostPageController({required this.pId});

  @override
  void onInit() {
    post.bindStream(PostRepo.stream(pId));
    super.onInit();
  }

  Rx<Post> post = Rx(Post.empty);
}

Things I know

  1. The parameter is being delivered with no problemo.
  2. The getxcontroller seems to stay in the memory, unless the page injected with it is being popped from the navigation stack.

Final questions from my investigations

Upvotes: 0

Views: 925

Answers (1)

Hooman
Hooman

Reputation: 793

Cleaner approach is to not reuse the controller, instead use tag property to create controller related to specific post.

to put controller releated to postA:

Get.put(PostPageController(), tag: postA.id);

and to find the controller

Get.find<PostPageController>(tag: postA.id);

if you are using GetView you can override tag getter

Upvotes: 1

Related Questions