DEV Community

Cover image for Data Transfer Between Fragment and BottomSheetDialogFragment Using Dagger and Navigation Component
Denis
Denis

Posted on • Updated on

Data Transfer Between Fragment and BottomSheetDialogFragment Using Dagger and Navigation Component

Data transfer between a Fragment and a BottomSheetDialogFragment can be effectively managed using Daggerand the Navigation Component, avoiding the use of data transfer through constructors or interfaces, as well as SharedViewModeland Hilt. This approach allows for a focus on dependency injection and state management through standard tools.


In our example, the key component is DaggerBottomSheetDialogFragment, which provides dependency injection and state management, offering flexibility and control over the process.


Using Dagger in this context allows for dependency injection, which opens up possibilities for extending functionality. When dependencies need to be injected into BottomSheetDialogFragment and other components of the application, Dagger helps maintain architectural cleanliness and flexibility.

Data Transfer
Data transfer between FirstFragment and SecondBottomSheetFragment is organized with a focus on bidirectional data flow as follows:
β€’ Sending Data: FirstFragment sends data to SecondBottomSheetFragmentusing the openBottomFragment method. This method sets the arguments and uses findNavController() for navigation.
β€’ Receiving Data: Values obtained from SecondBottomSheetFragment are observed in observeBackStack, where currentBackStackEntryFlow is used to track changes in the navigation stack state, followed by updating data in the ViewModel.
Let’s look at how this is implemented in code:


Note that in this example, the openBottomFragment method uses a check before performing a navigation action. This is necessary because rapid opening or closing of windows may result in an error related to the incorrect state of navigation. This error manifests as java.lang.IllegalArgumentException if the NavController attempts to perform navigation when the current fragment location does not support the transition.

Next, let’s consider the example in SecondBottomSheetFragment, where data from FirstFragment is received via initArgs, which initializes the ViewModel. The processed data is then sent back to FirstFragmentthrough the sendDataToParentFragment method. This method allows for updating the user interface in FirstFragment, ensuring it reflects the changes made in SecondBottomSheetFragment.



This example demonstrates how to use Dagger and the Navigation Component for managing state and transferring data between fragments and a BottomSheetDialogFragment. The complete code is available at the GitHub link.

Top comments (0)