<?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 Andrea Briasco on Medium]]></title>
        <description><![CDATA[Stories by Andrea Briasco on Medium]]></description>
        <link>https://medium.com/@andrea.briasco?source=rss-8a862b7c749e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*L_D_6oq48HPEPYxE</url>
            <title>Stories by Andrea Briasco on Medium</title>
            <link>https://medium.com/@andrea.briasco?source=rss-8a862b7c749e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 19:51:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andrea.briasco/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[The Power of State Management in React Native: A Guide to Redux]]></title>
            <link>https://insights.overapp.com/the-power-of-state-management-in-react-native-a-guide-to-redux-70afe48761a6?source=rss-8a862b7c749e------2</link>
            <guid isPermaLink="false">https://medium.com/p/70afe48761a6</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <dc:creator><![CDATA[Andrea Briasco]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 16:13:48 GMT</pubDate>
            <atom:updated>2024-02-12T10:47:40.190Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o7LwUDsojOoFT81jhWDstQ.png" /></figure><p><strong>Understanding the Need for State Management</strong></p><p>State management is a crucial aspect of any mobile application, including React Native applications.</p><p>It helps you maintain and organise the data in your app, making it more efficient and easier to maintain.</p><p>In this article, we will explore the importance of state management and walk through a step-by-step guide to implementing it using <a href="https://redux.js.org/"><strong>Redux</strong></a>, the renowned state management library, in a new React Native project.</p><p>In React Native, you deal with two main types of data:</p><ul><li><strong>Local State:</strong> Confined to individual components, with a limited scope, and remains isolated from other parts of the app.</li><li><strong>Global State:</strong> Holds data required across diverse app components or sections, including critical information like user authentication status, application settings, or data retrieved from a server.</li></ul><p>Efficiently managing global state is a complex challenge that necessitates a structured approach for consistent data handling.</p><p>Here, Redux shines by offering a streamlined method to manage global state, thus improving the maintainability and performance of React Native applications.</p><p><strong>Setting Up a React Native Project</strong></p><p><em>Creating a New Project</em></p><p>In order to implement Redux, we first set up a new project. Follow these steps to get started:</p><ol><li>Open your terminal and navigate to your desired directory.</li><li>Run the following command to create a new React Native project:</li></ol><pre>npx react-native init YourProjectName</pre><p>3. Replace <em>YourProjectName</em> with the desired name. This command will generate a new React Native project with the specified name.</p><p><em>Project Structure</em></p><p>Once the project is created, you will have a basic directory structure to work with.</p><p>I have created a very simple example with two screens: <strong>InputScreen</strong> and <strong>DisplayScreen</strong>.</p><p><strong>InputScreen</strong> will contain:</p><ul><li>A value that can be incremented or decremented between 0 and 10.</li><li>A reset button to reset the local value to 0.</li><li>A button to submit the value to Redux.</li><li>A button to navigate to DisplayScreen.</li></ul><p><strong>DisplayScreen</strong> will contain:</p><ul><li>A text element to display the retrieved counter value from Redux.</li><li>A button to reset the counter value in Redux back to its default.</li><li>A button to calculate the factorial of the counter in Redux.</li><li>A text element to display the factorial value after calculation.</li></ul><p><strong>Introducing Redux</strong></p><p>While passing data between components using props can suffice for simple data passing, it has limitations in more complex scenarios. This is particularly evident in cases of “prop drilling”, where props are solely utilised to pass data through multiple components with the sole purpose of reaching the final component in the hierarchy.</p><p>This can lead to tightly coupled components, convoluted data flows, and inefficient updates when dealing with larger projects. Here’s where Redux shines.</p><p>Redux, inspired by the Flux pattern, offers a streamlined approach to state management. It simplifies the process by introducing a single immutable state tree managed by a Redux store.</p><p>With Redux, state changes are triggered by actions. It enables you to maintain a global state accessible from anywhere in your app, reducing the complexity of passing data through multiple components and improves the overall efficiency of your application.</p><p>So let’s install the library and start using it.</p><p><strong>Implementing Redux Toolkit in Your Project</strong></p><p><em>Installing Redux Toolkit</em></p><p>In most scenarios, opting for Redux Toolkit instead of Redux vanilla is preferable as it enhances the setup process by providing built-in utilities for common Redux patterns, like slices for easier state management, enables immutable updates, integrates with Redux DevTools, and optimises performance. This makes it the preferred choice for efficient state management in React Native applications.</p><p>Begin by running the command below in your terminal:</p><pre>npm install @reduxjs/toolkit react-redux</pre><p>This will add Redux Toolkit and React-Redux as dependencies in your project. Now let’s also integrate the Redux Saga library to be able to manage side effects in our project by running the following command:</p><pre>npm install redux-saga</pre><p><em>Create a Redux Slice</em></p><p>A <strong>Redux Slice</strong> represents a portion of your application’s state. In Redux, it is common to divide your application’s state into multiple slices, each responsible for managing a particular piece of data or functionality. In our case, we will create a single slice to manage the state of our counter values.</p><p>Below is an example of how to create a Redux Slice for the counter.</p><pre>import {createSlice} from &#39;@reduxjs/toolkit&#39;;<br><br>const initialState = {<br>  counterValue: 0,<br>  factorialValue: 1,<br>};<br><br>const counterSlice = createSlice({<br>  name: &#39;counter&#39;,<br>  initialState,<br>  reducers: {<br>    setCounterValue: (state, action) =&gt; {<br>      state.counterValue = action.payload;<br>    },<br>    calculateFactorial: state =&gt; {<br>      // Calculate factorial<br>      let fact = 1;<br>      for (let i = 1; i &lt;= state.counterValue; i++) {<br>        fact *= i;<br>      }<br>      // Update factorial state value<br>      state.factorialValue = fact;<br>    },<br>  },<br>});<br><br>export const {setCounterValue, calculateFactorial} = counterSlice.actions;<br>export default counterSlice.reducer;</pre><p>Here we have defined the initial states of the counter, along with actions to update the counter value and calculate its factorial. The reducer function manages these actions to update the state values accordingly.</p><p>This slice will play a crucial role in managing our counter states within Redux.</p><p><em>Create Redux Saga</em></p><p><strong>Redux Sagas</strong> is a library designed for managing side effects, such as handling asynchronous API calls, complex workflows, and asynchronous actions.</p><p>While our project doesn’t involve actual API calls or complex operations, we will utilise Redux Sagas to simulate an asynchronous operation by adding a deliberate delay when saving the counter state value.</p><p>In the code below, we define the method responsible for handling the action, which will store the value passed into the counter slice.</p><pre>import {put, takeLatest} from &#39;redux-saga/effects&#39;;<br>import {setCounterValue} from &#39;../slices/counterSlice&#39;;<br><br>function* submitDataSaga(action) {<br>  try {<br>    // Simulate a delay and then dispatch the slice&#39;s action<br>    yield new Promise(resolve =&gt; setTimeout(resolve, 1000));<br>    yield put(setCounterValue(action.data));<br>  } catch (error) {<br>    console.log(error);<br>  }<br>}<br><br>export function* watchSubmitData() {<br>  yield takeLatest(&#39;SUBMIT_DATA&#39;, submitDataSaga);<br>}</pre><p>In the above code, we use the <em>takeLatest</em> effect provided by Redux Sagas which listens for a specific action type, ‘<em>SUBMIT_DATA</em>’ in this case, and automatically cancels any previous instances of the saga if they are still running.</p><p>It ensures that only the latest instance of the saga is active at any given time, which is particularly useful for scenarios where you may want to handle only the most recent action. This helps prevent race conditions and ensures that our application behaves predictably.</p><p>Next, let’s create a root saga and include the counter operation saga within it.</p><pre>import {all} from &#39;redux-saga/effects&#39;;<br>import {watchSubmitData} from &#39;./counterSaga&#39;;<br><br>export default function* rootSaga() {<br>  yield all([watchSubmitData()]);<br>}</pre><p>This setup enables Redux Sagas to effectively manage side effects in our project, even when simulating asynchronous operations.</p><p><em>Create the Redux Store</em></p><p>In this step, we will create the <strong>Redux Store</strong>, which serves as the central hub for managing application state.</p><p>The store holds the combined state from different slices into one root reducer, and it is configured to work seamlessly with Redux Sagas for handling side effects thanks to the saga middleware.</p><pre>import {combineReducers, configureStore} from &#39;@reduxjs/toolkit&#39;;<br>import createSagaMiddleware from &#39;redux-saga&#39;;<br>import counterReducer from &#39;../slices/counterSlice&#39;;<br>import rootSaga from &#39;../sagas/sagas&#39;;<br><br>const sagaMiddleware = createSagaMiddleware();<br><br>const rootReducer = combineReducers({<br>  counter: counterReducer,<br>});<br><br>const store = configureStore({<br>  reducer: rootReducer,<br>  middleware: getDefaultMiddleware =&gt;<br>    getDefaultMiddleware({thunk: false}).concat(sagaMiddleware),<br>});<br><br>sagaMiddleware.run(rootSaga);<br><br>export default store;</pre><p>By disabling <em>thunk</em>, we ensure that Redux Sagas exclusively handle side effects, simplifying the Redux setup. This ensures our Redux Store is fully prepared to manage both state changes and side effects effectively.</p><p><em>Connecting Redux to React Native Components</em></p><p>Wrap your application in the <strong>Redux Provider</strong>, passing in the store to make it available throughout your app.</p><pre>import React from &#39;react&#39;;<br>import Router from &#39;./js/src/navigation/Router&#39;;<br>import { Provider } from &#39;react-redux&#39;;<br>import store from &#39;./js/src/redux/store/store&#39;;<br><br>export const App = () =&gt; {<br>  return ( <br>  &lt;Provider store={store}&gt;<br>    &lt;Router /&gt;<br>  &lt;/Provider&gt; );<br>}</pre><p>Now that Redux is available in our application, we can start harnessing its power in our screen components.</p><pre>import React, {useState} from &#39;react&#39;;<br>import {useDispatch} from &#39;react-redux&#39;;<br><br>export default InputScreen = () =&gt; {<br>  const [value, setValue] = useState(0);<br>  const dispatch = useDispatch();<br>   <br>  const handleSubmitPress = () =&gt; {<br>    dispatch({type: &#39;SUBMIT_DATA&#39;, data: value});<br>  };<br><br>...</pre><p>In the <em>InputScreen</em> component, when a user interacts with the <em>Submit</em> button, it triggers the <em>handleSubmitPress</em> function. Within this function, we make use of the <em>useDispatch</em> hook provided by Redux, which plays a crucial role in initiating actions within the Redux state management system.</p><p>In our specific case, we are dispatching an action with the type ‘<em>SUBMIT_DATA</em>’ and including the <em>value</em> as the data payload. This action is essentially instructing Redux to update its state with the new value we wish to store globally.</p><p>Now, let’s retrieve and display the value in the <em>DisplayScreen</em> component.</p><pre>import React, {useState} from &#39;react&#39;;<br>import {useDispatch, useSelector} from &#39;react-redux&#39;;<br>import {<br>  calculateFactorial,<br>  setCounterValue,<br>} from &#39;../../redux/slices/counterSlice&#39;;<br><br>export default DisplayScreen = () =&gt; {<br>  const [showFactorial, setShowFactorial] = useState(false);<br><br>  const counter = useSelector(state =&gt; state.counter.counterValue);<br>  const factorial = useSelector(state =&gt; state.counter.factorialValue);<br>  const dispatch = useDispatch();<br>  <br>  const handleFactorialPress = () =&gt; {<br>    dispatch(calculateFactorial());<br>    setShowFactorial(true);<br>  };<br><br>  const handleResetPress = () =&gt; {<br>    dispatch(setCounterValue(0));<br>    setShowFactorial(false);<br>  };<br><br>...</pre><p>In the <em>DisplayScreen</em> component we use a local state variable <em>showFactorial</em>, which controls the display of the counter’s factorial value based on its boolean value.</p><p>To access the stored counter and factorial values from Redux, we utilise the <em>useSelector</em> hook. It enables us to retrieve the current values stored in the Redux store and assign it to the <em>counter</em> and the <em>factorial</em> variables.</p><p>The <em>handleFactorialPress</em> function dispatches an action to Redux, triggering the calculation of the factorial based on the current counter state value. Additionally, it updates the UI by toggling the boolean state to display the factorial value.</p><p>On the other hand, the <em>handleResetPress</em> function is responsible for resetting the displayed counter value. It dispatches an action to reset the counter value stored in Redux, and hides the factorial text in the UI.</p><p>It’s worth noting that for these functions, I have used the slice methods directly instead of utilising the saga. The reason behind this decision is to showcase the versatility of Redux and how it can adapt to different use cases.</p><p>Redux can handle simple state updates efficiently with the slice method while excelling at complex operations with sagas. It highlights how Redux adapts to different project requirements.</p><p><strong>Conclusion</strong></p><p>Redux simplifies the process when we require access to a state across multiple screens, as it maintains the state value consistently accessible throughout the entire app.</p><p>It is an essential tool in React Native development for maintaining organisation, efficiency, and maintainability of your applications. It offers a structured and powerful solution for state management.</p><p>By following this guide, you can seamlessly integrate Redux into your projects, gaining the benefits of predictability, centralised state management, and enhanced debugging capabilities.</p><p>I hope this article has been helpful for you to start your setup with Redux. If you found this information valuable, stay tuned for future updates.</p><p>If you’d like to explore the project used in this guide, you can find it on <a href="https://github.com/Andrea-B-90/GuideToRedux">GitHub</a>.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70afe48761a6" width="1" height="1" alt=""><hr><p><a href="https://insights.overapp.com/the-power-of-state-management-in-react-native-a-guide-to-redux-70afe48761a6">The Power of State Management in React Native: A Guide to Redux</a> was originally published in <a href="https://insights.overapp.com/">OverApp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigation in Flutter with AutoRoute]]></title>
            <link>https://insights.overapp.com/navigation-in-flutter-with-autoroute-4f4d40d95b65?source=rss-8a862b7c749e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f4d40d95b65</guid>
            <category><![CDATA[flutter-navigation]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Andrea Briasco]]></dc:creator>
            <pubDate>Mon, 29 May 2023 15:15:09 GMT</pubDate>
            <atom:updated>2023-05-29T15:24:19.262Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iEB3B7TdbRkmRcNmFZ1-Ng.png" /></figure><p><strong>Introduction</strong></p><p>Navigation is an essential aspect of an application because the vast majority of apps have multiple screens to show to the user and to make a great UX (User Experience) the navigation should be well managed and done properly.</p><p>In this article I am going to show you how to manage the navigation between a few simple screens, sending some data between them and managing the navigation stack to previous destinations.</p><p>To implement and use the navigation in Flutter can be done by using either the <strong><em>Navigator</em></strong> widget which comes without having to install any package, or installing one like <a href="https://pub.dev/packages/auto_route"><strong><em>AutoRoute</em></strong></a>.</p><p>Using an external package can be useful if you want more control over how routes are defined and managed in your app.</p><p><strong>Why AutoRoute?</strong></p><p><em>AutoRoute</em> is based on <strong>Navigator 2.0</strong>, a declarative API which sets the history stack of the <em>Navigator</em> and has a <em>Router</em> widget to configure the <em>Navigator</em> based on app state and system events.</p><p>I chose to install this package for the navigation which has some cool handy features.</p><blockquote>It allows for strongly-typed arguments passing, effortless deep-linking and it uses code generation to simplify routes setup, with that being said it requires a minimal amount of code to generate everything needed for navigation inside of your App.</blockquote><p><strong>Installation</strong></p><p>Before we start implementing the navigation’s logic we need to install the package in the <strong><em>pubspec.yaml</em></strong> file as shown below.</p><pre>dependencies:                    <br> auto_route: ^7.1.0                    <br>                   <br>dev_dependencies:                    <br>  auto_route_generator: ^7.0.0<br>  build_runner: ^2.4.4</pre><p>After adding the needed navigation dependency, sync your project or type below command in the terminal. Make sure you execute this command inside your project directory.</p><pre>flutter packages get</pre><p><strong>Setup</strong></p><p>To auto-generate the navigation we first need to create the <strong><em>router.dart</em></strong> file and put it in the <strong><em>lib</em></strong> directory, this is where all our code will be.</p><p>In it we create a <em>Router</em> class and annotate it with <em>@AutoRouterConfig</em> then extend <em>$YourClassName</em> and override the routes getter which contains a list of <em>AutoRoute</em> objects, this will wrap all our routes.</p><pre>@AutoRouterConfig()      <br>class AppRouter extends $AppRouter {      <br>   <br> @override      <br> List&lt;AutoRoute&gt; get routes =&gt; [      <br>    /// routes go here     <br>  ];    <br>}</pre><p>The <em>“$”</em> character on the extended class is needed to tell the library to generate that <em>Router</em> class for the navigation, while the annotation takes care of creating the navigation for each of the pages added in the array.</p><p><strong>Create the UI</strong></p><p>Now that the dependency setup is done we are going to compose three simple screen widgets in the <strong><em>lib</em></strong> directory.</p><p>The first screen represents the start destination and will have a button that takes us to the second screen, this one will have an up back button on the <em>AppBar</em> to navigate us back and a button which directs us to the third screen, the latter will have an up back button too and a button which navigates us to the first screen clearing the stack.</p><p>Let’s now put all of this in practice!</p><ul><li><em>First Screen</em></li></ul><pre>@RoutePage()<br>class FirstScreen extends StatefulWidget {<br>  const FirstScreen({super.key});<br><br>  @override<br>  State&lt;StatefulWidget&gt; createState() =&gt; _FirstScreenState();<br>}<br><br>class _FirstScreenState extends State&lt;FirstScreen&gt; {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        backgroundColor: Theme.of(context).colorScheme.inversePrimary,<br>        title: const Text(&quot;First Screen&quot;),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            Text(<br>              &quot;First Screen&quot;,<br>              style: Theme.of(context).textTheme.headlineMedium,<br>            )<br>          ],<br>        ),<br>      ),<br>      floatingActionButton: FloatingActionButton(<br>        child: const Icon(Icons.arrow_forward_ios),<br>        onPressed: () {      <br>          /// navigation goes here     <br>        },<br>      ),<br>    );<br>  }<br>}</pre><ul><li><em>Second Screen</em></li></ul><pre>@RoutePage()<br>class SecondScreen extends StatefulWidget {<br>  const SecondScreen({super.key});<br><br>  @override<br>  State&lt;StatefulWidget&gt; createState() =&gt; _SecondScreenState();<br>}<br><br>class _SecondScreenState extends State&lt;SecondScreen&gt; {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        backgroundColor: Theme.of(context).colorScheme.inversePrimary,<br>        title: const Text(&quot;Second Screen&quot;),<br>        automaticallyImplyLeading: false,<br>        leading: IconButton(<br>          icon: const Icon(Icons.arrow_back_ios),<br>          onPressed: () {      <br>            /// navigation goes here     <br>          },<br>        ),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            Text(<br>              &quot;Second Screen&quot;,<br>              style: Theme.of(context).textTheme.headlineMedium,<br>            ),<br>          ],<br>        ),<br>      ),<br>      floatingActionButton: FloatingActionButton(<br>        child: const Icon(Icons.arrow_forward_ios),<br>        onPressed: () {      <br>          /// navigation goes here     <br>        },<br>      ),<br>    );<br>  }<br>}</pre><ul><li><em>Third Screen</em></li></ul><pre>@RoutePage()<br>class ThirdScreen extends StatefulWidget {<br>  const ThirdScreen({super.key});<br><br>  @override<br>  State&lt;StatefulWidget&gt; createState() =&gt; _ThirdScreenState();<br>}<br><br>class _ThirdScreenState extends State&lt;ThirdScreen&gt; {<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        backgroundColor: Theme.of(context).colorScheme.inversePrimary,<br>        title: const Text(&quot;Third Screen&quot;),<br>        automaticallyImplyLeading: false,<br>        leading: IconButton(<br>          icon: const Icon(Icons.arrow_back_ios),<br>          onPressed: () {      <br>            /// navigation goes here     <br>          },<br>        ),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            Text(<br>              &quot;Third Screen&quot;,<br>              style: Theme.of(context).textTheme.headlineMedium,<br>            ),<br>          ],<br>        ),<br>      ),<br>      floatingActionButton: FloatingActionButton(<br>        child: const Icon(Icons.restart_alt),<br>        onPressed: () {      <br>          /// navigation goes here     <br>        },<br>      ),<br>    );<br>  }<br>}</pre><p>To generate the routes we annotated the widgets pages with <em>@RoutePage()</em> which allows them to be constructed by the router.</p><p>As you can see in the code above, in each page, I left the <strong><em>onPressed()</em></strong> block empty for each click events, we will add the code for the navigation in a moment.</p><p>Now simply run the generator with the following command which will generate a <strong><em>router.gr.dart</em></strong> file in your directory, this will handle the navigation for us.</p><pre>flutter packages pub run build_runner watch</pre><p>Note that in case you end up adding some new screens in your app after generating the file for the navigation, you just need to run the above command again to update that generated file, don’t forget to also declare the added screen with the <em>@RoutePage()</em> annotation.</p><p><strong>Finalise the setup</strong></p><p>Finally we can add the generated routes to the routes <em>List</em> we created earlier.</p><pre>@override<br>final List&lt;AutoRoute&gt; routes = [<br>  AutoRoute(page: FirstRoute.page, path: &#39;/&#39;),<br>  AutoRoute(page: SecondRoute.page),<br>  AutoRoute(page: ThirdRoute.page),<br>];</pre><p>Here the <em>“/”</em> character in the path for that route states that the page is used as the first screen by the <em>AutoRoute</em> package library.</p><p>The route names are auto-generated by the package, by default it replaces words like <em>“Page”</em> and <em>“Screen”</em> with <em>“Route”.</em></p><blockquote>e.g. FirstScreen would be FirstRoute</blockquote><blockquote>Auto generated route names can be a bit long with the Route suffix e.g. ProductDetailsPage would be ProductDetailsPageRoute<br>You can replace some relative parts in your route names by providing a replacement in the follow pattern <strong>whatToReplace,replacement</strong> what to replace and the replacement should be separated with a comma , e.g. ‘Page,Route’ so ProductDetailsPage would be ProductDetailsRoute<br>defaults to ‘Page|Screen,Route’, ignored if a route name is provided.</blockquote><p>There are two ways to decide our own names for the route pages.</p><ul><li>In the actual page, inside the <em>@RoutePage()</em> annotation, add the <em>name</em> attribute and set the name you prefer e.g. <strong><em>@RoutePage(name:“FirstScreen”)</em></strong>, this is the easiest way but it could be a bit repetitive when set on each screen page so let’s opt for the second way.</li><li>In the <strong><em>router.dart</em></strong> file, inside the <em>@AutoRouterConfig()</em> annotation, add the <em>replaceInRouteName</em> attribute and here is where the default value is <em>“Page|Screen,Route”</em>, that means if your pages name have either <em>“Page”</em> or <em>“Screen”</em> in it, this will be replaced with <em>“Route”</em>, so if we want to keep our route name we add the value <em>“Route,Page|Screen”</em> e.g. <strong><em>@AutoRouterConfig(replaceInRouteName: “Route,Page|Screen”)</em></strong>.</li></ul><p>We now refactor the route class with the pages name we decided, below is the final code.</p><pre>@AutoRouterConfig(replaceInRouteName: &quot;Route,Page|Screen&quot;)<br>class AppRouter extends $AppRouter {<br>  @override<br>  final List&lt;AutoRoute&gt; routes = [<br>    AutoRoute(page: FirstScreen.page, path: &#39;/&#39;),<br>    AutoRoute(page: SecondScreen.page),<br>    AutoRoute(page: ThirdScreen.page),<br>  ];<br>}</pre><p>To finalise the setup we need to hook the <em>MaterialApp</em> with the route class because this is where <em>AppRouter</em> is registered and the navigation is set.</p><pre>@override<br>  Widget build(BuildContext context) {<br>    return MaterialApp.router(<br>      routerConfig: _appRouter.config(),<br>      title: &quot;Flutter Navigation&quot;,<br>      debugShowCheckedModeBanner: false,<br>      theme: ThemeData(<br>        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>        useMaterial3: true,<br>      ),<br>    );<br>  }</pre><p><strong>Navigation in action</strong></p><p>The navigation is now ready to use so let’s implement the logic for the click events in the <strong><em>onPressed()</em></strong> empty block in each page.</p><p>Let’s start the flow from the first screen.</p><pre>floatingActionButton: FloatingActionButton(<br>        child: const Icon(Icons.arrow_forward_ios),<br>        onPressed: () {<br>          AutoRouter.of(context).push(<br>            SecondRoute(title: &quot;Second Screen&quot;),<br>          );<br>        },<br>      ),</pre><p>As you can see in the code above, to make the navigation in action with the <em>FloatingActionButton</em> we created, we used the <em>AutoRouter</em> object and called the <strong><em>push()</em></strong> method and passed in the screen route destination we want to navigate to.</p><p>That method, as the word suggests, pushes the destination on top of the current one, this creates a stack in the navigation.</p><p>To notice that we also passed a title as a <em>String</em> argument so that our second screen will receive and use it as the text title for that page.</p><p>In the second screen we handle the passed argument in the class constructor, then when we need it we just reference the <em>widget</em> instance to set the <em>Text</em> in the <em>AppBar</em>.</p><pre>/// ...<br><br>final String title;<br><br>const SecondScreen({super.key, required this.title});<br><br>/// ...<br><br>appBar: AppBar(<br>        backgroundColor: Theme.of(context).colorScheme.inversePrimary,<br>        title: Text(widget.title),<br>        automaticallyImplyLeading: false,<br>        leading: IconButton(<br>          icon: const Icon(Icons.arrow_back_ios),<br>          onPressed: () {<br>            AutoRouter.of(context).pop();<br>          },<br>        ),<br>      ),<br><br>/// ...<br><br>floatingActionButton: FloatingActionButton(<br>        child: const Icon(Icons.arrow_forward_ios),<br>        onPressed: () {<br>          AutoRouter.of(context).push(<br>            ThirdRoute(title: &quot;Third Screen&quot;),<br>          );<br>        },<br>      ),</pre><p>For the back navigation we used an <em>IconButton </em>in the <em>AppBar </em>and called the <strong><em>pop()</em></strong> method on the <em>AutoRouter</em> object, this handles clearing the navigation stack and navigate us back to the previous screen.<br>While the forward <em>FloatingActionButton</em> navigates us to the next page.</p><p>In the third screen we handle the logic for the up back button as we did before, it takes us to the second page.</p><pre>floatingActionButton: FloatingActionButton(<br>        child: const Icon(Icons.restart_alt),<br>        onPressed: () {<br>          AutoRouter.of(context).popUntilRoot();<br>        },<br>      ),</pre><p>While on the <em>FloatingActionButton</em>, as you can see above, we used <strong><em>popUntilRoot()</em></strong> which clears all the navigation stack, this takes us to the first page since the stack got cleared out and that one was the very first destination we defined in the list of routes.</p><p><strong>Wrapping up</strong></p><p>We just arrived at the end of this article, I showed you a quick intro about the navigation in <em>Flutter</em> and how to setup the <strong><em>AutoRoute</em></strong> package library, how to name the route pages as you prefer, we handled argument-passing in navigation and learned how to manage the stack and clearing it completely to make the navigation directing us to the very first screen page.</p><p>Thank you for reading my article, I hope it was helpful for you and that you liked it.</p><p>Many thanks to my colleague <a href="https://medium.com/@franceska.leskaj">Franceska</a> for designing and drawing the lovely illustration at the top of my article.</p><p>Until the next one, Cheers! 😁✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f4d40d95b65" width="1" height="1" alt=""><hr><p><a href="https://insights.overapp.com/navigation-in-flutter-with-autoroute-4f4d40d95b65">Navigation in Flutter with AutoRoute</a> was originally published in <a href="https://insights.overapp.com/">OverApp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>