<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ahmed Khater on Medium]]></title>
        <description><![CDATA[Stories by Ahmed Khater on Medium]]></description>
        <link>https://medium.com/@khater?source=rss-a34b0a8166a9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*cT_m5ujyeEgaGJtO</url>
            <title>Stories by Ahmed Khater on Medium</title>
            <link>https://medium.com/@khater?source=rss-a34b0a8166a9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:25:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khater/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Navigation in Jetpack compose.Advanced Full guide passing arguments — Clean Architecture .]]></title>
            <link>https://medium.com/@khater/navigation-in-jetpack-compose-advanced-full-guide-passing-arguments-clean-architecture-f264f2f5ff0a?source=rss-a34b0a8166a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f264f2f5ff0a</guid>
            <dc:creator><![CDATA[Ahmed Khater]]></dc:creator>
            <pubDate>Sun, 14 Jan 2024 17:37:10 GMT</pubDate>
            <atom:updated>2024-01-14T17:40:47.091Z</atom:updated>
            <content:encoded><![CDATA[<h3>Navigation in Jetpack compose , Advanced Full guide passing arguments — Clean Architecture .</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*slizRKssniaUeKeMkrnv1Q.png" /></figure><h4>Certainly! Here’s a breakdown of key points about Navigation in Jetpack Compose:</h4><h3><strong>1. Understanding App Flow:</strong></h3><ul><li>Navigation in Jetpack Compose is essential for comprehending how your app transitions between different composables, forming the overall flow of the user experience.</li></ul><h3><strong>2. Android Jetpack Navigation in Compose:</strong></h3><ul><li>Android Jetpack Navigation seamlessly integrates with Jetpack Compose, offering a streamlined approach to handling high-level navigation within your Compose-based application.</li></ul><h3><strong>3. Navigation Component Components:</strong></h3><h4><strong>Navigation Graph:</strong></h4><ul><li>Acts as a consolidated resource containing all navigation-related data, <br> including destinations (locations in the app) and possible user paths.</li><li>Functions like a comprehensive map and guide, outlining the various places users can navigate within the app.</li></ul><h4><strong>NavHost:</strong></h4><ul><li>A unique composable that integrates into your layout and displays destinations from the Navigation Graph.</li><li>Links the NavController with the navigation graph, specifying the composable destinations available for navigation.</li><li>As users move between composables, the content of the NavHost is automatically recomposed.</li></ul><h4><strong>NavController:</strong></h4><ul><li>Serves as the central API for the Navigation component in Compose.</li><li>Maintains the state of the navigation, including the back stack of composables representing the screens in your app.</li><li>Tracks the state of each screen, ensuring a coherent navigation experience.</li></ul><h3>4. Navigation in Jetpack Compose Applications:</h3><ul><li>The Navigation component extends its support to Jetpack Compose applications, allowing developers to navigate between composables while leveraging the infrastructure and features provided by the Navigation component.</li></ul><p>To get started with navigation in Jetpack Compose, you need to include the required dependencies in your project’s build.gradle file:</p><pre>    // Navigation<br>    implementation(&quot;androidx.navigation:navigation-compose:2.7.6&quot;)</pre><p>Update the gradle dependencies , simply add hilt to the list of repositories in your main build.gradle file:</p><pre>    id(&quot;com.google.dagger.hilt.android&quot;) version &quot;2.44&quot; apply false</pre><p>In your app/build.gradle file, add the dependencies for hilt:</p><pre>plugins {<br>    ...<br>    id(&quot;kotlin-kapt&quot;)<br>    id(&quot;com.google.dagger.hilt.android&quot;)<br>}<br><br>// Dagger - Hilt<br>    implementation(&quot;com.google.dagger:hilt-android:2.48&quot;)<br>    kapt(&quot;com.google.dagger:hilt-android-compiler:2.48&quot;)<br>    kapt(&quot;androidx.hilt:hilt-compiler:1.1.0&quot;)<br>    implementation(&quot;androidx.hilt:hilt-navigation-compose:1.1.0&quot;)</pre><p>creata app class in <strong>package</strong> <strong>com.example.youApp</strong> for HiltAndroidApp to complete hilt setup</p><pre>import android.app.Application<br>import dagger.hilt.android.HiltAndroidApp<br><br>@HiltAndroidApp<br>class WoolApplication:Application()</pre><p>add app class to android manifest</p><pre> &lt;application  <br>        ...<br>        android:name=&quot;.WoolApplication&quot;<br>        ...<br>/&gt;</pre><p>Create <strong>presentation</strong> package that contains our UI , then on the presentation package create <strong>navigation</strong> package that contains <strong>Screen routes </strong>and<strong> </strong>our<strong> NavGraph:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*m1nx5UgwREKsxx-PBvGvXQ.png" /></figure><p><strong>Screen</strong> class is a sealed class contains all screens <strong>routes</strong> that we have in our app:</p><pre><br>sealed class Screen(val route: String) {<br><br>    /*<br>    * here i have three screens ...<br>    * In details screen we will pass ID to fetch all data about the wool.<br>    * after passing ID we will get it from details screen viewModel to hit API with the specific ID<br>    *  */<br>    data object HomeScreen : Screen(&quot;HomeScreen&quot;)<br>    data object SettingScreen : Screen(&quot;SettingScreen&quot;)<br><br>    data object DetailsScreen : Screen(&quot;DetailsScreen/{$WOOL_DETAILS_ID}&quot;) {<br>        fun passId(id: String): String {<br>            return this.route.replace(oldValue = &quot;{$WOOL_DETAILS_ID}&quot;, newValue = id)<br>        }<br>    }<br>}</pre><p>On presentation package we will create <strong>screens</strong> package that contains all composables screens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*yH1mXWGdS_m0wd5xreR1bA.png" /></figure><p>On screens package we will create package for each screen and each package contains <strong>[ composable screen — screen route function — screen viewModel ]</strong> so lets check each file of the screens package.</p><p><strong>1 — Screen as composable DetailsScreen for example:</strong></p><pre>@Composable<br>fun DetailsScreen(<br>    navController: NavController,<br>    detailsScreenViewModel: DetailsViewModel = hiltViewModel()<br>) {<br>    val args = detailsScreenViewModel.args<br><br>    Box(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .background(Color.Yellow.copy(0.5f)),<br>        contentAlignment = Alignment.Center<br>    ) {<br>        Text(<br>            text = &quot;Details Screen&quot;,<br>            fontSize = 25.sp,<br>            color = Color.Black,<br>            modifier = Modifier.align(<br>                Alignment.TopCenter<br>            )<br>        )<br>        Text(<br>            text = args,<br>            fontSize = 25.sp,<br>            color = Color.Black,<br>            modifier = Modifier.align(<br>                Alignment.Center<br>            )<br>        )<br><br>        Button(<br>            onClick = { navController.navigate(Screen.SettingScreen.route) },<br>            modifier = Modifier<br>                .align(<br>                    Alignment.BottomCenter<br>                )<br>                .padding(bottom = 50.dp)<br>        ) {<br>            Text(text = &quot;Navigate to setting screen&quot;, fontSize = 18.sp, color = Color.Black)<br>        }<br>    }<br>}</pre><p>on homeScreen constructor we passed <strong>navController to navigate to </strong>every screen we need and <strong>homeViewModel </strong>for preparing and managing the data for an screen</p><p><strong>2 — viewModel for details screen:</strong></p><pre>@HiltViewModel<br>class DetailsViewModel @Inject constructor(<br>    savedStateHandle: SavedStateHandle<br>):ViewModel() {<br>    /* this is ID that we send it to details screen<br>       so we acn hit the API to get all wool details.<br>       make args as private but i make it public to print it in details screen when navigate<br>     */<br>     val args: String = checkNotNull(savedStateHandle[WOOL_DETAILS_ID]?:&quot;&quot;)<br>    /*<br>    * complete your code here with your useCases like that<br>    * getWoolDetailsUseCase.invoke(args) -&gt; this useCase used to get all wool details.<br>    * you can check the code here of my wool app.<br>    * but API not working currently<br>    * */<br><br>}</pre><p>we use <strong>savedStateHandle</strong> to get the ID that we passed to details screen and use this <strong>ID</strong> to get data by hit the API use your <strong>useCase</strong></p><p><strong>3 — DetailsScreenRoute this is extention function from NavGraphBuilder that contains <em>composable Screen</em></strong></p><pre>fun NavGraphBuilder.detailsScreenRoute(navController: NavController){<br>    composable(Screen.DetailsScreen.route){<br>        DetailsScreen(navController = navController)<br>    }<br>}</pre><ol><li>fun NavGraphBuilder.detailsScreenRoute(navController: NavController):</li></ol><ul><li>This is a function definition named detailsScreenRoute that is an extension function on NavGraphBuilder.</li><li>NavGraphBuilder is a builder class for constructing navigation graphs in Jetpack Compose.</li></ul><p>2. composable(Screen.DetailsScreen.route) { ... }:</p><ul><li>Inside the function, there is a call to the composable function. This function is used to define a composable screen within the navigation graph.</li><li>Screen.DetailsScreen.route represents the route or destination associated with the DetailsScreen. It seems to be part of a sealed class or an enum class (Screen), where each screen has an associated route.</li></ul><p>3. DetailsScreen(navController = navController):</p><ul><li>This line is creating an instance of the DetailsScreen composable.</li><li>It passes the navController as a parameter to the DetailsScreen. The navController is typically used within the composable to handle navigation actions, allowing the composable to navigate to other screens.</li></ul><p>create another package named utilities that contains all constants of UI like <strong>WOOL_DETAILS_ID</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*KeQYBfmFaVzo5qDTs3Freg.png" /></figure><pre>object Constants {<br>    /*<br>     * the id of wool that we will send it to the destination<br>     * the wool is my app that fetch wallpapers<br>     * check the link here https://youtu.be/H1pRm24x5iA?si=x9rJeWhCkgVdy42D<br>     */<br>    const val WOOL_DETAILS_ID = &quot;woolId&quot;<br>}</pre><p>Here we will pass any ID to details Screen from any screen</p><pre>@Composable<br>fun HomeScreen(navController: NavController,homeViewModel: HomeViewModel= hiltViewModel()) {<br>    Box(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .background(Color.Red.copy(0.5f)),<br>        contentAlignment = Alignment.Center<br>    ) {<br>        Text(text = &quot;Home Screen&quot;, fontSize = 25.sp, color = Color.Black, modifier = Modifier.align(<br>            Alignment.Center))<br>        Button(onClick = { navController.navigate(Screen.DetailsScreen.passId(&quot;7&quot;)) }, modifier = Modifier<br>            .align(<br>                Alignment.BottomCenter<br>            )<br>            .padding(bottom = 50.dp)) {<br>            Text(text = &quot;Navigate to details screen&quot;, fontSize = 18.sp, color = Color.Black)<br>        }<br>    }<br>}</pre><p>Finally we will create <strong>WoolApp</strong> that contains WoolNavGraph and call WoolApp on <strong>MainActivity</strong></p><pre>@Composable<br>fun WoolApp() {<br>    val navController = rememberNavController()<br>    WoolNavGraph(navController)<br>}</pre><pre>@AndroidEntryPoint<br>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            NavigationCleanarchTheme {<br>                // A surface container using the &#39;background&#39; color from the theme<br>                Surface(<br>                    modifier = Modifier.fillMaxSize(),<br>                    color = MaterialTheme.colorScheme.background<br>                ) {<br>                    WoolApp()                }<br>            }<br>        }<br>    }<br>}</pre><p>we add @AndroidEntryPoint for dagger setup …</p><p>you can check that <br><a href="https://github.com/khaatteerr/Navigation-Clean-Arch">https://github.com/khaatteerr/Navigation-Clean-Arch</a> <br><a href="https://www.youtube.com/@khatteeeer_Dev/videos">https://www.youtube.com/@khatteeeer_Dev/videos</a><br><a href="https://www.linkedin.com/in/khateer/">https://www.linkedin.com/in/khateer/</a></p><h3>Final result..</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*m2yaXFOiSr7C5PvHK7OFFg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f264f2f5ff0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swipeable Component with Jetpack Compose | swipe to delete or archive]]></title>
            <link>https://medium.com/@khater/swipeable-component-with-jetpack-compose-swipe-to-delete-or-archive-debfe4503613?source=rss-a34b0a8166a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/debfe4503613</guid>
            <dc:creator><![CDATA[Ahmed Khater]]></dc:creator>
            <pubDate>Wed, 26 Apr 2023 10:02:23 GMT</pubDate>
            <atom:updated>2023-04-26T10:02:23.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K0gDu1apMl_IFbiyCQAptQ.png" /></figure><p>Flixability is a mobile app designed to give you complete control over your chat experience. With its intuitive user interface and easy-to-use features, Flixability offers a smooth and enjoyable messaging experience that you won’t find anywhere else.</p><p>One of the standout features of Flixability is its easy animation for swipe to delete chat, powered by Jetpack Compose. With a simple swipe, you can quickly and easily delete individual chats, making it easier to keep your chat list organized and clutter-free.</p><p>Using Jetpack Compose, Flixability’s swipe-to-delete animation is both smooth and responsive, providing a seamless experience that feels natural and intuitive. With just a few swipes, you can declutter your chat list and focus on the conversations that matter most.</p><p>Overall, Flixability offers a feature-rich messaging experience that combines functionality, usability, and style, all in one convenient app. Whether you’re looking for a messaging app that’s easy to use, packed with features, or just want to try out Jetpack Compose in action, Flixability has everything you need and more.</p><h3>The final result | Video</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*PjEbEkikfXnzmK_VKZGA0A.gif" /><figcaption>swipe to delete item form list</figcaption></figure><p>The drawable<strong> </strong><a href="https://drive.google.com/drive/folders/1ldyB1G1j8AmBqgPrtOvKRf7yMS0sg0ul?usp=share_link"><strong>files </strong></a>and font i used tap the “files ” to get data</p><h3>Step 1 — Update the gradle dependencies</h3><p>simply add hilt to the list of repositories in your main build.gradle file:</p><pre>plugins {<br>...<br>id &#39;com.google.dagger.hilt.android&#39; version &#39;2.44&#39; apply false<br>}</pre><p>In your app/build.gradle file , Add swipe dependency and sync gradle</p><pre>plugins {<br>...<br>    id &#39;kotlin-kapt&#39;<br>    id &#39;com.google.dagger.hilt.android&#39;<br>}<br><br>dependencies {<br>...<br>  //Swipe<br>    implementation &quot;me.saket.swipe:swipe:1.1.1&quot;<br><br>   //hilt<br>    implementation &#39;androidx.hilt:hilt-navigation-compose:1.0.0&#39;<br>    implementation &quot;com.google.dagger:hilt-android:2.44&quot;<br>    kapt &quot;com.google.dagger:hilt-compiler:2.44&quot;<br><br>}<br><br></pre><h3>Step 2 — creata app class for HiltAndroidApp</h3><pre>@HiltAndroidApp<br>class Yourpplication:Application()</pre><h3>Step 3 — add app class to android manifest</h3><pre>&lt;application<br>...<br>    android:name=&quot;.YourApplication&quot;<br>...<br> /&gt;</pre><p><strong><em>*</em>After adding files and font to font directory,</strong> <strong>create Font File on ui package.</strong></p><pre>val Ubuntu = FontFamily(<br>    Font(R.font.ubuntu_bold, weight = FontWeight.Bold)<br>)</pre><p>After sync gradle ,now let’s create ChatCardItemContent that contains</p><p>1-image</p><p>2–messengerName</p><p>3–message</p><p>4–messageDate</p><p>5-messageNumberBadge</p><p>6-id</p><blockquote><strong>create data class that contains all data</strong></blockquote><pre>data class ChatCardItemContent(<br>    val id:Int = 0,<br>    val image : Int,<br>    val messengerName:String,<br>    val message:String,<br>    val messageDate:String,<br>    val messageNumberBadge:Int = 0<br>)</pre><blockquote>Now we will create design for chatCardItem with compose</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*00QjC0BQiLyJSph6dvuhRw.jpeg" /></figure><blockquote>This card contains <strong><em>Row </em></strong>and this row has<strong> <em>Box </em></strong>for image , <strong><em>Column </em></strong>for messenger name and message and other <strong><em>Column </em></strong>for message date and messageNumberBadge , so let’s go</blockquote><pre>@Composable<br>fun ChatCardItem(<br>    chatCardItem: ChatCardItemContent,<br> ) {<br>    Row(<br>        verticalAlignment = Alignment.CenterVertically,<br>        horizontalArrangement = Arrangement.Start,<br>        modifier = Modifier<br>            .fillMaxWidth()<br>            .height(80.dp)<br>            .padding(start = 16.dp, end = 16.dp)<br>            .clickable { /* navigate to chat*/ }<br>    ) {<br>        Box(<br>            Modifier<br>                .size(50.dp)<br>                .clip(CircleShape)<br>         ) {<br>            Image(<br>                painter = painterResource(id = chatCardItem.image),<br>                contentDescription = &quot;Messenger image&quot;,<br>                contentScale = ContentScale.Crop<br>            )<br>        }<br><br>        Column(<br>            horizontalAlignment = Alignment.Start,<br>            verticalArrangement = Arrangement.spacedBy(5.dp),<br>            modifier = Modifier<br>                .padding(horizontal = 10.dp)<br>                .weight(1f)<br>        ) {<br>            Text(<br>                text = chatCardItem.messengerName,<br>                fontSize = 15.sp,<br>                fontFamily = Ubuntu,<br>                fontWeight = FontWeight.Bold,<br><br>                )<br>            Text(<br>                text = chatCardItem.message,<br>                fontSize = 12.sp,<br>                fontWeight = FontWeight.Light,<br><br>                )<br>        }<br><br>        Column(<br>            horizontalAlignment = Alignment.End,<br>            verticalArrangement = Arrangement.Center<br>        ) {<br>            Text(<br>                text = chatCardItem.messageDate,<br>                fontFamily = Ubuntu,<br>                fontSize = 12.sp,<br>                fontWeight = FontWeight.Thin<br>            )<br>            if (chatCardItem.messageNumberBadge &gt; 0) {<br>                Box(<br>                    modifier = Modifier<br>                        .padding(top = 10.dp)<br>                        .size(25.dp)<br>                        .clip(CircleShape)<br>                        .background(Color(0xFFEF5350)),<br>                    contentAlignment = Alignment.Center<br>                ) {<br>                    Text(<br>                        text = chatCardItem.messageNumberBadge.toString(),<br>                        fontSize = 12.sp,<br>                        fontFamily = Ubuntu,<br>                        color = Color.White,<br>                        fontWeight = FontWeight.Thin<br>                    )<br>                }<br>            }<br>        }<br><br>    }<br>}</pre><p><strong>we need to provide the data for cards so we need</strong></p><blockquote>1-uiState</blockquote><blockquote>2-view model</blockquote><p><strong>[uiState] </strong>Now we will create data class <strong>ChatScreenUiState </strong>that contains list of ChatCardItemContent</p><pre>data class ChatScreenUiState(<br>    val messages:List&lt;ChatCardItemContent&gt; = emptyList()<br>)</pre><p><strong>[view model] </strong>we create view model to update state of data</p><pre>class HomeViewModel @Inject constructor(): ViewModel() {<br><br>    private val _state = MutableStateFlow(ChatScreenUiState())<br>    val state = _state.asStateFlow()<br><br>    init {<br>        getMessages()<br>    }<br><br>    private fun getMessages() {<br>        _state.update {<br>            it.copy(<br>                messages = listOf(<br>                    ChatCardItemContent(<br>                        1,<br>                        R.drawable.person1,<br>                        &quot;Ahmed Khater&quot;,<br>                        &quot;Yes, that&#39;s gonna work, hopefully&quot;,<br>                        &quot;15:12&quot;,<br>                        2<br>                    ),<br>                    ChatCardItemContent(<br>                        2,<br>                        R.drawable.pesron2,<br>                        &quot;Krishna Barbe&quot;,<br>                        &quot;Hello guys, we have discussed about...&quot;,<br>                        &quot;12:00&quot;<br>                    ),<br>                    ChatCardItemContent(<br>                        3,<br>                        R.drawable.person3,<br>                        &quot;Eshan Terrel&quot;,<br>                        &quot;Thanks dude ☻&quot;,<br>                        &quot;10:17&quot;<br>                    ),<br>                    ChatCardItemContent(<br>                        4,<br>                        R.drawable.person4,<br>                        &quot;Beck Bowes&quot;,<br>                        &quot;You can new method...&quot;,<br>                        &quot;Yesterday&quot;,<br>                        3<br>                    ),<br>                    ChatCardItemContent(<br>                        5,<br>                        R.drawable.person5,<br>                        &quot;Cameron Williamson&quot;,<br>                        &quot;Voice message&quot;,<br>                        &quot;Yesterday&quot;<br>                    ),<br>                    ChatCardItemContent(<br>                        6,<br>                        R.drawable.person6,<br>                        &quot;Eleanor Pena&quot;,<br>                        &quot;Voice message&quot;,<br>                        &quot;2 Days Ago&quot;<br>                    ),<br>                    ChatCardItemContent(<br>                        7,<br>                        R.drawable.person7,<br>                        &quot;Tyra Dhillon&quot;,<br>                        &quot;Good morning.&quot;,<br>                        &quot;4 Days Ago&quot;<br>                    ),<br>                    ChatCardItemContent(<br>                        8,<br>                        R.drawable.person8,<br>                        &quot;Sia&quot;,<br>                        &quot;Voice message&quot;,<br>                        &quot;4 Days Ago&quot;<br>                    ),<br>                    ChatCardItemContent(<br>                        9,<br>                        R.drawable.person3,<br>                        &quot;Eshan Terrel&quot;,<br>                        &quot;Thanks dude ☻&quot;,<br>                        &quot;10:17&quot;<br>                    ),<br>                    ChatCardItemContent(<br>                        10,<br>                        R.drawable.person4,<br>                        &quot;Beck Bowes&quot;,<br>                        &quot;You can new method...&quot;,<br>                        &quot;Yesterday&quot;,<br>                        3<br>                    ),<br>                    ChatCardItemContent(<br>                        11,<br>                        R.drawable.person5,<br>                        &quot;Cameron Williamson&quot;,<br>                        &quot;Voice message&quot;,<br>                        &quot;Yesterday&quot;<br>                    ),<br>                    ChatCardItemContent(<br>                        12,<br>                        R.drawable.person6,<br>                        &quot;Eleanor Pena&quot;,<br>                        &quot;Voice message&quot;,<br>                        &quot;2 Days Ago&quot;<br>                    ),<br>                )<br>            )<br>        }<br>    }<br><br>    fun onSwipeToDelete(selectedMessage: ChatCardItemContent) {<br>        _state.update {<br>            it.copy(<br>                messages = it.messages.filterNot { message -&gt;<br>                    message.id == selectedMessage.id<br>                }<br>            )<br>        }<br>    }<br><br>    fun onSwipeToArchive(selectedMessage: ChatCardItemContent) {<br>        _state.update {<br>            it.copy(<br>                messages = it.messages.filterNot { message -&gt;<br>                    message.id == selectedMessage.id<br>                }<br>            )<br>        }<br>    }<br><br>}</pre><p><strong>filterNot </strong>is a function that returns a list containing all elements not matching the given…</p><p>You can use any function or any way to update state, When the list is large, it is recommended to use random access collections</p><p><strong>On home screen or MainActivity you can create composable function to view list of cards</strong></p><p>on this section we will create two SwipeActions</p><p>1 — for delete</p><p>2 — for archive</p><p>1 — The onSwipe function is a callback that is triggered when the user performs a swipe gesture on the SwipeAction component. It is used to define what happens when the user swipes in a particular direction, such as deleting an item, archiving a message, or marking a task as complete.</p><p>2 — threshold: This parameter specifies the minimum amount of drag distance required to trigger the swipe action. It is a fraction of the box width, so a value of 0.5 means the user needs to drag the item halfway across the box to trigger the swipe action. You can set the threshold value by passing it as a parameter to the SwipeableActionsBox component.</p><p>3 — startActions: This parameter specifies the set of actions that should be triggered when the user starts to swipe the item. These actions are typically used to display additional information or options related to the item. You can define the start actions by passing them as a lambda function to the startActions parameter of the SwipeableActionsBox component.</p><p>4 — endActions: This parameter specifies the set of actions that should be triggered when the user completes the swipe action. These actions are typically used to perform a specific action on the item, such as deleting it or marking it as read. You can define the end actions by passing them as a lambda function to the endActions parameter of the SwipeableActionsBox component.</p><pre>@Composable<br>fun ChatCardSection(<br>    chatCardItems: ChatScreenUiState,<br>    onSwipeToDelete: (ChatCardItemContent) -&gt; Unit<br>) {<br><br><br>    LazyColumn(Modifier.fillMaxSize()) {<br><br>        items(chatCardItems.messages) {<br>            val delete = SwipeAction(<br>                onSwipe = {<br>                    onSwipeToDelete(it)<br>                    Log.d(&quot;OnSwipeToDelete&quot;, chatCardItems.messages.size.toString())<br>                },<br>                icon = {<br>                    Icon(<br>                        Icons.Default.Delete,<br>                        contentDescription = &quot;Delete chat&quot;,<br>                        modifier = Modifier.padding(16.dp),<br>                        tint = Color.White<br>                    )<br>                }, background = Color.Red.copy(alpha = 0.5f),<br>                isUndo = true<br>            )<br>            val archive = SwipeAction(<br>                onSwipe = {},<br>                icon = {<br>                    Icon(<br>                        painterResource(id = R.drawable.baseline_archive_24),<br>                        contentDescription = &quot;archive chat&quot;,<br>                        modifier = Modifier.padding(16.dp),<br><br>                        tint = Color.White<br><br>                    )<br>                }, background = Color(0xFF50B384).copy(alpha = 0.7f)<br>            )<br>            SwipeableActionsBox(<br>                modifier = Modifier,<br>                swipeThreshold = 200.dp,<br>                startActions = listOf(archive),<br>                endActions = listOf(delete)<br>            ) {<br>                ChatCardItem(it)<br>            }<br><br>        }<br>    }<br><br><br>}</pre><p>I will create <strong>HOME SCREEN </strong>composable that contains <strong>ChatCardSection</strong></p><pre>@Composable<br>fun HomeScreen(<br>    homeViewModel: HomeViewModel = hiltViewModel()<br>) {<br>     val state by homeViewModel.state.collectAsState()<br>    HomeContent(state, homeViewModel::onSwipeToDelete)<br>}<br><br>@Composable<br>private fun HomeContent(<br>    state: ChatScreenUiState,<br>    onSwipeToDelete: (ChatCardItemContent) -&gt; Unit,<br>   ) {<br>    Column(<br>        Modifier<br>          .fillMaxSize()<br>           ) {<br>       <br>        ChatCardSection(<br>            state, onSwipeToDelete <br>        )<br>    }<br><br>}</pre><p><strong>Finally call HomeScreen on MainActivity…</strong></p><pre>@AndroidEntryPoint<br>class MainActivity : ComponentActivity() {<br><br>      override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        WindowCompat.setDecorFitsSystemWindows(window, false)<br><br>        setContent {<br>            YourTheme  {<br>                HomeScreen()<br>            }<br>        }<br><br>    }<br>}</pre><p><strong>Follow for more</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=debfe4503613" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dark mode on android with jetpack compose using dataStore with hilt]]></title>
            <link>https://medium.com/@khater/dark-mode-on-android-with-jetpack-compose-using-datastore-bb2a1eff5565?source=rss-a34b0a8166a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb2a1eff5565</guid>
            <dc:creator><![CDATA[Ahmed Khater]]></dc:creator>
            <pubDate>Mon, 24 Apr 2023 16:11:16 GMT</pubDate>
            <atom:updated>2023-04-25T10:57:35.321Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction:</h3><p>“Dark mode” is a feature that has been gaining popularity in recent years, as it reduces eye strain and improves battery life. With Jetpack Compose, developers can easily implement dark theme in their Android applications. In this article, we’ll explore how to create a dark theme in Android using Jetpack Compose, and the benefits it provides to users. We’ll also discuss the steps involved in creating a dark theme, and how it can be customized to suit your application’s needs. So, whether you’re a beginner or an experienced developer, this guide will help you create a sleek and stylish dark theme for your Android application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mQCfsqZPZs6J_vWtrHqfVA.png" /><figcaption>this is final result to switch theme</figcaption></figure><p>The final result | Video</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*3gYgsxRaS4uvb7_OjlJcqw.gif" /></figure><h3>Step 1 — Update the gradle dependencies</h3><p>Hilt and dataStore dependencies are available via Google’s new Maven repository, simply add it to the list of repositories in your main build.gradle file:</p><pre>plugins {<br>   <br>    id &#39;com.google.dagger.hilt.android&#39; version &#39;2.44&#39; apply false<br>}</pre><p>In your app/build.gradle file, add the dependencies for hilt and dataStore</p><pre>plugins {<br>    ...<br><br>    id &#39;kotlin-kapt&#39;<br>    id &#39;com.google.dagger.hilt.android&#39;<br>}<br><br>dependencies {<br><br>  //hilt<br>    implementation &#39;androidx.hilt:hilt-navigation-compose:1.0.0&#39;<br>    implementation &quot;com.google.dagger:hilt-android:2.44&quot;<br>    kapt &quot;com.google.dagger:hilt-compiler:2.44&quot;<br><br>    // data store<br>    implementation &quot;androidx.datastore:datastore-preferences:1.0.0&quot;<br>}</pre><h3>Step 2 — creata app class for HiltAndroidApp</h3><pre>@HiltAndroidApp<br>class Yourpplication:Application()</pre><h3>Step 3 — add app class to android manifest</h3><pre>&lt;application<br>...<br>    android:name=&quot;.YourApplication&quot;<br>...<br> /&gt;</pre><h3>Step 4 — create app module class</h3><p>we need dependency injection to provide context for create dataStore</p><pre><br>@Module<br>@InstallIn(SingletonComponent::class)<br>class AppModule {<br><br>     @Provides<br>     fun provideDataStoreUtil(@ApplicationContext context:  Context):DataStoreUtil = DataStoreUtil(context)<br><br> }</pre><h3>Step 5 — create DataStoreUtil class to create <em>preferences</em> dataStore</h3><pre>class DataStoreUtil @Inject constructor(context: Context) {<br><br>    val dataStore = context.dataStore<br><br>    companion object {<br>        private val Context.dataStore: DataStore&lt;Preferences&gt; by preferencesDataStore(&quot;settings&quot;)<br>        val IS_DARK_MODE_KEY = booleanPreferencesKey(&quot;dark_mode&quot;)<br>    }<br>}</pre><h3>Step 6— create data class for ThemeState</h3><pre>data class ThemeState(val isDarkMode: Boolean)</pre><h3>Step 7 — create ThemeViewModel to handle dark mode state</h3><pre>@HiltViewModel<br>class ThemeViewModel @Inject constructor(dataStoreUtil: DataStoreUtil) : ViewModel() {<br><br>    private val _themeState = MutableStateFlow(ThemeState(false))<br>    val themeState: StateFlow&lt;ThemeState&gt; = _themeState<br><br>    private val dataStore = dataStoreUtil.dataStore<br><br>    init {<br>        viewModelScope.launch(Dispatchers.IO) {<br>            dataStore.data.map { preferences -&gt;<br>                ThemeState(preferences[IS_DARK_MODE_KEY] ?: false)<br>            }.collect {<br>                _themeState.value = it<br>            }<br>        }<br><br>    }<br><br>    fun toggleTheme() {<br>        viewModelScope.launch(Dispatchers.IO) {<br>            dataStore.edit { preferences -&gt;<br>                preferences[IS_DARK_MODE_KEY] = !(preferences[IS_DARK_MODE_KEY] ?: false)<br>            }<br>        }<br>    }<br><br><br>}</pre><h3>Step 8 — create custom Switch to choose the mode you need</h3><p>this CustomSwitch has a nice view you can see video below</p><pre>@Composable<br>fun CustomSwitch(<br>    width: Dp = 45.dp,<br>    height: Dp = 30.dp,<br>    checkedTrackColor: Color = Color(0xFF50B384).copy(alpha = 0.7f),<br>    uncheckedTrackColor: Color = Color(0xFFe0e0e0),<br>    gapBetweenThumbAndTrackEdge: Dp = 4.dp,<br>    borderWidth: Dp = 2.dp,<br>    cornerSize: Int = 50,<br>    iconInnerPadding: Dp = 4.dp,<br>    thumbSize: Dp = 20.dp,<br>    themeViewModel: ThemeViewModel = hiltViewModel(),<br>) {<br><br><br>    // this is to disable the ripple effect<br>    val interactionSource = remember {<br>        MutableInteractionSource()<br>    }<br><br><br>    val themeState by themeViewModel.themeState.collectAsState()<br><br><br>    // for moving the thumb<br>    val alignment by animateAlignmentAsState(<br>        if (themeState.isDarkMode<br>        ) 1f else -1f<br>    )<br><br>    Box(<br>        modifier = Modifier<br>            .animateContentSize(<br>                animationSpec = spring(<br>                    dampingRatio = Spring.DampingRatioHighBouncy,<br>                    stiffness = Spring.StiffnessMediumLow<br>                )<br>            ), contentAlignment = Alignment.CenterEnd<br>    ) {<br>        Text(<br>            text = if (themeState.isDarkMode<br>            ) &quot;ON&quot; else &quot;OFF&quot;,<br>            fontFamily = Ubuntu,<br>            fontWeight = FontWeight.SemiBold,<br><br>            modifier = Modifier,<br><br>            )<br>    }<br>    SpacerHorizontal16()<br>    // outer rectangle with border<br>    Box(<br>        modifier = Modifier<br>            .size(width = width, height = height)<br>            .border(<br>                width = borderWidth,<br>                color = if (themeState.isDarkMode<br>                ) checkedTrackColor else uncheckedTrackColor,<br>                shape = RoundedCornerShape(percent = cornerSize)<br>            )<br>            .clickable(<br>                indication = null,<br>                interactionSource = interactionSource<br>            ) {<br>                themeViewModel.toggleTheme()<br><br>            },<br>        contentAlignment = Alignment.Center<br>    ) {<br><br>        // this is to add padding at the each horizontal side<br>        Box(<br>            modifier = Modifier<br>                .padding(<br>                    start = gapBetweenThumbAndTrackEdge,<br>                    end = gapBetweenThumbAndTrackEdge<br>                )<br>                .fillMaxSize(),<br>            contentAlignment = alignment<br>        ) {<br><br>            // thumb with icon<br>            Icon(<br>                if (themeState.isDarkMode<br>                ) painterResource(id = R.drawable.night_mode) else painterResource(id = R.drawable.light_mode),<br>                contentDescription = if (themeState.isDarkMode) &quot;Enabled&quot; else &quot;Disabled&quot;,<br>                modifier = Modifier<br>                    .size(size = thumbSize)<br>                    .background(<br>                        color = if (themeState.isDarkMode) checkedTrackColor else uncheckedTrackColor,<br>                        shape = CircleShape<br>                    )<br>                    .padding(all = iconInnerPadding),<br>                tint = Color.Black<br>            )<br>        }<br>    }<br><br>    // gap between switch and the text<br>    Spacer(modifier = Modifier.height(height = 16.dp))<br><br><br>}<br></pre><h3>Step 9 — update theme from view model theme</h3><pre>@Composable<br>fun ComposeCourseTheme(<br>    themeViewModel: ThemeViewModel = hiltViewModel(),<br>     // Dynamic color is available on Android 12+<br>    dynamicColor: Boolean = true,<br>    content: @Composable () -&gt; Unit<br>) {<br>    val themeState by themeViewModel.themeState.collectAsState()<br><br><br>    val colorScheme = when {<br>        dynamicColor &amp;&amp; Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.S -&gt; {<br>            val context = LocalContext.current<br>            if (themeState.isDarkMode) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)<br>        }<br><br>        themeState.isDarkMode -&gt; DarkColorScheme<br>        else -&gt; LightColorScheme<br>    }<br>    val view = LocalView.current<br><br>    if (!view.isInEditMode) {<br>        SideEffect {<br>            val window = (view.context as Activity).window<br>            window.statusBarColor = Color.Transparent.toArgb()<br><br>//            WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = false<br>        }<br>    }<br><br>    MaterialTheme(<br>        colorScheme = colorScheme,<br>        typography = Typography,<br>        content = content<br>    )<br>}</pre><p>Now you can switch theme as you like and save theme state on dataStore</p><h3>Follow for more</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb2a1eff5565" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>