<?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 Ali Akber on Medium]]></title>
        <description><![CDATA[Stories by Ali Akber on Medium]]></description>
        <link>https://medium.com/@ali852609?source=rss-5882a491e8e5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Se9qScx8_2geEdJnCGdRBw.jpeg</url>
            <title>Stories by Ali Akber on Medium</title>
            <link>https://medium.com/@ali852609?source=rss-5882a491e8e5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 12:40:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ali852609/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[Making a Flutter Application with CLEAN ARCHITECTURE — Part3]]></title>
            <link>https://medium.com/@ali852609/making-a-flutter-application-with-clean-architecture-part3-cbd52907eb77?source=rss-5882a491e8e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbd52907eb77</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Ali Akber]]></dc:creator>
            <pubDate>Sun, 05 Jan 2025 09:43:17 GMT</pubDate>
            <atom:updated>2025-01-05T09:43:17.567Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making a Flutter Application with CLEAN ARCHITECTURE — Part3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kyD-ZdZlLAjo5ZPe2GI9zA.png" /></figure><p>Hello and welcome! This is part 3 and the final part of the tutorial series “Making a Flutter Application with CLEAN ARCHITECTURE”.<br>If you haven’t already completed part 1 and 2 please do so before reading this article!<br><a href="https://medium.com/@ali852609/making-a-flutter-application-with-clean-architecture-part1-f42b93431924">Part1</a><br><a href="https://medium.com/@ali852609/making-a-flutter-application-with-clean-architecture-part2-1424a4c97e03">Part 2</a></p><p>In parts 1 and 2 of the article, we have created the Data Layer and the Domain Layer. In part 3, we will work with the presentation layer and combine all of it together.</p><p>Let’s first start by verifying all the code we wrote till now works. Generally, I’d also write unit tests along with the code. But here for the sake of keeping the tutorial short, I did not add any. However, we will write some e2e test to verify everything we wrote till now works! We’ll only test the happy path.</p><p>One thing I forgot to add in the previous parts, is the dio configurations. We need to have the base URL and content type to make requests to OpenWeather API. We also set network timeout durations in this file. Create a new file under the folder <strong>core/data/network/ </strong>named <strong>config.dart</strong> and paste the following code</p><pre>import &#39;package:dio/dio.dart&#39;;<br><br>const int _networkTimeoutDurationSeconds = 10;<br>const String _baseUrl = &quot;https://api.openweathermap.org/data/2.5/&quot;;<br>const String _contentTypeJson = &quot;application/json&quot;;<br><br>/// Here we could change the baseUrl based on the<br>/// BuildMode of the app or the Flavor<br>/// baseUrl: (kDebugMode) ? _stagingUrl : _prodUrl<br>/// For the sake of simplicity I&#39;m using only the<br>/// Production url here<br>BaseOptions configureDio() {<br>  final options = BaseOptions(<br>    baseUrl: _baseUrl,<br>    contentType: _contentTypeJson,<br>    responseType: ResponseType.json,<br>    sendTimeout: const Duration(seconds: _networkTimeoutDurationSeconds),<br>    receiveTimeout: const Duration(seconds: _networkTimeoutDurationSeconds),<br>  );<br><br>  return options;<br>}</pre><p>We have pretty much everything ready for the e2e test. Let’s start with the Dependency Injection to put everything we built till now, together. We will be using the <a href="https://pub.dev/packages/get_it">get_it</a> package for dependency management. So let’s add it to our project with the following command.</p><pre>flutter pub add get_it</pre><p>Create a new file under the<strong> lib/</strong> folder named <strong>di/di.dart </strong>and paste the following content.</p><pre>import &#39;package:dio/dio.dart&#39;;<br>import &#39;package:get_it/get_it.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/data/mapper/exception_to_error_mapper.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/data/network/dio_configuration.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/data/network/dio_network_client.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/data/network/network_client.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/data/mapper/current_weather_entity_mapper.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/data/mapper/current_weather_entity_mapper_impl.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/data/network_source/current_weather_network_source.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/data/network_source/current_weather_network_source_impl.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/data/repository/current_weather_repository_impl.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/domain/repository/current_weather_reository.dart&#39;;<br><br>final getIt = GetIt.I;<br><br>Future&lt;void&gt; setup() async {<br>  getIt.registerLazySingleton&lt;Dio&gt;(<br>    () =&gt; Dio(<br>      configureDio(),<br>    ),<br>  );<br>  getIt.registerLazySingleton&lt;NetworkClient&gt;(<br>    () =&gt; DioNetworkClient(<br>      getIt.get(),<br>    ),<br>  );<br>  getIt.registerLazySingleton&lt;CurrentWeatherNetworkSource&gt;(<br>    () =&gt; CurrentWeatherNetworkSourceImpl(<br>      getIt.get(),<br>    ),<br>  );<br>  getIt.registerLazySingleton&lt;ExceptionToErrorMapper&gt;(<br>    () =&gt; ExceptionToErrorMapperImpl(),<br>  );<br>  getIt.registerLazySingleton&lt;CurrentWeatherEntityMapper&gt;(<br>    () =&gt; CurrentWeatherEntityMapperImpl(),<br>  );<br>  getIt.registerLazySingleton&lt;CurrentWeatherRepository&gt;(<br>    () =&gt; CurrentWeatherRepositoryImpl(<br>      getIt.get(),<br>      getIt.get(),<br>      getIt.get(),<br>    ),<br>  );<br>}</pre><p>As you can see in this file we are putting all of it together. We initialized instances of the classes as lazy singletons. This ensures the objects get created only when we need them, and throughout the app there is only a single instance used.</p><p>Now it’s time to test. Create a new file under the lib folder named <strong>e2e.dart </strong>and paste the following code</p><pre>import &#39;package:weather_clean_architecture_flutter/di/di.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/domain/entity/current_weather_entity.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/domain/repository/current_weather_reository.dart&#39;;<br><br>void main() async {<br>  await setup();<br>  final CurrentWeatherRepository repository = getIt.get();<br><br>  final result = await repository.getCurrentWeather(<br>    lat: 20.3,<br>    lon: 14.9,<br>    units: MeasurementUnit.metric,<br>  );<br><br>  print(result);<br>}</pre><p>In this file we have a main function which calls the setup function from the di.dart file. This ensures we have registered all the required dependencies. Then we get an instance of the repository from getIt and call getCurrentWeather() . If you check the result that is printed to the console or if you put a debugger breakpoint in the print statement, you will be able to see that the result contains a list of WeatherEntity . Which is what we want!</p><p>Finally, it’s time to get started with the presentation layer. We will start by creating a UI model and a mapper.</p><p>First, create a new folder named <strong>model/ </strong>under <strong>features/presentation/ </strong>and create a new file inside the <strong>model/</strong> folder named <strong>current_weather_ui_model.dart. </strong>Paste the following content inside this file.</p><pre>import &#39;package:equatable/equatable.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/domain/entity/current_weather_entity.dart&#39;;<br><br>class CurrentWeatherUiModel extends Equatable {<br>  final String dayNameFull;<br>  final String dayNameShort;<br>  final String temp;<br>  final String tempMin;<br>  final String tempMax;<br>  final String tempMinByTempMax;<br>  final String pressure;<br>  final String humidity;<br>  final String partOfDay;<br>  final String weatherCondition;<br>  final String description;<br>  final String smallIcon;<br>  final String bigIcon;<br>  final String windSpeed;<br>  final MeasurementUnit measurementUnit;<br>  final String temperatureUnit;<br><br>  const CurrentWeatherUiModel({<br>    required this.dayNameFull,<br>    required this.dayNameShort,<br>    required this.temp,<br>    required this.tempMin,<br>    required this.tempMax,<br>    required this.tempMinByTempMax,<br>    required this.pressure,<br>    required this.humidity,<br>    required this.partOfDay,<br>    required this.weatherCondition,<br>    required this.description,<br>    required this.smallIcon,<br>    required this.bigIcon,<br>    required this.windSpeed,<br>    required this.measurementUnit,<br>    required this.temperatureUnit,<br>  });<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [<br>        dayNameFull,<br>        dayNameShort,<br>        temp,<br>        tempMin,<br>        tempMax,<br>        tempMinByTempMax,<br>        pressure,<br>        humidity,<br>        partOfDay,<br>        weatherCondition,<br>        description,<br>        smallIcon,<br>        bigIcon,<br>        windSpeed,<br>        measurementUnit,<br>        temperatureUnit,<br>      ];<br>}</pre><p>We will be using this class to show different informations in our widgets. This class contains all the information in a pre-formatted way so that the widgets can use them without any modification. We will use a mapper class to map a CurrentWeatherEntity object of domain layer into a CurrentWeatherUiModel object of UI Layer.</p><p>Create another folder named <strong>mapper/ </strong>inside <strong>features/presentation/ </strong>and create a new file inside <strong>mapper/</strong> folder named <strong>current_weather_entity_to_ui_model_mapper.dart</strong>. Paste the following code inside this file.</p><pre>import &#39;package:equatable/equatable.dart&#39;;<br>import &#39;package:intl/intl.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/domain/entity/current_weather_entity.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/model/current_weather_ui_model.dart&#39;;<br><br>abstract class CurrentWeatherEntityToUiModelMapper {<br>  CurrentWeatherUiModel map(CurrentWeatherEntity entity);<br>}<br><br>const _fullNameFormat = &quot;EEEE&quot;;<br>const _shortNameFormat = &quot;EEE&quot;;<br>const _humidityUnit = &quot;%&quot;;<br>const _pressureUnit = &quot;hPa&quot;;<br>const _windSpeedUnitMetric = &quot;m/s&quot;;<br>const _windSpeedUnitImperial = &quot;mph&quot;;<br>const _imageScalingSmall = &quot;@2x&quot;;<br>const _imageScalingLarge = &quot;@4x&quot;;<br>const _celsiusUnit = &quot;°C&quot;;<br>const _fahrenheitUnit = &quot;°F&quot;;<br>const _imageBaseUrl = &quot;https://openweathermap.org/img/wn/&quot;;<br>const _imageExt = &quot;.png&quot;;<br><br>class CurrentWeatherEntityToUiModelMapperImpl<br>    implements CurrentWeatherEntityToUiModelMapper {<br>  @override<br>  CurrentWeatherUiModel map(CurrentWeatherEntity entity) {<br>    return CurrentWeatherUiModel(<br>      dayNameFull: _getDayNameFromTimeStamp(<br>        entity.dateTime,<br>        _fullNameFormat,<br>      ),<br>      dayNameShort: _getDayNameFromTimeStamp(<br>        entity.dateTime,<br>        _shortNameFormat,<br>      ),<br>      temp: &quot;${entity.temp.toStringAsFixed(2)}°&quot;,<br>      tempMin: &quot;${entity.tempMin.toStringAsFixed(2)}°&quot;,<br>      tempMax: &quot;${entity.tempMax.toStringAsFixed(2)}°&quot;,<br>      pressure: &quot;${entity.pressure} $_pressureUnit&quot;,<br>      humidity: &quot;${entity.humidity} $_humidityUnit&quot;,<br>      partOfDay: entity.partOfDay,<br>      weatherCondition: entity.weather.isNotEmpty ? entity.weather[0].name : &quot;&quot;,<br>      description:<br>          entity.weather.isNotEmpty ? entity.weather[0].description : &quot;&quot;,<br>      smallIcon: entity.weather.isNotEmpty<br>          ? _getWeatherImageIcon(entity.weather[0].icon, _imageScalingSmall)<br>          : &quot;&quot;,<br>      bigIcon: entity.weather.isNotEmpty<br>          ? _getWeatherImageIcon(entity.weather[0].icon, _imageScalingLarge)<br>          : &quot;&quot;,<br>      windSpeed: _getWindSpeedWithUnit(entity.speed, entity.unit),<br>      measurementUnit: entity.unit,<br>      temperatureUnit: _getMeasurementUnit(entity.unit),<br>    );<br>  }<br><br>  static String _getWindSpeedWithUnit(double windSpeed, MeasurementUnit unit) {<br>    final speed = windSpeed.toStringAsFixed(2);<br>    if (unit == MeasurementUnit.metric) {<br>      return &quot;$speed $_windSpeedUnitMetric&quot;;<br>    }<br>    return &quot;$speed $_windSpeedUnitImperial&quot;;<br>  }<br><br>  static String _getDayNameFromTimeStamp(int timestamp, String format) {<br>    DateTime date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);<br>    return DateFormat(format).format(date);<br>  }<br><br>  static String _getWeatherImageIcon(String imageIcon, String imageScaling) {<br>    return &quot;$_imageBaseUrl$imageIcon$imageScaling$_imageExt&quot;;<br>  }<br><br>  static String _getMeasurementUnit(MeasurementUnit measurementUnit) {<br>    if (measurementUnit == MeasurementUnit.metric) {<br>      return _celsiusUnit;<br>    }<br><br>    return _fahrenheitUnit;<br>  }<br>}</pre><p>In this class, we have a bunch of constant values, which help us to format the information. There are a few private function, which format the data. The function _getDayNameFromTimeStamp uses the function DateTime.fromMillisecondsSinceEpoch from the intl library, so we need to add that. Run the following command to add it.</p><pre>flutter pub add intl</pre><p>The function _getWeatherImageIcon helps us to build the proper URL for the image icons from OpenWeatherAPI. From the weather endpoint we only get the icon name not the full URL. <a href="https://openweathermap.org/weather-conditions">Here</a> they provide the base URL for the images and all the icon codes. This functions combines the base URL, the image size and image name to form a proper URL.</p><p>The map function maps the values from the entity into the UI model and returns it. The rest of the functions are quite simple so I will not discuss more about them.</p><p>Now, let’s start with state management. Since we will be using <a href="https://pub.dev/packages/flutter_bloc">flutter_bloc</a> for state management, let’s start by adding its dependency. Run the following command to add flutter_bloc</p><pre>flutter pub add flutter_bloc</pre><p>Create a new folder under the <strong>features/presentation/ </strong>folder named <strong>bloc/current_weather_bloc/. </strong>Add three files inside this folder named <strong>current_weather_state.dart</strong>, <strong>current_weather_event.dart</strong> and <strong>current_weather_bloc.dart</strong>.</p><p>Once you have the files, put the following code inside <strong>current_weather_state.dart</strong></p><pre>import &#39;package:equatable/equatable.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/domain/error/error.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/model/current_weather_ui_model.dart&#39;;<br><br>sealed class CurrentWeatherState extends Equatable {<br>  @override<br>  List&lt;Object?&gt; get props =&gt; [];<br>}<br><br>final class CurrentWeatherLoadingState extends CurrentWeatherState {}<br><br>final class CurrentWeatherLoadedState extends CurrentWeatherState {<br>  final List&lt;CurrentWeatherUiModel&gt; result;<br><br>  CurrentWeatherLoadedState(this.result);<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [result];<br>}<br><br>final class CurrentWeatherErrorState extends CurrentWeatherState {<br>  final BaseError error;<br><br>  CurrentWeatherErrorState({<br>    required this.error,<br>  });<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [error];<br>}</pre><p>We created three states. A loading state with no data, a loaded state which gives us a list of CurrentWeatherUiModel as result and an error state which gives us the error. We will use the result to show the weather data and we will use the error to show the appropriate error message.</p><p>Now, open the <strong>current_weather_event.dart</strong> class and paste the following code</p><pre>import &#39;package:equatable/equatable.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/domain/entity/current_weather_entity.dart&#39;;<br><br>abstract class CurrentWeatherEvent extends Equatable {}<br><br>class CurrentWeatherLoadEvent extends CurrentWeatherEvent {<br>  final double lat;<br>  final double lon;<br>  final MeasurementUnit units;<br><br>  CurrentWeatherLoadEvent({<br>    this.lat = 23.8041,<br>    this.lon = 90.4152,<br>    this.units = MeasurementUnit.metric,<br>  });<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [<br>        lat,<br>        lon,<br>        units,<br>      ];<br>}</pre><p>We have only one event, CurrentWeatherLoadEvent which as the name suggests, is used to load the current weather. We are sending the lat, long, and measurement units through this event. To keep things simple I am using default values here.</p><p>Now open the <strong>current_weather_bloc.dart</strong> file and paste the following code</p><pre>import &#39;dart:async&#39;;<br><br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/domain/error/error.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/domain/repository/current_weather_reository.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/bloc/current_weather_bloc/current_weather_event.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/bloc/current_weather_bloc/current_weather_state.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/mapper/current_weather_entity_to_ui_model_mapper.dart&#39;;<br><br>class CurrentWeatherBloc<br>    extends Bloc&lt;CurrentWeatherEvent, CurrentWeatherState&gt; {<br>  final CurrentWeatherRepository repository;<br>  final CurrentWeatherEntityToUiModelMapper uiModelMapper;<br><br>  CurrentWeatherBloc(<br>    this.repository,<br>    this.uiModelMapper,<br>  ) : super(CurrentWeatherLoadingState()) {<br>    on&lt;CurrentWeatherLoadEvent&gt;(_onCurrentWeatherLoadHandler);<br>  }<br><br>  FutureOr&lt;void&gt; _onCurrentWeatherLoadHandler(<br>    final CurrentWeatherLoadEvent event,<br>    final Emitter&lt;CurrentWeatherState&gt; emit,<br>  ) async {<br>    emit(CurrentWeatherLoadingState());<br>    try {<br>      final entityList = await repository.getCurrentWeather(<br>        lat: event.lat,<br>        lon: event.lon,<br>        units: event.units,<br>      );<br>      final uiModelList = entityList<br>          .map(<br>            (entity) =&gt; uiModelMapper.map(entity),<br>          )<br>          .toList();<br><br>      emit(CurrentWeatherLoadedState(uiModelList));<br>    } on BaseError catch (e) {<br>      emit(<br>        CurrentWeatherErrorState(<br>          error: e,<br>        ),<br>      );<br>    } catch (e) {<br>      emit(<br>        CurrentWeatherErrorState(<br>          error: CommonError(),<br>        ),<br>      );<br>    }<br>  }<br>}</pre><p>In the bloc file, we implement an event handler for the CurrentWeatherLoadEvent . When there is an event, Initially we emit a loading event to let the UI know that it’s loading. Then we make a request to the repository to get the weather data from the domain layer. Once we have the list of entities, we map it into a list of UI models and emit the success state. In case of any errors, we emit the error state. Your file folder structure should look like this till now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*oScLD7lL1gXb9SudGEkTEw.png" /></figure><p>Don’t forget to register the mapper and the bloc into getIt. Open di.dart file and paste the following code inside the setup function</p><pre>void setup async() {<br>....<br>....<br>  getIt.registerLazySingleton&lt;CurrentWeatherEntityToUiModelMapper&gt;(<br>    () =&gt; CurrentWeatherEntityToUiModelMapperImpl(),<br>  );<br>  getIt.registerFactory&lt;CurrentWeatherBloc&gt;(<br>    () =&gt; CurrentWeatherBloc(<br>      getIt.get(),<br>      getIt.get(),<br>    ),<br>  );<br>}</pre><p>Notice that we are registering the bloc as a Factory and not a Singleton. The reason is that the bloc here holds a state, and every time a new instance is created, we don’t want to have the previous states. We want a completely new instance with initial states.</p><p>We’re done with the state management. Now it’s time to add the widgets and screens. We will start with a loading screen.</p><p>Create a new folder under core, named screen and add a file named <strong>loading_screen.dart. </strong>Paste the following code there</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class LoadingScreen extends StatelessWidget {<br>  const LoadingScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return const Center(<br>      child: CircularProgressIndicator(),<br>    );<br>  }<br>}</pre><p>It’s a very simple screen with just a CircularProgressIndicator that loads infinitely.</p><p>Next, on the same folder create another file named <strong>error_screen.dart </strong>and paste the following content.</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class ErrorScreen extends StatelessWidget {<br>  final String errorText;<br>  final void Function() onRetry;<br><br>  const ErrorScreen({<br>    super.key,<br>    required this.errorText,<br>    required this.onRetry,<br>  });<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Column(<br>      mainAxisSize: MainAxisSize.max,<br>      mainAxisAlignment: MainAxisAlignment.center,<br>      children: [<br>        Text(<br>          errorText,<br>          style: const TextStyle(<br>            fontWeight: FontWeight.w400,<br>            fontSize: 14,<br>          ),<br>        ),<br>        const SizedBox(<br>          height: 32.0,<br>        ),<br>        MaterialButton(<br>          onPressed: onRetry,<br>          child: const Text(&quot;Retry&quot;),<br>        ),<br>      ],<br>    );<br>  }<br>}</pre><p>This screen takes an errorText to show the proper error message and an onRetry callback which we can use to retry.</p><p>We put the loading screen and the error screen inside the core folder because we can have other features in the future and these screens can be reused.</p><p>Now create a new folder named <strong>widget/ </strong>inside <strong>features/current_weather/presentation/ </strong>and add a new file named <strong>weather_info_line_widget.dart. </strong>Paste the following code in this file</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class WeatherInfoLineWidget extends StatelessWidget {<br>  final String property;<br>  final String value;<br><br>  const WeatherInfoLineWidget({<br>    super.key,<br>    required this.property,<br>    required this.value,<br>  });<br><br>  @override<br>  Widget build(BuildContext context) {<br><br>    return Row(<br>      children: [<br>        Text(<br>          &quot;$property: $value&quot;,<br>          style: const TextStyle(<br>            fontWeight: FontWeight.w400,<br>            fontSize: 12,<br>          ),<br>        ),<br>      ],<br>    );<br>  }<br>}</pre><p>This widget takes a property and value. We will use this widget to show humidity, pressure, and wind speed info.</p><p>In the same folder, create another file named <strong>weather_details_widget.dart </strong>and paste the following code.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/model/current_weather_ui_model.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/widget/weather_info_line_widget.dart&#39;;<br><br>class WeatherDetailsWidget extends StatelessWidget {<br>  final CurrentWeatherUiModel currentWeatherUiModel;<br><br>  const WeatherDetailsWidget({<br>    super.key,<br>    required this.currentWeatherUiModel,<br>  });<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Column(<br>      crossAxisAlignment: CrossAxisAlignment.center,<br>      mainAxisSize: MainAxisSize.max,<br>      mainAxisAlignment: MainAxisAlignment.spaceEvenly,<br>      children: [<br>        Text(<br>          currentWeatherUiModel.dayNameFull,<br>          style: const TextStyle(<br>            fontWeight: FontWeight.w500,<br>            fontSize: 16,<br>          ),<br>        ),<br>        Text(<br>          currentWeatherUiModel.weatherCondition,<br>          style: const TextStyle(<br>            fontWeight: FontWeight.w400,<br>            fontSize: 14,<br>          ),<br>        ),<br>        const SizedBox(<br>          height: 8.0,<br>        ),<br>        Image.network(<br>          currentWeatherUiModel.smallIcon,<br>        ),<br>        Text(<br>          currentWeatherUiModel.temp,<br>          style: const TextStyle(<br>            fontWeight: FontWeight.w500,<br>            fontSize: 32,<br>          ),<br>        ),<br>        Column(<br>          children: [<br>            WeatherInfoLineWidget(<br>              property: &quot;Humidity&quot;,<br>              value: currentWeatherUiModel.humidity,<br>            ),<br>            WeatherInfoLineWidget(<br>              property: &quot;Pressure&quot;,<br>              value: currentWeatherUiModel.pressure,<br>            ),<br>            WeatherInfoLineWidget(<br>              property: &quot;Wind&quot;,<br>              value: currentWeatherUiModel.windSpeed,<br>            ),<br>          ],<br>        ),<br>      ],<br>    );<br>  }<br>}</pre><p>This widget takes in a CurrentWeatherUiModel object and shows the details of the selected weather.</p><p>Next, inside the same folder create another file named <strong>weather_day_info_widget.dart </strong>and paste the following code</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/model/current_weather_ui_model.dart&#39;;<br><br>class WeatherDayInfoWidget extends StatelessWidget {<br>  final CurrentWeatherUiModel currentWeatherUiModel;<br>  final void Function() onTap;<br><br>  const WeatherDayInfoWidget({<br>    super.key,<br>    required this.currentWeatherUiModel,<br>    required this.onTap,<br>  });<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Card(<br>      clipBehavior: Clip.antiAlias,<br>      child: InkWell(<br>        onTap: onTap,<br>        child: Padding(<br>          padding: const EdgeInsets.all(8.0),<br>          child: SizedBox(<br>            width: 180,<br>            child: Column(<br>              mainAxisAlignment: MainAxisAlignment.spaceEvenly,<br>              children: [<br>                Text(<br>                  currentWeatherUiModel.dayNameShort,<br>                  style: const TextStyle(<br>                    fontWeight: FontWeight.w500,<br>                    fontSize: 14,<br>                  ),<br>                ),<br>                Image.network(<br>                  currentWeatherUiModel.smallIcon,<br>                ),<br>                Text(<br>                  &quot;${currentWeatherUiModel.tempMax}/${currentWeatherUiModel.tempMax}&quot;,<br>                  style: const TextStyle(<br>                    fontWeight: FontWeight.w400,<br>                    fontSize: 12,<br>                  ),<br>                ),<br>              ],<br>            ),<br>          ),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>This widget represents a single day&#39;s in from the list.</p><p>Now, create a new folder named <strong>screen/</strong> inside <strong>features/current_weather/presentation/ </strong>and add a new file named <strong>current_weather_screen.dart. </strong>Paste the following code</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/model/current_weather_ui_model.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/widget/weather_day_info_widget.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/widget/weather_details_widget.dart&#39;;<br><br>class CurrentWeatherScreen extends StatefulWidget {<br>  final List&lt;CurrentWeatherUiModel&gt; weatherDetailsUiModelList;<br><br>  const CurrentWeatherScreen({<br>    super.key,<br>    required this.weatherDetailsUiModelList,<br>  });<br><br>  @override<br>  State&lt;CurrentWeatherScreen&gt; createState() =&gt;<br>      _CurrentWeatherScreenState();<br>}<br><br>class _CurrentWeatherScreenState<br>    extends State&lt;CurrentWeatherScreen&gt; {<br><br>  @override<br>  Widget build(BuildContext context) {<br><br>    return Padding(<br>      padding: const EdgeInsets.all(<br>        16.0,<br>      ),<br>      child: Column(<br>        mainAxisSize: MainAxisSize.max,<br>        children: [<br>          Expanded(<br>            child: WeatherDetailsWidget(<br>              currentWeatherUiModel: widget.weatherDetailsUiModelList.first,<br>            ),<br>          ),<br>          SizedBox(<br>            height: 200,<br>            child: ListView.builder(<br>              scrollDirection: Axis.horizontal,<br>              itemCount: widget.weatherDetailsUiModelList.length,<br>              itemBuilder: (BuildContext context, int index) {<br>                return WeatherDayInfoWidget(<br>                  currentWeatherUiModel: widget.weatherDetailsUiModelList[index],<br>                  onTap: (){<br>                    //todo: implement later<br>                  },<br>                );<br>              },<br>            ),<br>          )<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>In this screen, we combine the weather details section and the list of weather for 5 days. Notice that we are sending the first item from the weatherDetailsUiModelList to the WeatherDetailsWidget object. We will implement this in a later step to change this dynamically.</p><p>Next, in the same folder add another file named <strong>current_weather_screen_container.dart</strong>. This is the place where we will combine the widgets with bloc. Paste the following code into this file</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/domain/error/error.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/presentation/mapper/error_to_message_mapper.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/di/di.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/bloc/current_weather_bloc/current_weather_bloc.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/screen/error_screen.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/screen/loading_screen.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/bloc/current_weather_bloc/current_weather_event.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/bloc/current_weather_bloc/current_weather_state.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/screen/current_weather_screen.dart&#39;;<br><br>class CurrentWeatherScreenContainer extends StatefulWidget {<br>  const CurrentWeatherScreenContainer({super.key});<br><br>  @override<br>  State&lt;CurrentWeatherScreenContainer&gt; createState() =&gt;<br>      _CurrentWeatherScreenContainerState();<br>}<br><br>class _CurrentWeatherScreenContainerState<br>    extends State&lt;CurrentWeatherScreenContainer&gt; {<br>  final CurrentWeatherBloc currentWeatherBloc = getIt.get();<br>  final ErrorToMessageMapper mapper = getIt.get();<br><br>  @override<br>  void initState() {<br>    _loadWeather();<br>    super.initState();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: BlocBuilder&lt;CurrentWeatherBloc, CurrentWeatherState&gt;(<br>        bloc: currentWeatherBloc,<br>        builder: (ctx, state) {<br>          if (state is CurrentWeatherLoadedState) {<br>            return CurrentWeatherScreen(<br>              weatherDetailsUiModelList: state.result,<br>            );<br>          } else if (state is CurrentWeatherLoadingState) {<br>            return const LoadingScreen();<br>          } else if (state is CurrentWeatherErrorState) {<br>            return Center(<br>              child: ErrorScreen(<br>                errorText: mapper.map(state.error),<br>                onRetry: _loadWeather,<br>              ),<br>            );<br>          } else {<br>            return Center(<br>              child: ErrorScreen(<br>                errorText: mapper.map(CommonError()),<br>                onRetry: _loadWeather,<br>              ),<br>            );<br>          }<br>        },<br>      ),<br>    );<br>  }<br><br>  void _loadWeather() {<br>    currentWeatherBloc.add(<br>      CurrentWeatherLoadEvent(),<br>    );<br>  }<br>}</pre><p>Firstly we get an instance of the bloc and the error message mapper from getIt. In the initState we call the function _loadWeather which in terms adds a CurrentWeatherLoadEvent to the bloc. This triggers the process of getting the weather data. Inside the build function, we have a BlocBuilder , which depending on the state of the bloc shows the appropriate widget.</p><p>Notice that, in case of an error state, we are using the error message mapper to show the proper message. Since the mapper is part of the presentation layer, we could also add localization here if we wanted to.</p><p>Your file folder structure should look like the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*0GFuP8km7HS_jnYyyT2fkQ.png" /></figure><p>We also need to register the error message mapper into getIt. Open the setup() function and add the following</p><pre>void setup() async { <br>....<br>....<br>  getIt.registerFactory&lt;ErrorToMessageMapper&gt;(<br>        () =&gt; ErrorMessageMapperImpl(),<br>  );<br>}</pre><p>We have almost everything we need to put everything together. Open the file <strong>app/weather_app.dart </strong>and make the following modification to show the CurrentWeatherScreen</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/screen/current_weather_screen_container.dart&#39;;<br><br>class WeatherApp extends StatelessWidget {<br>  const WeatherApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return const MaterialApp(<br>      title: &#39;Current Weather&#39;,<br>      debugShowCheckedModeBanner: false,<br>      home: CurrentWeatherScreenContainer(),<br>    );<br>  }<br>}</pre><p>Open the <strong>main.dart</strong> file and do the following modifications</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/di/di.dart&#39;;<br><br>import &#39;app/weather_app.dart&#39;;<br><br>void main() async {<br>  await setup();<br>  runApp(const WeatherApp());<br>}</pre><p>We need to call the setup() function from <strong>di.dart</strong> in here to ensure that all the dependencies are properly registered.</p><p>Now run the app and see the output. It should be similar to the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qS2ttEQr52kHnAoYGPB-eA.png" /></figure><p>We have the weather details on the top and the list of 5 days weather at the bottom. Clicking on the list items does not do anything. Next, we will implement that.</p><p>Start by creating a new folder named <strong>weather_details_cubit/ </strong>inside the bloc folder and inside that folder add a new file <strong>weather_details_cubit.dart</strong>. This cubit will keep track of the currently selected weather item. Paste the following code in this folder</p><pre>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/model/current_weather_ui_model.dart&#39;;<br><br>class WeatherDetailsCubit extends Cubit&lt;CurrentWeatherUiModel?&gt; {<br>  WeatherDetailsCubit() : super(null);<br><br>  void updateWeatherDetails(<br>      final CurrentWeatherUiModel? weatherDetailsUiModel) {<br>    emit(weatherDetailsUiModel);<br>  }<br>}</pre><p>The initial state of the cubit is null. Every time we click a list item, we will call updateWeatherDetails to update the currently selected weather.</p><p>Now let’s register this new cubit into getIt</p><pre>void setup() async {<br>  ....<br>  ....<br>  getIt.registerFactory&lt;WeatherDetailsCubit&gt;(<br>    () =&gt; WeatherDetailsCubit(),<br>  );<br>}</pre><p>Now open the CurrentWeatherScreen class and paste the following</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/di/di.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/bloc/weather_details_cubit/weather_details_cubit.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/model/current_weather_ui_model.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/widget/weather_day_info_widget.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/presentation/widget/weather_details_widget.dart&#39;;<br><br>class CurrentWeatherScreen extends StatefulWidget {<br>  final List&lt;CurrentWeatherUiModel&gt; weatherDetailsUiModelList;<br><br>  const CurrentWeatherScreen({<br>    super.key,<br>    required this.weatherDetailsUiModelList,<br>  });<br><br>  @override<br>  State&lt;CurrentWeatherScreen&gt; createState() =&gt; _CurrentWeatherScreenState();<br>}<br><br>class _CurrentWeatherScreenState extends State&lt;CurrentWeatherScreen&gt; {<br>  final WeatherDetailsCubit weatherDetailsCubit = getIt.get();<br><br>  @override<br>  void initState() {<br>    weatherDetailsCubit<br>        .updateWeatherDetails(widget.weatherDetailsUiModelList.first);<br>    super.initState();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Padding(<br>      padding: const EdgeInsets.all(<br>        16.0,<br>      ),<br>      child: Column(<br>        mainAxisSize: MainAxisSize.max,<br>        children: [<br>          Expanded(<br>            child: BlocBuilder&lt;WeatherDetailsCubit, CurrentWeatherUiModel?&gt;(<br>              bloc: weatherDetailsCubit,<br>              builder: (ctx, state) {<br>                if (state != null) {<br>                  return WeatherDetailsWidget(<br>                    currentWeatherUiModel: state,<br>                  );<br>                } else {<br>                  return const SizedBox();<br>                }<br>              },<br>            ),<br>          ),<br>          SizedBox(<br>            height: 200,<br>            child: ListView.builder(<br>              scrollDirection: Axis.horizontal,<br>              itemCount: widget.weatherDetailsUiModelList.length,<br>              itemBuilder: (BuildContext context, int index) {<br>                final currentWeatherUiModel =<br>                    widget.weatherDetailsUiModelList[index];<br>                return WeatherDayInfoWidget(<br>                  currentWeatherUiModel: currentWeatherUiModel,<br>                  onTap: () {<br>                    weatherDetailsCubit.updateWeatherDetails(<br>                      currentWeatherUiModel,<br>                    );<br>                  },<br>                );<br>              },<br>            ),<br>          )<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>We made a few modifications. Firstly we add the following line to get an instance of the cubit</p><pre>final WeatherDetailsCubit weatherDetailsCubit = getIt.get();</pre><p>Next, on initState we initialize the cubit with the first item of the list.</p><pre>@override<br>  void initState() {<br>    weatherDetailsCubit<br>        .updateWeatherDetails(widget.weatherDetailsUiModelList.first);<br>    super.initState();<br>  }</pre><p>In the build functions WeatherDetails section, we use the cubit to show the currently selected weather details. In case there is no data, we just show a SizedBox.</p><pre>Expanded(<br>            child: BlocBuilder&lt;WeatherDetailsCubit, CurrentWeatherUiModel?&gt;(<br>              bloc: weatherDetailsCubit,<br>              builder: (ctx, state) {<br>                if (state != null) {<br>                  return WeatherDetailsWidget(<br>                    currentWeatherUiModel: state,<br>                  );<br>                } else {<br>                  return const SizedBox();<br>                }<br>              },<br>            ),<br>          ),</pre><p>We have also modified the list, to update the cubit with new weather details every time an item is clicked.</p><pre>(BuildContext context, int index) {<br>  final currentWeatherUiModel =<br>      widget.weatherDetailsUiModelList[index];<br>  return WeatherDayInfoWidget(<br>    currentWeatherUiModel: currentWeatherUiModel,<br>    onTap: () {<br>      weatherDetailsCubit.updateWeatherDetails(<br>        currentWeatherUiModel,<br>      );<br>    },<br>  );<br>}</pre><p>That’s it. If you click on the list items, you will see the details section updating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*DKi9m8XtB82V4WuI6r_QzQ.gif" /></figure><p>If you turn of the internet and re-run the app, you can see the error screen that we have built. You can play around with the responses to see different error messages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aSeH7JtKajyakAEeMsgLsg.png" /></figure><p>That’s it! Congratulations on completing the tutorial. Now you have a flutter application built with clean architecture!</p><p>You can find the full source code <a href="https://github.com/AliAkberAakash/weather_clean_architecture_flutter/tree/part_3">here</a>.</p><p>If you have any questions, feel free to leave a comment!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbd52907eb77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making a Flutter Application with CLEAN ARCHITECTURE — Part2]]></title>
            <link>https://medium.com/@ali852609/making-a-flutter-application-with-clean-architecture-part2-1424a4c97e03?source=rss-5882a491e8e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1424a4c97e03</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Ali Akber]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 20:05:33 GMT</pubDate>
            <atom:updated>2025-01-05T09:44:16.419Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making a Flutter Application with CLEAN ARCHITECTURE — Part2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kyD-ZdZlLAjo5ZPe2GI9zA.png" /></figure><p>Hello and welcome! This is part 2 of the tutorial series “Making a Flutter Application with CLEAN ARCHITECTURE”. <br><a href="https://medium.com/@ali852609/making-a-flutter-application-with-clean-architecture-part1-f42b93431924">Here you can find the link to part 1</a>. If you haven’t already, complete it first!</p><p>In part 1, we have created the core network module, and error handling for our application. In this part we will start with the data layer and domain layer.</p><p>Let’s start by creating a few new folders. Under <strong>lib/ </strong>we will create a new folder called <strong>features/</strong>. We will keep all of the features inside this folder. Create another folder named <strong>current_weather/ </strong>inside<strong> features/. </strong>And inside <strong>current_weather/</strong> create three new folders, <strong>data/</strong> , <strong>domain/</strong> and <strong>presentation/</strong>. It should look something like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*eIO0wGgcP2h7QNOdxvthpg.png" /></figure><p>As you can see, we have three modules to each feature. This will be the common file folder structure we will use for any new feature.</p><p>Now that we have the necessary folders, let’s define the DTO (Data Transfer Object) classes. We will use the DTO classes to transfer data between the app and the network. Create one more folder under <strong>network/</strong> module of <strong>current_weather</strong> feature, named <strong>dto/. </strong>Create a new file under this folder named <strong>current_weather_response.dart . </strong>Paste the following code into this new file.</p><pre>import &#39;package:equatable/equatable.dart&#39;;<br>import &#39;package:json_annotation/json_annotation.dart&#39;;<br><br>part &#39;current_weather_response.g.dart&#39;;<br><br>@JsonSerializable(createToJson: false)<br>class CurrentWeatherResponse extends Equatable {<br>  @JsonKey(name: &#39;dt&#39;)<br>  final int dateTime;<br>  @JsonKey(name: &#39;main&#39;)<br>  final WeatherDetails weatherDetails;<br>  @JsonKey(name: &#39;weather&#39;)<br>  final List&lt;Weather&gt; weather;<br>  @JsonKey(name: &#39;wind&#39;)<br>  final Wind wind;<br>  @JsonKey(name: &#39;sys&#39;)<br>  final Sys sys;<br><br>  const CurrentWeatherResponse({<br>    required this.dateTime,<br>    required this.weatherDetails,<br>    required this.weather,<br>    required this.wind,<br>    required this.sys,<br>  });<br><br>  factory CurrentWeatherResponse.fromJson(final Map&lt;String, dynamic&gt; json) =&gt;<br>      _$CurrentWeatherResponseFromJson(json);<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [<br>    dateTime,<br>    weatherDetails,<br>    weather,<br>    wind,<br>    sys,<br>  ];<br>}<br><br>@JsonSerializable(createToJson: false)<br>class WeatherDetails extends Equatable {<br>  @JsonKey(name: &#39;temp&#39;)<br>  final double temp;<br>  @JsonKey(name: &#39;temp_min&#39;)<br>  final double tempMin;<br>  @JsonKey(name: &#39;temp_max&#39;)<br>  final double tempMax;<br>  @JsonKey(name: &#39;pressure&#39;)<br>  final int pressure;<br>  @JsonKey(name: &#39;humidity&#39;)<br>  final int humidity;<br><br>  const WeatherDetails({<br>    required this.temp,<br>    required this.tempMin,<br>    required this.tempMax,<br>    required this.pressure,<br>    required this.humidity,<br>  });<br><br>  factory WeatherDetails.fromJson(final Map&lt;String, dynamic&gt; json) =&gt;<br>      _$WeatherDetailsFromJson(json);<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [<br>    tempMin,<br>    tempMax,<br>    pressure,<br>    humidity,<br>  ];<br>}<br><br>@JsonSerializable(createToJson: false)<br>class Sys extends Equatable {<br>  @JsonKey(name: &#39;pod&#39;)<br>  final String partOfDay;<br><br>  const Sys({<br>    required this.partOfDay,<br>  });<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [partOfDay];<br><br>  factory Sys.fromJson(final Map&lt;String, dynamic&gt; json) =&gt; _$SysFromJson(json);<br>}<br><br>@JsonSerializable(createToJson: false)<br>class Weather extends Equatable {<br>  @JsonKey(name: &#39;main&#39;)<br>  final String name;<br>  @JsonKey(name: &#39;description&#39;)<br>  final String description;<br>  @JsonKey(name: &#39;icon&#39;)<br>  final String icon;<br><br>  const Weather({<br>    required this.name,<br>    required this.description,<br>    required this.icon,<br>  });<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [<br>    name,<br>    description,<br>    icon,<br>  ];<br><br>  factory Weather.fromJson(final Map&lt;String, dynamic&gt; json) =&gt;<br>      _$WeatherFromJson(json);<br>}<br><br>@JsonSerializable(createToJson: false)<br>class Wind extends Equatable {<br>  @JsonKey(name: &quot;speed&quot;)<br>  final double speed;<br><br>  const Wind({<br>    required this.speed,<br>  });<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [speed];<br><br>  factory Wind.fromJson(final Map&lt;String, dynamic&gt; json) =&gt;<br>      _$WindFromJson(json);<br>}</pre><p>This class maps the response from the network request. We created this based on the <a href="https://openweathermap.org/forecast5#example_JSON">json response</a> provided by the OpenWeather API. You will see the compiler complaining since we haven’t yet added a few libraries.</p><p>Run the following command to add <a href="https://pub.dev/packages/build_runner">build_runner</a>, <a href="https://pub.dev/packages/json_annotation/install">json_annotation</a> and <a href="https://pub.dev/packages/json_serializable/install">json_serializable</a> libraries.</p><pre>dart pub add dev:build_runner<br>flutter pub add json_annotation<br>dart pub add dev:json_serializable</pre><p>From the json_annotation library, we use the <strong>JsonSerializable </strong>annotation<strong> </strong>to mark the class as json serializable. We set <strong>createToJson: false </strong>because this is a response object that we get from the network, we don’t need to convert it to json for our feature. We use the<strong> JsonKey </strong>annotation to map the json fields with the dart object fields.</p><p>We also added one extra line under the imports, <br><strong>part ‘current_weather_response.g.dart’; <br></strong>We add this so that we can use the generated methods from <strong>current_weather_response.g.dart </strong>into our <strong>current_weather_response.dart </strong>file.<strong> </strong>However, since we don’t have <strong>current_weather_response.g.dart </strong>yet we need to generate it. Run the following command to generate this file.</p><pre>dart run build_runner build</pre><p>Now that we have the DTO class, let’s start with the network source.</p><p>We will start by adding an <strong>env.dart</strong> file under the <strong>lib/</strong> folder. We will put our API key in this file. Since this is a sensitive file, we do not want to add it to the version control. Make sure to add the following line in .gitignore file, so that it does not track the <strong>env.dart</strong> file.</p><pre>lib/env.dart</pre><p>There are better ways to secure API keys, but for this tutorial we will follow the above mentioned approach.</p><p>Now, paste the following line in the <strong>env.dart</strong> file. Replace “YOUR_KEY_HERE” with your own API key from <a href="https://home.openweathermap.org/api_keys">OpenWeather.</a></p><pre>const String apiKey = &quot;YOUR_KEY_HERE&quot;;</pre><p>Create two new files, <strong>current_weather_network_source.dart</strong> and <strong>current_weather_network_source_impl.dart </strong>inside the <strong>current_weather/data/networ_ksource/</strong> folder. Paste the following code in <strong>current_weather_network_source.dart</strong></p><pre>import &#39;package:weather_clean_architecture_flutter/features/current_weather/data/dto/current_weather_response.dart&#39;;<br><br>abstract class CurrentWeatherNetworkSource {<br>  Future&lt;List&lt;CurrentWeatherResponse&gt;&gt; getCurrentWeather({<br>    required final double lat,<br>    required final double lon,<br>    required final String units,<br>  });<br>}</pre><p>This class defines the API for the network data source. We have one single function named getCurrentWeather which takes a latitude, a longitude, and the unit in which we want the response. The units is a String variable that can take the following values: standard, metric and imperial. <a href="https://openweathermap.org/current#data">Here</a> you can find the details from the OpenWeather API docs.</p><p>Now that we have the API definition ready let’s implement it. Paste the following code into <strong>current_weather_network_source_impl.dart</strong></p><pre>import &#39;package:weather_clean_architecture_flutter/core/data/network/network_client.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/data/network/network_request.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/env.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/data/network_source/current_weather_network_source.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/data/dto/current_weather_response.dart&#39;;<br><br>class CurrentWeatherNetworkSourceImpl implements CurrentWeatherNetworkSource {<br>  final NetworkClient _networkClient;<br><br>  CurrentWeatherNetworkSourceImpl(<br>      this._networkClient,<br>      );<br><br>  @override<br>  Future&lt;List&lt;CurrentWeatherResponse&gt;&gt; getCurrentWeather({<br>    required final double lat,<br>    required final double lon,<br>    required final String units,<br>  }) async {<br>    try {<br>      final networkRequest = NetworkRequest(<br>        path: &quot;forecast&quot;,<br>        queryParams: {<br>          &quot;lat&quot;: lat.toString(),<br>          &quot;lon&quot;: lon.toString(),<br>          &quot;appId&quot;: apiKey,<br>          &quot;units&quot;: units,<br>        },<br>      );<br>      final response = await _networkClient.get(networkRequest);<br>      final weatherDataList = response.body[&quot;list&quot;];<br>      final List&lt;CurrentWeatherResponse&gt; weatherList = [];<br><br>      for (var weatherData in weatherDataList) {<br>        weatherList.add(CurrentWeatherResponse.fromJson(weatherData));<br>      }<br><br>      return weatherList;<br>    } catch (e) {<br>      rethrow;<br>    }<br>  }<br>}</pre><p>This class takes a NetworkClient object as a constructor parameter. We created this class in part 1. The getCurrentWeather function implementation constructs a NetworkRequest object from the lat, long, and unit parameters. You might have noticed an additional filed appId . This is where we need to use the API key which we get from the OpenWeather API. For now, keep this as it is in the code above. We will later add this key to our project securely.</p><p>Once the request object is made, we make a network request with the help of the network client. The response is a big json, and we only care about the list object. So we get the list with final weatherDataList = response.body[“list”]; . Once we have the json list, we convert it into a list of CurrentWeatherResponse object and return it.</p><p>In case there is any exception we just rethrow because we don’t want to add any custom exception from the data source layer, and we already handled all the network exceptions in the NetworkClientImpl.</p><p>Your file folder structure should look like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*KP0OuE-hmkJUZQxZyzJVeQ.png" /></figure><p>Now it’s time to get started with the domain layer. Inside the <strong>domain/</strong> folder, we are going to create a new file <strong>entity/current_weather_entity.dart </strong>and paste the following code.</p><pre>class CurrentWeatherEntity {<br>  final int dateTime;<br>  final double temp;<br>  final double tempMin;<br>  final double tempMax;<br>  final int pressure;<br>  final int humidity;<br>  final String partOfDay;<br>  final List&lt;WeatherEntity&gt; weather;<br>  final double speed;<br>  final MeasurementUnit unit;<br><br>  const CurrentWeatherEntity({<br>    required this.dateTime,<br>    required this.temp,<br>    required this.tempMin,<br>    required this.tempMax,<br>    required this.pressure,<br>    required this.humidity,<br>    required this.partOfDay,<br>    required this.weather,<br>    required this.speed,<br>    required this.unit,<br>  });<br>}<br><br>class WeatherEntity {<br>  final String name;<br>  final String description;<br>  final String icon;<br><br>  const WeatherEntity({<br>    required this.name,<br>    required this.description,<br>    required this.icon,<br>  });<br>}<br><br>enum MeasurementUnit {<br>  metric,<br>  imperial,<br>}</pre><p>The entity is the core building block of our domain. Each CurrentWeatherEntity represents a unique weather object, which we will use throughout the application. All the other layers know about the entity. The data layer will try to map its response into an entity, and the UI layer will try to map its data from an entity. We will get back to the mappings shortly.</p><p>Now it’s time to define our repository API. The repository is divided into two parts. Its API definition will be in the domain layer. It’s like the domain layer is defining, “This is how I want my data”. The repository will be implemented in the data layer. The data layer will be providing the data as the domain layer requests it.</p><p>Let’s create the repository API definition in the domain layer. Create a new file <strong>repository/current_weather_repository.dart </strong>inside the<strong> domain/ </strong>folder<strong> </strong>and paste the following code into it</p><pre>import &#39;package:weather_clean_architecture_flutter/features/current_weather/domain/entity/current_weather_entity.dart&#39;;<br><br>abstract class CurrentWeatherRepository {<br>  Future&lt;List&lt;CurrentWeatherEntity&gt;&gt; getCurrentWeather({<br>    required final double lat,<br>    required final double lon,<br>    required final MeasurementUnit unit,<br>  });<br>}</pre><p>We have a single function getCurrentWeather , which takes in the parameters latitude, longitude, and the units, and returns a list of CurrentWeatherEntity objects. Notice, that here we are sending a MeasurementUnit object instead of a string because this is how our domain layer recognizes the units. The same goes for the response, instead of NetworkResponse objects, we get CurrentWeatherEntity objects, because the domain layer does not know about the network responses and this is how the weather data is represented in the domain layer.</p><p>Before we can implement the repository, we will need a mapper that can convert the data layer responses into domain layer entities. Let’s create a new class <strong>mapper/current_weather_entity_mapper.dart </strong>inside<strong> </strong>the <strong>data/ </strong>folder and paste the following code</p><pre>import &#39;package:weather_clean_architecture_flutter/features/current_weather/data/dto/current_weather_response.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/domain/entity/current_weather_entity.dart&#39;;<br><br>abstract class CurrentWeatherEntityMapper {<br>  List&lt;CurrentWeatherEntity&gt; map(<br>    final List&lt;CurrentWeatherResponse&gt; responseList,<br>    final MeasurementUnit units,<br>  );<br>}</pre><p>There is only one function map which takes a list of CurrentWeatherResponse and a units object and converts it into a list of CurrentWeatherEntity .</p><p>Now let’s implement the mapper. Create another file <strong>current_weather_entity_mapper_impl.dart </strong>in the same folder and paste the following code</p><pre>import &#39;package:weather_clean_architecture_flutter/features/current_weather/data/dto/current_weather_response.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/data/mapper/current_weather_entity_mapper.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/domain/entity/current_weather_entity.dart&#39;;<br><br>class CurrentWeatherEntityMapperImpl extends CurrentWeatherEntityMapper {<br>  @override<br>  List&lt;CurrentWeatherEntity&gt; map(<br>    final List&lt;CurrentWeatherResponse&gt; responseList,<br>    final MeasurementUnit units,<br>  ) {<br>    final entityList = responseList<br>        .map(<br>          (response) =&gt; _mapFromWeatherResponse(<br>            response,<br>            units,<br>          ),<br>        )<br>        .toList();<br><br>    return _filterFirstWeatherDetailsPerDay(entityList);<br>  }<br><br>  CurrentWeatherEntity _mapFromWeatherResponse(<br>    final CurrentWeatherResponse response,<br>    final MeasurementUnit unit,<br>  ) {<br>    return CurrentWeatherEntity(<br>      dateTime: response.dateTime,<br>      temp: response.weatherDetails.temp,<br>      tempMin: response.weatherDetails.tempMin,<br>      tempMax: response.weatherDetails.tempMax,<br>      pressure: response.weatherDetails.pressure,<br>      humidity: response.weatherDetails.humidity,<br>      partOfDay: response.sys.partOfDay,<br>      weather: response.weather<br>          .map((response) =&gt; _mapFromWeather(response))<br>          .toList(),<br>      speed: response.wind.speed,<br>      unit: unit,<br>    );<br>  }<br><br>  WeatherEntity _mapFromWeather(<br>    final Weather response,<br>  ) {<br>    return WeatherEntity(<br>      name: response.name,<br>      description: response.description,<br>      icon: response.icon,<br>    );<br>  }<br><br>  List&lt;CurrentWeatherEntity&gt; _filterFirstWeatherDetailsPerDay(<br>    final List&lt;CurrentWeatherEntity&gt; weatherDetails,<br>  ) {<br>    Map&lt;String, CurrentWeatherEntity&gt; firstWeatherDetailsPerDay = {};<br><br>    for (var entity in weatherDetails) {<br>      DateTime date =<br>          DateTime.fromMillisecondsSinceEpoch(entity.dateTime * 1000);<br>      String dayKey = &quot;${date.year}-${date.month}-${date.day}&quot;;<br><br>      if (!firstWeatherDetailsPerDay.containsKey(dayKey)) {<br>        firstWeatherDetailsPerDay[dayKey] = entity;<br>      }<br>    }<br><br>    return firstWeatherDetailsPerDay.values.toList();<br>  }<br>}</pre><p>We have two private functions _mapFromWeather and _mapFromWeatherResponse which converts the corresponding network responses into entity objects. We do the list conversion inside the map function and before returning, we also call _filterFirstWeatherDetailsPerDay .</p><p>Why do we need this filtering? Well, the open API returns three responses for each day. But according to our design, we only need to show one response for a single day. This filter function filters the data and takes the first response for each day.</p><p>Now that we have the mappers, let’s implement the repository. Create a new file <strong>repository/current_weather_repository_impl.dart </strong>inside the <strong>data/</strong> folder and paste the following code. Notice that we are putting the repository API definition in the domain, but the implementation inside the data folder.</p><pre>import &#39;package:weather_clean_architecture_flutter/core/data/exceptions/base_exception.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/data/mapper/exception_to_error_mapper.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/data/network_source/current_weather_network_source.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/data/mapper/current_weather_entity_mapper.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/domain/entity/current_weather_entity.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/features/current_weather/domain/repository/current_weather_reository.dart&#39;;<br><br>class CurrentWeatherRepositoryImpl implements CurrentWeatherRepository {<br>  final CurrentWeatherNetworkSource _weatherNetworkSource;<br>  final CurrentWeatherEntityMapper _weatherDetailsEntityMapper;<br>  final ExceptionToErrorMapper _exceptionToErrorMapper;<br><br>  CurrentWeatherRepositoryImpl(<br>    this._weatherNetworkSource,<br>    this._weatherDetailsEntityMapper,<br>    this._exceptionToErrorMapper,<br>  );<br><br>  @override<br>  Future&lt;List&lt;CurrentWeatherEntity&gt;&gt; getCurrentWeather({<br>    required final double lat,<br>    required final double lon,<br>    required final MeasurementUnit units,<br>  }) async {<br>    try {<br>      final response = await _weatherNetworkSource.getCurrentWeather(<br>        lat: lat,<br>        lon: lon,<br>        units: units.name,<br>      );<br><br>      return _weatherDetailsEntityMapper.map(response, units);<br>    } on BaseException catch (e) {<br>      final error = _exceptionToErrorMapper.map(e);<br>      throw error;<br>    } catch (e) {<br>      rethrow;<br>    }<br>  }<br>}</pre><p>The repository implementation, takes a network source, an entity mapper and an exception mapper. The getCurrentWeather function uses the _weatherNetworkSource to get the response, and then the _weatherDetailsEntityMapper to map the response into an entity object for the domain.</p><p>It does the same for exceptions. It uses the _exceptionToErrorMapper to convert the data layer exceptions into domain layer exceptions, and throws it for the domain layer to handle. If there is any unexpected exception we just rethrow it to handle it in the other layers.</p><p>This is how your file folder structure should look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*4NoQHXICHZklhrMavjh7Zg.png" /></figure><p>Whew! That was a lot of code. But we are finally done with the data layer and the domain layer. In the next and final part, we will implement the UI layer.</p><p><a href="https://github.com/AliAkberAakash/weather_clean_architecture_flutter/tree/part_2">Here</a> you can find the GitHub repo for the code.</p><p>Read the next part <a href="https://medium.com/@ali852609/making-a-flutter-application-with-clean-architecture-part3-cbd52907eb77">here</a>.</p><p>If you have any questions, feel free to leave a comment!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1424a4c97e03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making a Flutter Application with CLEAN ARCHITECTURE — Part1]]></title>
            <link>https://medium.com/@ali852609/making-a-flutter-application-with-clean-architecture-part1-f42b93431924?source=rss-5882a491e8e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f42b93431924</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <dc:creator><![CDATA[Ali Akber]]></dc:creator>
            <pubDate>Thu, 05 Dec 2024 22:25:20 GMT</pubDate>
            <atom:updated>2025-01-04T08:39:40.030Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making a Flutter Application with CLEAN ARCHITECTURE — Part1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kyD-ZdZlLAjo5ZPe2GI9zA.png" /></figure><p>Hello and welcome! In this blog, we are going to create a Flutter application together with CLEAN Architecture and Industry Best Practices. We’ll try to make it as close to production-ready as possible. So Let’s get started!</p><p>We will be making a Weather application using the free <a href="https://openweathermap.org/forecast5">OpenWeather API</a>. Create an account and get an API Key. We will use it later.</p><p>The final application will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qS2ttEQr52kHnAoYGPB-eA.png" /></figure><p>These are the requirements:</p><ul><li>The app shows a list of the weather for the next 5 days.</li><li>User can select any of the items in the list to see more details.</li><li>The selected day gets focused on the details section.</li><li>The details show the current day at the top, an icon of the weather, current temperature, Humidity, Pressure, and Wind speed. The text on the top left describes the weather conditions.</li></ul><p>If you are completely new to Clean Architecture and want to know how it works, you can read <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">this</a>.</p><p>Our application will have the following architecture:</p><ul><li>Data Layer: For keeping data-related code, ex: network request related code, repository implementation, etc.</li><li>Domain Layer: Domain-specific code, ex: Entities, repository contracts, etc.</li><li>Presentation Layer: UI-specific code, ex: Screens and Widgets, etc.</li></ul><p>We will use <a href="https://pub.dev/packages/flutter_bloc">flutter_bloc</a> for state management, <a href="https://pub.dev/packages/dio">dio</a> for network &amp; <a href="https://pub.dev/packages/get_it">get_it</a> for dependency injection.</p><p>Let’s start by creating a new flutter project. You can name it whatever you want. I’m naming mine <strong>weather_clean_architecture_flutter</strong>. Once created, clean up the main file to make it look like this.</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>void main() {<br>  runApp(const WeatherApp());<br>}</pre><p>We still don’t have the <strong>WeatherApp</strong> class, so the compiler will complain. Let’s create it. Create a new directory named <strong>app</strong> and create a new dart file <strong>weather_app.dart .</strong> Paste the following code into it. Import <strong>WeatherApp </strong>in the main file to make the compiler happy!</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class WeatherApp extends StatelessWidget {<br>  const WeatherApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return const MaterialApp(<br>      title: &#39;Current Weather&#39;,<br>      debugShowCheckedModeBanner: false,<br>      home: Scaffold(<br>        body: Center(<br>          child: Text(&quot;Hello World&quot;),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Since we need to make network requests from this application, let’s create a network module with some core functionalities. We will need the following libraries: <strong>dio</strong> and <strong>equatable</strong>. Add them to your project.</p><pre>flutter pub add dio<br>flutter pub add equatable</pre><p>Once the dependencies are added it’s time to create some helper classes. under the lib folder create a new directory named <strong>core/data</strong>. Create two more directories under <strong>data</strong> named, <strong>network</strong> and <strong>exception</strong>. It should look like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*8FOICSNGcDwJlXj9XQZ0Kw.png" /></figure><p>Since the network request is a job of the data layer, we put it in the data folder. In the <strong>network</strong> folder create a class named <strong>network_request.dart</strong></p><pre>import &#39;package:equatable/equatable.dart&#39;;<br><br>class NetworkRequest extends Equatable {<br>  final String path;<br>  final Map&lt;String, dynamic&gt;? requestBody;<br>  final Map&lt;String, dynamic&gt;? queryParams;<br>  final Map&lt;String, dynamic&gt;? headers;<br><br>  const NetworkRequest({<br>    required this.path,<br>    this.requestBody,<br>    this.queryParams,<br>    this.headers,<br>  });<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [<br>        path,<br>        requestBody,<br>        queryParams,<br>        headers,<br>      ];<br>}</pre><p>The class has four fields. The <strong>path</strong> field defines the endpoint where we will make the request. The <strong>requestBody </strong>field contains the request body as a map, queryParams contain the query parameters as a map and the <strong>header </strong>in case we need to send any headers along with the request. The class extends <strong>equatable </strong>so that we can check the equatability of this object. This will come in handy when we want to compare two instances of this object, for example, asserting in unit tests.</p><p>Similarly let&#39;s create another file inside the <strong>network</strong> folder named <strong>network_response.dart</strong></p><pre>import &#39;package:equatable/equatable.dart&#39;;<br><br>class NetworkResponse extends Equatable {<br>  final Map&lt;String, dynamic&gt; body;<br>  final Map&lt;String, List&lt;String&gt;&gt; headers;<br><br>  const NetworkResponse({required this.body, required this.headers});<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [<br>        body,<br>        headers,<br>      ];<br>}</pre><p>This class has two fields, the response body and any headers we get along. This class also extends from <strong>equatable</strong>.</p><p>In the exceptions folder we will create a new file named <strong>base_exceptions.dart </strong>This class will be the base of all the custom exceptions in this application.</p><pre>import &#39;package:equatable/equatable.dart&#39;;<br><br>abstract class BaseException extends Equatable {<br>  const BaseException();<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [];<br>}</pre><p>Create another file inside the same directory, named <strong>network_exceptions.dart</strong> and paste the following code</p><pre>import &#39;package:weather_clean_architecture_flutter/core/data/exceptions/base_exception.dart&#39;;<br><br>class NetworkException extends BaseException {<br>  const NetworkException();<br>}<br><br>class NetworkTimeoutException extends BaseException {<br>  const NetworkTimeoutException();<br>}<br><br>class ServerException extends BaseException {<br>  final int? statusCode;<br>  final String? statusMessage;<br><br>  const ServerException({<br>    this.statusCode,<br>    this.statusMessage,<br>  });<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [<br>    statusCode,<br>    statusMessage,<br>  ];<br>}</pre><p>There can be many exceptions thrown from the network layer. We will convert all of them into the following exceptions:</p><ul><li><strong>NetworkException:</strong> Anything happened that wasn’t supposed to happen, for example, parsing error of wrong response body, wrong headers, etc.</li><li><strong>NetworkTimeoutException: </strong>For timeout-related errors, ie. slow internet, or no internet connection.</li><li><strong>ServerException: </strong>When we get a response from the server, but it’s not a successful response. In this case, we also want the status code and any message returned from the server to show the user a meaningful message.</li></ul><p>Now it’s time to create our network client. In the <strong>core/data/network</strong> folder create two new files, <strong>network_client.dart</strong> and <strong>dio_network_client.dart</strong></p><pre>import &#39;package:weather_clean_architecture_flutter/core/data/network/network_request.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/data/network/network_response.dart&#39;;<br><br>abstract class NetworkClient {<br>  Future&lt;NetworkResponse&gt; get(final NetworkRequest request);<br>}</pre><pre>import &#39;package:dio/dio.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/data/exceptions/base_exception.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/data/exceptions/network_exceptions.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/data/network/network_client.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/data/network/network_request.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/data/network/network_response.dart&#39;;<br><br>class DioNetworkClient implements NetworkClient {<br>  final Dio _dio;<br>  final List&lt;Interceptor&gt; interceptors;<br><br>  DioNetworkClient(<br>      this._dio, {<br>        this.interceptors = const [],<br>      }) {<br>    if (interceptors.isNotEmpty) {<br>      _dio.interceptors.addAll(interceptors);<br>    }<br>  }<br><br>  @override<br>  Future&lt;NetworkResponse&gt; get(final NetworkRequest request) async {<br>    try {<br>      final response = await _dio.get(<br>        request.path,<br>        options: _createDioOptions(request),<br>        queryParameters: request.queryParams,<br>      );<br>      return _handleResponse(response);<br>    } on DioException catch (error) {<br>      throw _handleDioExceptions(error);<br>    } on ServerException {<br>      rethrow;<br>    } catch (error) {<br>      throw const NetworkException();<br>    }<br>  }<br><br>  Options _createDioOptions(final NetworkRequest request) =&gt; Options(<br>    headers: request.headers ?? {},<br>  );<br><br>  NetworkResponse _handleResponse(final Response&lt;dynamic&gt; response) {<br>    if (_isInvalidStatusCode(response.statusCode)) {<br>      throw ServerException(<br>        statusCode: response.statusCode,<br>        statusMessage: response.statusMessage,<br>      );<br>    }<br><br>    return NetworkResponse(<br>      body: response.data,<br>      headers: response.headers.map,<br>    );<br>  }<br><br>  bool _isInvalidStatusCode(final int? statusCode) {<br>    return statusCode == null || statusCode &lt; 200 || statusCode &gt;= 300;<br>  }<br><br>  BaseException _handleDioExceptions(final DioException error) {<br>    if (error.response != null) {<br>      throw ServerException(<br>        statusCode: error.response?.statusCode,<br>        statusMessage: error.response?.statusMessage,<br>      );<br>    }<br><br>    switch (error.type) {<br>      case DioExceptionType.connectionTimeout:<br>      case DioExceptionType.sendTimeout:<br>      case DioExceptionType.receiveTimeout:<br>        throw const NetworkTimeoutException();<br>      default:<br>        throw const NetworkException();<br>    }<br>  }<br>}</pre><p>The <strong>NetworkClient </strong>class describes the interface of the client. Since we only need to make a get request in this application, there is only one get function, which takes the request body and returns the response.</p><p>Now let’s have a deeper look into the <strong>DioNetworkClient </strong>class. The class takes two constructor parameters, a <strong>Dio</strong> object and a list of <strong>interceptors</strong>. In the constructor body it applies the interceptors to the dio object. This gives us the flexibility to inject different interceptors for different instances of the <strong>DioNetworkClient </strong>class.</p><p>Let’s look at the implementation of the get method. It makes the request using the fields from the request body. If there is a successful response it passes the response to the <strong>_handleResponse</strong> method. If there is some error from the server but we have a response, it throws a <strong>ServerException</strong>.<strong> </strong>If the response is successful, it converts it into a <strong>NetworkResponse</strong> object and returns it.</p><p>In case of any error from Dio, <strong>_handleDioExceptions </strong>is called. In case of timeout exceptions, we throw a <strong>NetworkTimeoutException</strong>. In any other case, we throw a <strong>NetworkException</strong>.</p><p>Next, we will create a new directory <strong>core/domain/error/ . </strong>In this folder, we will create a new class<strong> error.dart</strong></p><pre>import &#39;package:equatable/equatable.dart&#39;;<br><br>sealed class BaseError extends Equatable {<br>  @override<br>  List&lt;Object?&gt; get props =&gt; [];<br>}<br><br>class NetworkError extends BaseError {}<br><br>class NetworkTimeoutError extends BaseError {}<br><br>class ServerError extends BaseError {<br>  final int? statusCode;<br>  final String? statusMessage;<br><br>  ServerError({<br>    this.statusCode,<br>    this.statusMessage,<br>  });<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [<br>        statusCode,<br>        statusMessage,<br>      ];<br>}<br><br>class CommonError extends BaseError {}</pre><p>You might be wondering, we already created so many exceptions, why do we need errors? Also, why do they look similar to the exceptions? Well, in clean architecture, the domain layer is not supposed to know about the other layers. The domain layer has its own errors. It does not care about what the data layer has.</p><p>It might seem like, the domain layer is creating these error classes based on the data later. But actually, it’s the other way around. The data layer has these exceptions because the domain layer cares about them. When sending these exceptions to the domain layer, we will convert them into errors. It will be more clear once we implement the repositories.</p><p>Create one more folder: <strong>core/data/mapper/ </strong>and add a new file <strong>exception_to_error_mapper.dart</strong></p><pre>import &#39;package:weather_clean_architecture_flutter/core/data/exceptions/base_exception.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/data/exceptions/network_exceptions.dart&#39;;<br>import &#39;package:weather_clean_architecture_flutter/core/domain/error/error.dart&#39;;<br><br>abstract class ExceptionToErrorMapper {<br>  BaseError map(final BaseException exception);<br>}<br><br>class ExceptionToErrorMapperImpl extends ExceptionToErrorMapper {<br>  @override<br>  BaseError map(final BaseException exception) {<br>    switch (exception.runtimeType) {<br>      case const (ServerException):<br>        exception as ServerException;<br>        return ServerError(<br>            statusCode: exception.statusCode,<br>            statusMessage: exception.statusMessage);<br>      case const (NetworkException):<br>        return NetworkError();<br>      case const (NetworkTimeoutException):<br>        return NetworkTimeoutError();<br>      default:<br>        return CommonError();<br>    }<br>  }<br>}</pre><p>As you can see this class converts the data layer exceptions into domain layer errors. We will use this class in our repository implementation.</p><p>Now let’s get to the presentation layer. Add a new folder <strong>core/presentation/mapper </strong>and add a new file <strong>error_to_message_mapper.dart</strong></p><pre>import &#39;package:weather_clean_architecture_flutter/core/domain/error/error.dart&#39;;<br><br>abstract class ErrorToMessageMapper {<br>  String map(final BaseError error);<br>}<br><br>class ErrorMessageMapperImpl extends ErrorToMessageMapper {<br>  @override<br>  String map(final BaseError error) {<br>    switch (error.runtimeType) {<br>      case const (NetworkError):<br>        return &quot;Failed to load data&quot;;<br>      case const (NetworkTimeoutError):<br>        return &quot;Please check your internet connection&quot;;<br>      case const (ServerError):<br>        return &quot;Server Error&quot;;<br>      case const (CommonError):<br>        return &quot;Something went wrong&quot;;<br>      default:<br>        return &quot;Something went wrong&quot;;<br>    }<br>  }<br>}</pre><p>Our domain layer will only throw errors. The presentation layer needs to convert this errors into suitable messages for the users. Since showing a message is a responsibility of the presentation layer, we add the mapper in this layer.</p><p>Your file-folder structure should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*buRshJvEOUQDngxKKt-OAA.png" /></figure><p>So far, we have created the core network module, and error handling for our application. On the next part we will implement the domain and the data layer.</p><p><a href="https://github.com/AliAkberAakash/weather_clean_architecture_flutter/tree/part_1">Here</a> you can find the github repo for the code.</p><p>If you have any questions, feel free to leave a comment!</p><p><a href="https://medium.com/@ali852609/making-a-flutter-application-with-clean-architecture-part2-1424a4c97e03">Read Part 2 here.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f42b93431924" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Merge conflicts in git rebase]]></title>
            <link>https://medium.com/@ali852609/merge-conflicts-in-git-rebase-5d956edb0f6?source=rss-5882a491e8e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d956edb0f6</guid>
            <category><![CDATA[git-rebase]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Ali Akber]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 20:48:39 GMT</pubDate>
            <atom:updated>2023-06-04T20:48:39.706Z</atom:updated>
            <content:encoded><![CDATA[<p>I have recently been using git rebase and faced quite a hard time resolving merge conflicts. In this blog post, I talk about my understanding of it.</p><p>I created a feature branch from the main branch and added a few commits. When I made a PR I noticed there were new changes pushed to the main. It looked like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*eybPXvlcAhwnO47lutDWog.png" /></figure><p>main only had commits till C like the image above when I created my feature branch. But commit D got merged into main before my feature branch was ready to be merged.</p><p>Now, if the new changes, D had not touched any of the files to which I had made changes in the feature branch, rebasing would’ve been straightforward. Like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*lcvWSYdVnLeyx9SvM2RBlA.png" /></figure><p>You’ll notice E` F` and G` are not the same commits as E, F &amp; G. Because git creates completely new commits and puts them on top of D when rebasing.</p><p>However, in my case, commit D had changes in the same files as in commits E, F, and G. Now this is an issue. Why? because rebase tends to reset the base of the feature branch to the latest changes in the main branch which in this case is D. But since the same file had changes in both D and E, there was a merge conflict. We couldn’t just make D the base of the feature branch.</p><p>Now to fix the issue I had to fix the conflicts in D and E and make E`.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*8mHB_SWcO1MSNyi0syuKhQ.png" /></figure><p>But we are not done yet. Now that, we want to put the changes in commit F on top of E`, we need to resolve merge conflicts in E` and F (which is now re-written as F`). So we do that and continue with rebasing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*eHoSpdGNAg1dgLDaJNbkpw.png" /></figure><p>Finally, we come to commit G and fix the merge conflicts with F`, and add G` to the top.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*lcvWSYdVnLeyx9SvM2RBlA.png" /></figure><p>Although it looks visually the same as the picture without any merge conflicts, there was quite a lot of work to be done to make it like this. And it gets worse when you have more commits.</p><p>But, hey on the bright side, I learned something new. I got to dig around this topic. It might seem complex, but if you have good communication then fixing the conflicts becomes quite easy.</p><p>That’s it for this post. Comment with any questions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d956edb0f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Matrix Rotation]]></title>
            <link>https://medium.com/%E0%A6%AA%E0%A7%8D%E0%A6%B0%E0%A7%8B%E0%A6%97%E0%A7%8D%E0%A6%B0%E0%A6%BE%E0%A6%AE%E0%A6%BF%E0%A6%82-%E0%A6%AA%E0%A6%BE%E0%A6%A4%E0%A6%BE/matrix-rotation-9c709740f57e?source=rss-5882a491e8e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c709740f57e</guid>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[matrix]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[bangla]]></category>
            <dc:creator><![CDATA[Ali Akber]]></dc:creator>
            <pubDate>Sat, 11 Jan 2020 15:44:59 GMT</pubDate>
            <atom:updated>2020-01-11T15:44:59.553Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*D_MflaCZWZKX-aVNvt2h2g.png" /></figure><p>Category: Job Interview Preparation</p><p>Level : beginner</p><p><strong>সমস্যার বিবরণ:</strong></p><p>একটি NxN ম্যাট্রিক্স দেয়া আছে, একে ৯০ ডিগ্রি কোনে ঘুরাতে হবে।</p><p>sample input :</p><pre>a b c d<br>e f g h<br>i j k l<br>m n o p</pre><p>sample output :</p><pre>m i e a<br>n j f b<br>o k g c<br>p l h d</pre><p><strong>সমাধান :</strong></p><p>সমস্যাটি সমাধান করার জন্য শুরুতেই আমরা ম্যাট্রিক্স এর বৈশিষ্ট্য গুলো দেখি। আমাদের কাছে একটি NxN ম্যাট্রিক্স আছে যা একটি টু ডাইমেনশনাল ম্যাট্রিক্স, অর্থাৎ আমাদের 4 টা তল আছে। ম্যাট্রিক্স এর প্রত্যেকটি ইলিমেন্ট এর জন্যে 3 টি করে প্রতিচ্ছবি আছে। মানে হল, আমরা যদি a ইলিমেন্টটির কথা চিন্তা করি তাহলে এর প্রতিচ্ছবি গুলো হলো d,p এবং m.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*jRub0g4CwQI_BGalNwq8Dw.png" /><figcaption>Counterparts of ‘a’</figcaption></figure><p>এখন ম্যাট্রিক্সটিকে রোটেট করার জন্যে আমরা a এবং এর প্রতিচ্ছবি গুলোকে এক ঘর করে সামনে বাড়াবো। এর মানে কি? আমরা যদি a কে d এর জায়গায়, d কে p এর জায়গায়, p কে m এর জায়গায় এবং m কে a এর জায়গায় আনি তাহলেই আমরা এই 4 টি ইলিমেন্টকে সফলভাবে swap করে ফেলতে পারি। এই একই কাজ আমরা প্রত্যেকটি ইলিমেন্ট এর জন্যে করলে ম্যাট্রিক্সটি 90 ডিগ্রি তে রোটেট হবে।</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*VT0psp2vfq5GnUdjeSXr2A.png" /></figure><p>এখন আমরা 4 টা ভ্যারিয়েবল একসাথে swap কিভাবে করব? ম্যাট্রিক্সের 4 টি তলকে আমরা top , left , bottom আর right নাম দেই। তাহলে আমাদের swap এর এলগরিদমটা অনেকটা এরকম হবে :</p><pre>temp = top;<br>top = left;<br>left = bottom;<br>bottom = right;<br>right = temp;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*pX7EkasuQn5Ns7e-VaSrSg.png" /><figcaption>Four sides of the matrix</figcaption></figure><p>এবার আমরা আবার প্রথম ধাপ এ ফিরে আসি, আমি বলেছিলাম ম্যাট্রিক্সের প্রত্যেকটি ইলিমেন্টকে ৯০ ডিগ্রি রোটেট করব কিন্তু আসলে এর প্রয়োজন নেই। একটু ভালোভাবে লক্ষ্য করলে আমরা দেখব যে একটি ইলিমেন্টকে রোটেট করলে আরও ৩ টি ইলিমেন্ট রোটেট হচ্ছে, অর্থাৎ প্রত্যেক ধাপে আমরা 4 টি ইলিমেন্টকে একসাথে রোটেট করছি। বিষয়টিকে আরও সহজ করতে আমরা ম্যাট্রিক্সটিকে কয়েকটি লেয়ার এ ভাগ করতে পারি। এখন প্রত্যেকটি লেয়ার এর জন্যে আমরা যদি কোন একটি রো কে রোটেট করি, সম্পূর্ণ লেয়ারটি রোটেট হয়ে যাবে।</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*ZzJZs275N6YkWzsZ-tnzew.png" /><figcaption>Divided in layers</figcaption></figure><p>তাহলে এবার অ্যালগরিদম তৈরি করা শুরু করি,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66299c3823fbf37e2fc4c66642b730b4/href">https://medium.com/media/66299c3823fbf37e2fc4c66642b730b4/href</a></iframe><p>এখানে n হলো মোট রো এর সংখ্যা। কিন্তু আমরা n/2 বার ট্র্যাভারস করছি, এর কারণ হল প্রত্যেক rotation এ আমরা ২ টি করে রো রোটেট করছি। তাই অর্ধেক রো এর জন্য করলেই কাজ হয়ে যাচ্ছে। আর বিজোড় সংখ্যক রো এর ক্ষেত্রে, আমাদের একদম মাঝের লেয়ার এ একটা মাত্র ইলিমেন্ট থাকবে, যাকে রোটেট করলেও এর অবস্থানের কোনো পরিবর্তন হবে না। তাই আমরা একে নিয়ে মাথা ঘামাবো না।</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*-LFxU9dhnx6NaiGiBsDTcQ.png" /><figcaption>The middle layer is not affected in case of odd number of rows</figcaption></figure><p>এবার আসি মেইন পার্ট এ, রো গুলোকে রোটেট করা। আমরা যদি শুরুতে বলা উপায়ে একটি রো এর সবগুলো মেম্বার কে 4 way swap করি, তাহলে ওই রো টি রোটেট হয়ে যাবে। এখানে লক্ষ্য করার মত একটি বিষয় হল একটি রো এর শুরুর ইলিমেন্ট রোটেট করলে শেষের ইলিমেন্টটিও রোটেট হয়ে যায়, তাই শেষের ইলিমেন্টটিকে আবার রোটেট করার প্রয়োজন নেই।</p><p>অ্যালগরিদমটি দাড়ায় :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fa27013f9f9457e588435bb6ad08fe2/href">https://medium.com/media/7fa27013f9f9457e588435bb6ad08fe2/href</a></iframe><p>এখানে একটা ভুল খেয়াল করেছ? প্রথম ফর লুপটির মাধ্যমে আমরা প্রত্যেকটি লেয়ার ট্র্যাভারস করেছি, এবং দ্বিতীয় ফর লুপটির মাধ্যমে প্রতিটি লেয়ারের শুরু থেকে শেষ পর্যন্ত ট্র্যাভারস করেছি। কিন্তু প্রত্যেক লেয়ার এর শুরু আর শেষ কিন্তু একই না। যেমন প্রথম লেয়ার এর শুরু 0 এবং শেষ n-1 (0 based index) , কিন্তু দ্বিতীয় লেয়ার এর শুরু 1 এবং শেষ n-2, পরবর্তী লেয়ার গুলোর জন্যেও শুরু এবং শেষ এভাবে চেঞ্জ হবে। তাহলে প্রত্যেক ধাপে আমাদের শুরু এবং শেষ অ্যাডজাস্ট করতে হবে। কাজটি আমরা এভাবে করতে পারি</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96ce15786b7d050afc8315171277d126/href">https://medium.com/media/96ce15786b7d050afc8315171277d126/href</a></iframe><p>আমাদের অ্যালগরিদমটি প্রায় রেডি, এখন শুধু 4 way swap ইমপ্লিমেন্ট করা বাকি। এ কাজটি বেশ সোজা, যা আমরা পোষ্ট এর শুরুতেই দেখেছি। প্রথমে আমরা একটি অফসেট তৈরি করি, যেখানে, offset = i-first ; এই অফসেটটি ব্যাবহার করে আমরা প্রত্যেকটি ইলিমেন্ট এর জন্যে তার প্রতিচ্ছবি গুলোকে নির্ণয়য় করতে পারবো। আমাদের ফাইনাল অ্যালগরিদমটি দাড়ায় :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fc97e7620f86d4267503d7c2703f75d/href">https://medium.com/media/6fc97e7620f86d4267503d7c2703f75d/href</a></iframe><p>swap এর কোডটি অনেক বড় মনে হলেও আসলে তেমন কিছুই না। তোমরা একবার হাতে কলমে সিমুলেট করলে দেখবে, আমাদের top যদি matrix[first][i] হয়, তাহলে</p><p>left হবে matrix[last-offset][first]</p><p>bottom হবে matrix[last][last-offset]</p><p>এবং right হবে matrix[i][last]</p><p>ব্যাস কাজ শেষ। আমরা সকসেস্ফুল ভাবে ম্যাট্রিক্সটিকে রোটেট করেছি।</p><p>সম্পূর্ণ কোডটি পাওয়া যাবে <a href="https://gist.github.com/AliAkberAakash/ea336326a246bd6c7ce813267545626b">এইখানে।</a></p><p>Reference : Cracking the Coding Interview by Gayle Laakmann McDowell</p><p>টিউটোরিয়ালটি পড়ার জন্যে সবাইকে ধন্যবাদ। Don’t forget to clap if u liked it! ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c709740f57e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E0%A6%AA%E0%A7%8D%E0%A6%B0%E0%A7%8B%E0%A6%97%E0%A7%8D%E0%A6%B0%E0%A6%BE%E0%A6%AE%E0%A6%BF%E0%A6%82-%E0%A6%AA%E0%A6%BE%E0%A6%A4%E0%A6%BE/matrix-rotation-9c709740f57e">Matrix Rotation</a> was originally published in <a href="https://medium.com/%E0%A6%AA%E0%A7%8D%E0%A6%B0%E0%A7%8B%E0%A6%97%E0%A7%8D%E0%A6%B0%E0%A6%BE%E0%A6%AE%E0%A6%BF%E0%A6%82-%E0%A6%AA%E0%A6%BE%E0%A6%A4%E0%A6%BE">প্রোগ্রামিং পাতা</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Hash Table with C++]]></title>
            <link>https://medium.com/%E0%A6%AA%E0%A7%8D%E0%A6%B0%E0%A7%8B%E0%A6%97%E0%A7%8D%E0%A6%B0%E0%A6%BE%E0%A6%AE%E0%A6%BF%E0%A6%82-%E0%A6%AA%E0%A6%BE%E0%A6%A4%E0%A6%BE/hash-table-35c4ed6874e1?source=rss-5882a491e8e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/35c4ed6874e1</guid>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[hash-table]]></category>
            <category><![CDATA[bangla]]></category>
            <category><![CDATA[hash-function]]></category>
            <dc:creator><![CDATA[Ali Akber]]></dc:creator>
            <pubDate>Thu, 12 Sep 2019 05:41:56 GMT</pubDate>
            <atom:updated>2019-09-12T05:46:48.064Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zBOjT4oOC5N0_gEzFALQ9w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@pisitheng?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pisit Heng</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>হ্যাশ টেবিল হচ্ছে একটি বিশেষ ডেটা স্ট্রাকচার যার মাধ্যমে আমরা কী-ভ্যালু পেয়ার হিসেবে ডেটা স্টোর করতে পারি। এটি অনেকটা অ্যারের মত ফরম্যাটে কাজ করে, আমরা প্রতিটা ইলিমেন্টকে তার ইনডেক্স এর মাধ্যমে এক্সেস করতে পারি। পার্থক্য হচ্ছে হ্যাশ টেবিলে আমরা ইনডেক্স হিসেবে ইন্টেজার ছাড়াও অন্যান্য ডেটা টাইপ (স্ট্রিং, কাস্টম অব্জেক্ট ইত্যাদি) ব্যবহার করতে পারি।</p><h4>Hashing :</h4><p>হ্যাশ টেবিলের ইনডেক্স বের করার জন্য বিভিন্ন উপায় আছে, এদেরকে হ্যাশিং টেকনিক বা হ্যাশিং বলা হয়। মনে কর আমরা কিছু শিক্ষার্থীর রেজিস্ট্রেশন নম্বর এর প্রেক্ষিতে নাম স্টোর করতে চাই। অর্থাৎ, কী হচ্ছে রেজিস্ট্রেশন নম্বর এবং ভ্যালু হচ্ছে শিক্ষার্থীর নাম। ধরা যাক প্রতিটা রেজিস্ট্রেশন নম্বর 10 ডিজিটের। এখন, আমাদের যদি জানা না থাকে যে রেজিস্ট্রেশন নম্বর কত থেকে শুরু এবং কত তে শেষ, তাহলে আমাদের 10 ডিজিটের সকল সংখ্যার জন্য একটি টেবিল তৈরি করতে হবে যার সাইজ হবে 10¹⁰। এটি প্রায় অসম্ভব বেপার।</p><p>এখন যদি আমাদের বলা হয়, সব মিলিয়ে 10 জন শিক্ষার্থীর ডেটা স্টোর করতে হবে, তাহলে আমাদের কাজ অনেক সহজ হয়ে যায়। প্রথম 10 টা 10 ডিজিট নিলেই কাজ হয়ে যাচ্ছে। কিন্তু যদি বলা হয় শিক্ষার্থীদের রেজিস্ট্রেশন নম্বর গুলো কোনো সিরিয়াল মেনে চলে না তাহলে কি হবে? 0000000000 থেকে 9999999999 পর্যন্ত যেকোনো সংখ্যা রেজিস্ট্রেশন নম্বর হতে পারে। আমরা কিন্তু আবার আগের জায়গায় পৌঁছে গেলাম।</p><p>তাহলে উপায় কি? উপায় হল হ্যাশিং। প্রতিটা রেজিস্ট্রেশন নম্বরকে আমরা এমন ভাবে ম্যাপিং করব যাতে 0 থেকে 9 এর মধ্যে আমরা এদেরকে রাখতে পারি। একটি পদ্ধতি হল আমরা রেজিস্ট্রেশন নম্বরের প্রতিটা ডিজিটকে যোগ করে 10 দিয়ে মডুলো করতে পারি। যেই ভ্যালু টা আমরা পাচ্ছি সেইটাই হচ্ছে হ্যাশ ভ্যালু। এই ভ্যালুটা সবসময় 0–9 এর মধ্যে থাকবে। তাহলে আমরা মাত্র 10 টি স্থান ব্যাবহার করেই রেজিস্ট্রেশন নম্বরটি স্টোর করতে পারবো।</p><pre>hash(1223583790) = (1+2+2+3+5+8+3+7+9+0) % 10 = 40 % 10 = 0<br>hash(4400023398) = (4+4+0+0+0+2+3+3+9+8) % 10 = 35 % 10 = 5<br>hash(9991305612) = (9+9+9+1+3+0+5+6+1+4) % 10 = 47 % 10 = 7</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*idkZTxEAJr1eM6mgGNNBHg.png" /><figcaption>Visual Representation of our proposed hash Table</figcaption></figure><p>হ্যাশিং করার জন্য বিভিন্ন পদ্ধতি রয়েছে। এদের মধ্যে উল্লেখযোগ্য হল ট্রানকেশন, ফোল্ডিং, মডুলার অ্যারিথমেটিক ইত্যাদি। আমাদের ব্যবহার করা মেথডটি মডুলার অ্যারিথমেটিকের মধ্যে পরে। উদাহরণের জন্য 10 দ্বারা মডুলো করা হলেও, <a href="https://www.quora.com/Why-are-prime-numbers-used-for-constructing-hash-functions">মডুলো করার ক্ষেত্রে প্রাইম সংখ্যা ব্যবহার করা উত্তম।</a></p><h4><strong>Hash Function :</strong></h4><p>হ্যাশিং টেকনিক ইমপ্লিমেন্ট করার ফাংশনকেই <strong>হ্যাশ ফাংশন</strong> বলে। এটি একটি কী ইনপুট হিসেবে নিবে এবং একটি হ্যাশ ভ্যালু রিটার্ন করবে।</p><pre>int hash_value = hashFunction(key)</pre><p>হ্যাশ ফাংশন ইমপ্লিমেন্ট করার সময় নিচের বিষয়গুলো খেয়াল রাখতে হবে,</p><p>১। হ্যাশ ভ্যালু নির্ণয় করার প্রক্রিয়াটি সহজ হতে হবে</p><p>২। কলিশন কম হবে</p><h4><strong>Collision :</strong></h4><p>আগের উদাহরণটিতে আমরা কিছু শিক্ষার্থীর রেজিস্ট্রেশন নম্বর এর প্রেক্ষিতে নাম স্টোর করেছি। আমরা হ্যাশ ভ্যালু বের করার জন্য যে টেকনিক ব্যাবহার করেছি তা সবসময় ইউনিক ভ্যালু দেয় না। কখনো কখনো একাধিক কী এর জন্যে একই হ্যাশ ভ্যালু আসতে পারে।</p><p>যেমন :</p><pre>hash(1223583794) = (1+2+2+3+5+8+3+7+9+4) % 10 = 44 % 10 = 4<br>hash(5904053170) = (5+9+0+4+0+5+3+1+7+0) % 10 = 34 % 10 = 4</pre><p>আর এটি শুধু মাত্র আমাদের ব্যাবহার করা হ্যাশিং পদ্ধতির জন্যে নয়, অন্য যেকোনো পদ্ধতিতেও একই সমস্যা হতে পারে। এ সমস্যাটিকে বলা হয় কলিশন। বাস্তবে কোনো হ্যাশিং টেকনিকই সম্পূর্ণভাবে কলিশন মুক্ত নয়।</p><h4><strong>Collision Resolution :</strong></h4><p>কলিশন সমস্যা সমাধান করার জন্য বিভিন্ন পদ্ধতি আছে। এদের সাধারণত 2 ভাগে ভাগ করা যায়।</p><p>১। ওপেন হ্যাশিং</p><p>২। ক্লোজড হ্যাশিং</p><p>টিউটোরিয়ালটিকে ছোট রাখতে এই পর্বে আমরা শুধু ওপেন হ্যাশিং পদ্ধতিটি দেখব। আগামী পর্বে আমরা ক্লোজড হ্যাশিং নিয়ে আলোচনা করব।</p><h4>Open Hashing (Separate Chaining):</h4><p>কলিশন রেজুলশন করার সবথেকে কমন পদ্ধতি হচ্ছে সেপারেট চেইনিং বা ওপেন হ্যাশিং। এ ক্ষেত্রে আমরা একটি লিঙ্কড লিস্ট এর অ্যারে ব্যাবহার করতে পারি। দুটি কী এর হ্যাশ ভ্যালু একই হলে তাদেরকে আমরা একই ইনডেক্সে রাখবো। অ্যারের প্রতিটা আইটেম একেকটি লিঙ্কড লিস্ট হওয়ায়, আমরা একই ইনডেক্সে একাধিক ডেটা স্টোর করতে পারব।</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*3_S5UuUOdPyF3o78iz_fvQ.png" /><figcaption>Source :<a href="https://www.hackerearth.com/ja/practice/data-structures/hash-tables/basics-of-hash-tables/tutorial/"> https://he-s3.s3.amazonaws.com/media/uploads/0e2c706.png</a></figcaption></figure><p>এ স্ট্রাকচারে একটি ডেটা খুঁজে বের করার কমপ্লেক্সিটি হবে সেই ডেটা যে ইনডেক্সে আছে সেই ইনডেক্সের লিস্ট এর লেংথ এর সমান। সব ডেটা সুষ্ঠু ভাবে বণ্টন করতে পারলে প্রত্যেকটা লিঙ্কড লিস্ট এর লেংথ সমান হবে, যা একটি ধ্রুবক। অতএব একটি ডেটা খুঁজে বের করার কমপ্লেক্সিটি হবে <em>O(1) [length of list &lt;&lt; n]</em></p><h3>Implementation:</h3><p>হ্যাশ টেবিল ইমপ্লিমেন্টেশন এর জন্যে আমরা C++ এর টু ডাইমেনশনাল ভেক্টর ব্যবহার করব। তোমরা যারা raw লিঙ্কড লিস্ট ইমপ্লিমেন্ট করতে চাও তারা <a href="https://gist.github.com/AliAkberAakash/30b2de01b36112305e7984a684ef5242">এই কোডটি</a> দেখতে পারো। যারা ভেক্টর সম্পর্কে জানো না তারা এই <a href="https://medium.com/@ali852609/introduction-to-stl-part-i-7ce17f97bfc0">টিউটোরিয়ালটি</a> দেখতে পারো।</p><h4>Single Item Structure :</h4><pre>struct item{    <br>    int key;    <br>    string name;     <br>    item(int _key, string _name)    <br>    {        <br>        key = _key;        <br>        name = _name;    <br>    }<br>};</pre><p>আমাদের স্ট্রাকচারে একটি কী এবং একটি ভ্যালু থাকবে। ইনিশিয়ালাইজেশন এর জন্যে আমরা একটি কন্সট্রাক্টর তৈরি করেছি।</p><h4>Hash Table Declaration :</h4><pre>vector&lt;item&gt; hashTable[11];  //11 hashValues</pre><p>প্রত্যেকটি ভেক্টর একেকটি লিঙ্কড লিস্ট এরমত কাজ করবে। তাই ইমপ্লিমেন্টেশনের ঝামেলা এড়াতে আমরা লিঙ্কড লিস্ট এর অ্যারের পরিবর্তে ভেক্টর এর অ্যারে অর্থাৎ টু ডাইমেনশনাল ভেক্টর ভ্যাবহার করেছি। তোমরা Java তে অ্যারেলিস্ট দিয়েও ট্রাই করে দেখতে পারো।</p><h4>Hash Function:</h4><pre>int hashFunction(int key){    <br>    int hashValue=0;     <br>    while(key&gt;0)    <br>    {        <br>        hashValue+=key%10; //add digits one by one        <br>        key=key/10;    <br>    }     <br>    return hashValue%11; //return the hashValue modulo by 11<br>}</pre><p>হ্যাশ ফাংশনটিতে আমরা আমাদের কি এর প্রত্যেকটি ডিজিট যোগ করে তাকে 11 দিয়ে মডুলো করেছি।</p><h4>Insert Function :</h4><pre>void insertItem(int key, string name){    <br>    int hashValue = hashFunction(key); <br>    hashTable[hashValue].push_back(item(key,name));<br>}</pre><p>প্রথমে আমরা কী এর জন্য হ্যাশ ভ্যালু নির্ণয় করেছি। হ্যাশভ্যালু অনুযায়ী ভেক্টর এক্সেস করে তাতে আমাদের আইটেম পুশ করেছি। ভেক্টর এর ক্ষেত্রে push_back() করলে আইটেমটি সবার শেষে গিয়ে যুক্ত হবে।</p><h4>Search Function :</h4><pre>bool searchItem(int key){   <br>    int i,hashValue = hashFunction(key);<br>    for(i=0; i&lt;hashTable[hashValue].size(); i++)<br>         if(hashTable[hashValue][i].key == key)            <br>             return true;    <br>    return false;<br>}</pre><p>সার্চ করার জন্য আমরা আগে হ্যাশভালু বের করে নিয়েছি। এইবার হ্যাশভ্যালু অনুযায়ী ভেক্টরটিকে ট্রাভারস করে আমাদের ইলিমেন্টটিকে খুঁজেছি।</p><h4>Delete Function :</h4><pre>bool deleteItem(int key){    <br>    int i,hashValue = hashFunction(key);<br>    for(i=0; hashTable[hashValue].size(); i++) {       <br>        if(hashTable[hashValue][i].key == key) {            <br>         hashTable[hashValue].erase(hashTable[hashValue].begin()+i);            <br>         return true;        <br>        }<br>     }     <br>     return false;<br>}</pre><p>ডিলিট করার জন্য আমরা অনেকটা সার্চ ফাংশন এর মতই কাজ করেছি। শুধু এই ক্ষেত্রে আমরা ইলিমেন্টটি খুঁজে পেলে <a href="http://www.cplusplus.com/reference/vector/vector/erase/">vector :: erase()</a> ফাংশনের মাধ্যমে তা ডিলিট করে দিয়েছি।</p><p>সম্পূর্ণ কোডটি পাওয়া যাবে <a href="https://gist.github.com/AliAkberAakash/91ba9ae563617a24a353450b2f662555">এইখানে</a>।</p><p>টিউটোরিয়ালটি পড়ার জন্যে সবাইকে ধন্যবাদ। আগামী পর্বে আমরা কলিশন রেজুলশন নিয়ে আরও বিস্তারিত দেখব।</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35c4ed6874e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E0%A6%AA%E0%A7%8D%E0%A6%B0%E0%A7%8B%E0%A6%97%E0%A7%8D%E0%A6%B0%E0%A6%BE%E0%A6%AE%E0%A6%BF%E0%A6%82-%E0%A6%AA%E0%A6%BE%E0%A6%A4%E0%A6%BE/hash-table-35c4ed6874e1">Introduction to Hash Table with C++</a> was originally published in <a href="https://medium.com/%E0%A6%AA%E0%A7%8D%E0%A6%B0%E0%A7%8B%E0%A6%97%E0%A7%8D%E0%A6%B0%E0%A6%BE%E0%A6%AE%E0%A6%BF%E0%A6%82-%E0%A6%AA%E0%A6%BE%E0%A6%A4%E0%A6%BE">প্রোগ্রামিং পাতা</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Development Course Outline]]></title>
            <link>https://medium.com/@ali852609/android-development-course-outline-79c805e1933f?source=rss-5882a491e8e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/79c805e1933f</guid>
            <category><![CDATA[course]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[final-project]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[final-presentation]]></category>
            <dc:creator><![CDATA[Ali Akber]]></dc:creator>
            <pubDate>Wed, 24 Jul 2019 13:48:08 GMT</pubDate>
            <atom:updated>2019-07-31T13:15:13.972Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Prerequisites:</strong></p><ul><li><strong>Basic java</strong> (if-else, switch case, for loop, while loop, operators, array, functions, recursion etc).</li><li><strong>Basic OOP concept</strong> (Class, object, inheritance,polymorphism, encapsulation, interface etc).</li></ul><p><strong>Course Duration:</strong> 3 months (12 weeks)</p><p><strong>Total classes:</strong> 24/26</p><p><strong>Possible start date</strong>: 20/8/2019</p><h4><strong>Syllabus:</strong></h4><ul><li><strong>Week 1 :</strong> Introduction to android, environment setup, OOP concept review.</li><li><strong>Week 2:</strong> First app, TextView, ImageView, Buttons, EditTexts, 1 mini project.</li><li><strong>Week 3:</strong> Spinner, Checkbox, RadioButton, Toast, WebView, Manifest.</li><li><strong>Week 4:</strong> Activity, lifecycle, saving the state, themes, customization, Intents.</li><li><strong>Week 5:</strong> ScrollView, ConstraintLayout, Toast, Floating action Button, external libraries.</li><li><strong>Week 6:</strong> ListView, Adapters, Actionbar.</li><li><strong>Week 7:</strong> AlertDialog, Fragments, FrameLayout.</li><li><strong>Week 8:</strong> Navigation Drawer. 1 mini project.</li><li><strong>Week 9:</strong> TabLayout, ViewPager. 1 mini project</li><li><strong>Week 10</strong>: SQLite database. 1 full project (Student info system or Library management)</li><li><strong>Week 11:</strong> Firebase part 1.</li><li><strong>Week 12</strong>: Firebase part 2. Final project.</li><li><strong>Week 13</strong>: Extra time for backup.</li></ul><blockquote><strong>NB: If you fail to attend any class, you have to cover it yourself by taking help from your classmates. Classes will not be repeated. Each student must bring own laptop.</strong></blockquote><h4><strong>Course Fee:</strong></h4><p>8k to be paid fully before the course starts.</p><h4><strong>Registration:</strong> <a href="https://docs.google.com/forms/d/e/1FAIpQLSeWMLj4rPEHQpEiPS1pRsx06IYghZgmC7YMJ29OOz_Dy2mvKg/viewform?usp=sf_link">Fill this form.</a></h4><h4><strong>Course Prepared by:</strong></h4><p>Ali Akber Aakash</p><p>Android Developer at Megaminds Web and IT Solutions</p><h4><strong>Contact:</strong></h4><p>Phone: 01683151988</p><p>Email: ali852609@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79c805e1933f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to STL Part-I]]></title>
            <link>https://medium.com/@ali852609/introduction-to-stl-part-i-7ce17f97bfc0?source=rss-5882a491e8e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ce17f97bfc0</guid>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[stl]]></category>
            <category><![CDATA[vector]]></category>
            <category><![CDATA[c-programming]]></category>
            <dc:creator><![CDATA[Ali Akber]]></dc:creator>
            <pubDate>Sat, 06 Jul 2019 17:25:20 GMT</pubDate>
            <atom:updated>2019-07-07T04:55:21.320Z</atom:updated>
            <content:encoded><![CDATA[<p>Vectors</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bWMuuVolDTe1fmsghjOJ7A.png" /></figure><p>C++ এর মাধ্যমে প্রব্লেম সল্ভিং করার একটি অন্যতম প্রধান টুল হল STL (Standard Template Library) । আমি যখন নতুন নতুন ডেটা স্ট্রকচার শিখি, তখন শুধু ভাবতাম কন্টেস্ট টাইমে এইগুলা কিভাবে ইমপ্লিমেন্ট করব। একটা ইমপ্লিমেন্ট করতে করতেই তো সব সময় চলে যাবে। পরবর্তীতে আমি STL এর পরিচয় পাই। প্রয়োজনীয় প্রায় সকল ডেটা স্ট্রাকচারই এইখানে ইমপ্লিমেন্ট করা আছে। শুধু তাই নয়, বেশ কিছু এলগরিদম ও এখানে ফাংশন হিসেবে পাওয়া যাবে। শুধু একটি ফাংশন কল করে সর্টিং এর মত ঝামেলার কাজও করা যাবে। মজার না? 😁</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHD6V1lwY_ZHtH5A2Gy1xg.jpeg" /></figure><p>নতুন প্রোগ্রামারদের মধ্যে STL ব্যাবহারে কিছুটা ভীতি থাকে, কিন্তু এ ভীতি কাটিয়ে উঠতে হবে। STL এর প্রতিটি ফাংশন অনেক বেশি ইফিশিয়েন্ট এবং টাইম সেভার। আর এটি ব্যবহার করাও অনেক সোজা। একবার ব্যবহার করা শিখলে তখন সবকিছুতে শুধু STL ই ব্যবহার করবা 😎 তাহলে শুরু করা যাক? 😀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e2b4n40DEYujjhv0cktFDw.jpeg" /><figcaption>source: <a href="https://www.pinterest.com/pin/463730092881935997/">https://www.pinterest.com/pin/463730092881935997/</a></figcaption></figure><p>এই পোস্ট এ আমরা STL এর অনেক কমন একটা কন্টেইনার ক্লাস ‘VECTOR’ সম্পর্কে শিখব। ভেক্টরের কাজ অনেকটা ডায়নামিক অ্যারের মত। একটা নতুন ইলিমেন্ট অ্যাড করলে বা রিমুভ করলে ভেক্টর নিজে নিজেই রিসাইজ হতে পারে। আমরা ইন্টেজার টাইপের একটা অ্যারেতে যেমন অনেকগুলো ইন্টেজার রাখতে পারি, একইভাবে ইন্টেজার টাইপের একটা ভেক্টরে আমরা অনেকগুলো ইন্টেজার ভ্যারিয়েবল রাখতে পারবো। এর জন্য প্রথমে আমাদের ভেক্টরটিকে ডিক্লেয়ার করতে হবে।</p><p>vector &lt;int&gt; v;</p><p>ভেক্টর ব্যবহার করার আগে অবশ্যই ভেক্টরের হেডার ফাইল include করে নিতে হবে । আমি সাধারণত আলাদা আলাদা হেডার ফাইল include না করে <a href="https://stackoverflow.com/questions/25311011/how-does-include-bits-stdc-h-work-in-c">#include&lt;bits/stdc++.h&gt;</a> দিয়ে দেই। এতে করে ঝামেলা ও কমে, সময় ও বাচে।</p><p>ভেক্টরের বেশ কিছু বিশেষ সুবিধা রয়েছে যা সাধারণ অ্যারেতে নেই। একে একে দেখা যাক সেগুলো।</p><ul><li>ভেক্টরের একটি অন্যতম সুবিধা হচ্ছে এতে পেছন দিক থেকে ইলিমেন্ট অ্যাড করা যায়। এর জন্য আমাদের শেষের ইনডেক্সটি জানতে হবে না। শুধু নিচের ফাংশনটি কল করলেই ভেক্টরের শেষে একটি করে নতুন ইলিমেন্ট যুক্ত হবে।</li></ul><p>v.push_back(10);</p><p>v.push_back(5);</p><p>v.push_back(13);</p><ul><li>ভেক্টরের সাইজ জানতে আমরা v.size() ফাংশনটি কল করতে পারি। এ ফাংশনটি ভেক্টরটির ইলিমেন্ট সংখ্যা রিটার্ন করে।</li><li>একটি ভেক্টর খালি কিনা তা v.empty() ফাংশনটির মাধ্যমে জানা যায়। ভেক্টরটি খালি হলে এটি true রিটার্ন করবে আর না হলে false ।</li><li>একটি ভেক্টরের কোন উপাদানকে এক্সেস করতে reference operator [] ব্যবহার করতে পারবো। আবার at(index) এর মাধ্যমেও একই কাজ করা যায়।</li></ul><p>x = v[0]; //x has the 0&#39;th element<br>y = v.at(0); //y has the 0&#39;th element</p><ul><li>কোন ভেক্টর থেকে সবগুলো ইলিমেন্ট মুছে ফেলতে v.clear() ফাংশনটি ব্যবহার করা যায়।</li></ul><p>v.clear(); <br>cout&lt;&lt;v.size()&lt;&lt;endl; //output is 0</p><ul><li>ভেক্টরের কোনো নির্দিষ্ট একটি পজিশনে একটি ইলিমেন্ট ইন্সারট করতে আমরা v.insert(position,val) ব্যবহার করতে পারি। এইখানে (positon-1) তম স্থানে val ইলিমেন্টটি যুক্ত হবে।</li></ul><p>v.insert(v.begin()+2,10);<br>cout&lt;&lt;v[1]&lt;&lt;endl; //prints 10</p><p>তোমরা অনেকে হয়ত দেখে অবাক হচ্ছো v.begin()+2 কেন লিখলাম। v.begin() একটি ইটারেটর রিটার্ন করে। এটি ভেক্টরের প্রথম ইলিমেন্ট এর অ্যাড্রেস নির্দেশ করে। সহজ ভাষায় এটি একটি পয়েন্টার জাতীয় ভ্যারিয়েবল। আমাদের ভেক্টরটি শুরু হয়েছে v.begin() থেকে। v.begin()+2 মানে ভেক্টরের ৩য় ঘর। যেহেতু insert() ফাংশনটি এক ঘর আগে insert করে সেহেতু ২য় ঘরটিতে 10 ভ্যালুটি যুক্ত হয়েছে।</p><p>ভেক্টরের এ সকল অপারেশনের আরও উদাহরণ দেখতে চাইলে <a href="https://gist.github.com/AliAkberAakash/302e899c479109546ed72381c60c5cd0">এই কোডটি</a> দেখতে পারো।</p><p>আমরা চাইলে 2D ভেক্টর ও তৈরী করতে পারি। এর জন্য আমাদেরকে ভেক্টরের অ্যারে তৈরী করতে হবে। এক্ষেত্রে আমাদের রো সংখ্যা আগে থেকে বলে দিতে হবে।</p><p>vector &lt;int&gt; v[10]; <br> <br>উপরের ডিক্লারেশনটি ১০ টি ভেক্টরের একটি অ্যারে তৈরী করবে। আমরা প্রতিটি ভেক্টরকে v[position] এর মাধ্যমে এক্সেস করতে পারবো এবং এর উপর ভেক্টরের সকল অপারেশন চালাতে পারবো। একটি ভেক্টরের নির্দিষ্ট স্থানের কোনো ইলিমেন্টকে এক্সেস করতে v[row][column] এই ফরম্যাট ব্যবহার করব।</p><p>v[1][5]; //access the 6th element of the 2nd vector</p><p>2D ভেক্টরের উদাহরণ দেখতে <a href="https://gist.github.com/AliAkberAakash/58f739f1e4aa0689b9d8c9064ec3302d">এই কোডটি</a> দেখতে পারো</p><p>আমরা ইন্টেজার, ফ্লোট, ডাবল, ক্যারেক্টার যেকোনো টাইপের এমনকি কোন ক্লাস এর অবজেক্ট টাইপেরও ভেক্টর ব্যবহার করতে পারবো। ভেক্টর টাইপের ও ভেক্টর ব্যবহার করা সম্ভব। এটা তোমাদের জন্যে বাড়ির কাজ রইল 😉 ।</p><p>এতক্ষণ যা পড়লে তার সবই ছিল ভেক্টরের বেসিক। এগুলো ছাড়াও ভেক্টরের আরও অনেক ফাংশন আছে। উপরের ফাংশনগুলো ভালোমতো শেখা হয়ে গেলে তোমরা ভেক্টর নিয়ে আরও ঘাটিয়ে দেখতে পারো।</p><p>STL সিরিজটা কন্টিনিউ করব কি না তা পাঠকদের রেসপন্স এর উপর ডিপেন্ড করে। এই পোস্টটা কেমন লাগলো এবং আগামীতে এই সিরিজের আরও লেখা পড়তে চাইলে অবশ্যই কমেন্ট করে জানাবে। সম্পূর্ণ পোষ্টটি পড়ার জন্য সকলকে ধন্যবাদ।</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ce17f97bfc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Broadcast Receivers ( ব্রডকাস্ট রিসিভার এর সাথে পরিচিতি )]]></title>
            <link>https://medium.com/@ali852609/introduction-to-broadcast-receivers-%E0%A6%AC%E0%A7%8D%E0%A6%B0%E0%A6%A1%E0%A6%95%E0%A6%BE%E0%A6%B8%E0%A7%8D%E0%A6%9F-%E0%A6%B0%E0%A6%BF%E0%A6%B8%E0%A6%BF%E0%A6%AD%E0%A6%BE%E0%A6%B0-%E0%A6%8F%E0%A6%B0-%E0%A6%B8%E0%A6%BE%E0%A6%A5%E0%A7%87-%E0%A6%AA%E0%A6%B0%E0%A6%BF%E0%A6%9A%E0%A6%BF%E0%A6%A4%E0%A6%BF-5bd3e2590f5a?source=rss-5882a491e8e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bd3e2590f5a</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[scheduled-tasks]]></category>
            <category><![CDATA[broadcastreceiver]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-apps]]></category>
            <dc:creator><![CDATA[Ali Akber]]></dc:creator>
            <pubDate>Thu, 11 Oct 2018 17:36:29 GMT</pubDate>
            <atom:updated>2018-10-11T17:36:29.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*xMj_J0dCCF9wIuqEsBUYeA.png" /></figure><p>আমি যখন ব্রডকাস্ট রিসিভার প্রথমবারের মত শিখতে যাই তখন ব্রডকাস্ট রিসিভার জিনিসটা কী তা বুঝতে আমার একটু কষ্ট হয়। অনেকখানি গুগল করার পর আমি কিছুটা ধারনা পাই। এই টিউটোরিয়ালটি এজন্যেই লেখা যাতে ব্রডকাস্ট রিসিভার আসলে কী এবং এটা ব্যাবহার করা কত সোজা তা সম্পর্কে কিছুটা ধারনা পাওয়া যায়।</p><h4><strong>ব্রডকাস্ট রিসিভার </strong>কী<strong>?</strong></h4><p>ব্রডকাস্ট রিসিভার কী তা জানার আগে আমাদের যা বুঝতে হবে তা হল, ব্রডকাস্ট রিসিভার এর কাজ কী। অ্যান্ড্রয়েড এ বিভিন্ন ধরনের ইভেন্ট রয়েছে, যেমন : কল আসা, মেসেজ আসা, চার্জার কানেক্ট/ডিসকানেক্ট করা ইত্যাদি। অ্যান্ড্রয়েড অ্যাপ্লিকেশন তৈরি করার সময় এই ইভেন্টগুলো সম্পন্ন হওয়ার উপর ভিত্তি করে কিছু কাজ করতে হয়। উদাহরণ হিসেবে বলা যায়, কোন অ্যাপে শুধুমাত্র চার্জার কানেক্টেড থাকলেই ডাউনলোড হবে। এই কাজটি করতে আমরা চার্জার কানেক্টেড ইভেন্ট ব্যাবহার করতে পারি। এই ইভেন্টটি কখন ট্রিগার হল তা জানার জন্য আমাদের একটা লিসেনার দরকার। এই লিসেনার আমাদের অ্যাপ কে বলবে চার্জার কানেক্টেড হয়েছে এখন তুমি তোমার কাজ করতে পারো। এই লিসেনারটিই হচ্ছে ব্রডকাস্ট রিসিভার।</p><p>একটি অ্যাপ এ ব্রডকাস্ট রিসিভার ব্যাবহার করতে হলে, সেটি আমরা কোন ইভেন্ট সম্পর্কে জানার জন্য ব্যাবহার করছি তা অ্যাপকে জানাতে হবে। একে বলা হয় রেজিস্টার করা। অর্থাৎ আমরা যদি “চার্জার কানেক্টেড” এই ইভেন্টটি নিয়ে কাজ করতে চাই, তাহলে এই ইভেন্ট এর জন্য একটি ব্রডকাস্ট রিসিভার রেজিস্টার করতে হবে। এটি দুই ভাবে করা যায়, স্ট্যাটিক এবং ডায়নামিক। এ টিউটোরিয়ালে আমরা শুধু স্ট্যাটিকালি রেজিস্টার করার উপায়টি দেখব। নিচের সমস্যাটি দেখা যাক।</p><p>সমস্যার বর্ণনা : <br>আমরা চাচ্ছি এমন একটি অ্যাপ বানাবো যেটি চার্জার কানেক্টেড হলে আমাদেরকে একটি Toast দেখাবে “Charger Connected”। কাজটি করার জন্য আমরা একটি ব্রডকাস্ট রিসিভার রেজিস্টার করব যা চার্জার কানেক্টেড হওয়ার সাথে সাথে আমাদের অ্যাপ কে জানাবে। এর উপর ভিত্তি করে আমরা একটি Toast দেখাবো। তাহলে কোড শুরু করা যাক।</p><p>আমরা শুরুতেই নিজের সুবিধা মত নাম দিয়ে একটি নতুন প্রজেক্ট বানিয়ে নিব। আমাদের প্রোজেক্টে MyActivity নামের একটি মাত্র অ্যাক্টিভিটি আছে। এখানে আমরা কিছু পরিবর্তন করব না।</p><p>এবার আমরা একটা নতুন জাভা ক্লাস বানিয়ে নিব, যার নাম দিলাম MyBroadCastReceiver. এ ক্লাসটি BroadcastReceiver ক্লাসকে extend করবে।</p><pre><strong>public class </strong>MyBroadcastreceiver <strong>extends </strong>BroadcastReceiver {<br>    <br>}</pre><p>এবার আমরা প্রজেক্টের manifest ফাইলে চলে যাবো এবং &lt;application&gt; ট্যাগ এর মধ্যে নিচের লাইন গুলো পেস্ট করব :</p><blockquote><em>&lt;receiver android:name=”.MyBroadcastreceiver”&gt;<br> &lt;intent-filter&gt;<br> &lt;action android:name=”android.intent.action.ACTION_POWER_CONNECTED”/&gt;<br> &lt;/intent-filter&gt;<br>&lt;/receiver&gt;</em></blockquote><p>আমাদের ব্রডকাস্ট রিসিভারটি রেজিস্টার করা হয়ে গেল। একটু খেয়াল করলে দেখা যাবে intent-filter এর মধ্যে আমরা একটি একশন স্পেসিফাই করেছি। এর কারণ হচ্ছে আমরা ACTION_POWER_CONNECTED এই ইভেন্টটি রেজিস্টার করতে চাচ্ছি।</p><p>এবার আমাদের MyBroadCastReceiver ক্লাস এ ফিরে আসা যাক। Android studio একটি এরর দেখাচ্ছে, কারণ onReceive() মেথডটি ইমপ্লিমেন্ট করা হয়নি। Alt+enter প্রেস করে আমরা মেথডটি ইমপ্লিমেন্ট করে নিব।</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*8mHiNcBj1tbn1TYX9-OcTA.png" /><figcaption>MyBroadcastreceiver Class</figcaption></figure><p>যখনই অ্যান্ড্রয়েড সিস্টেম “ACTION_POWER_CONNECTED” এই ইভেন্টটি সম্পর্কে আমাদের অ্যাপ কে অবহিত করবে, onReceive() মেথডটি এক্সিকিউট হবে। এই মেথডে আমরা স্পেসিফাই করব যে চার্জার কানেক্টেড হলে আমরা কি করতে চাই। টিউটোরিয়ালটিকে সংক্ষিপ্ত ও সহজ রাখতে এখানে আমরা শুধুমাত্র একটি টোস্ট দেখাব।</p><pre><strong>public class </strong>MyBroadcastreceiver <strong>extends </strong>BroadcastReceiver {<br><br>    @Override<br>    <strong>public void </strong>onReceive(Context context, Intent intent) {<br><br>        Toast.<em>makeText</em>(context, <strong>&quot;Charger Connected&quot;</strong>,      Toast.<strong><em>LENGTH_SHORT</em></strong>).show();<br><br>    }<br><br>}</pre><p>এবার প্রোজেক্টটি রান করি। আমরা অ্যাপ এর ভিতরে বা বাইরে যেখানেই থাকি না কেন, চার্জার কানেক্ট করার সাথে সাথে আমরা একটি টোস্ট দেখতে পাব, কারণ চার্জার কানেক্টেড হওয়ার সাথে সাথে Mybroadcastreceiver ক্লাসের onReceive() মেথডটি এক্সিকিউট হয় এবং Toast টি প্রদর্শিত হয়।</p><p>ব্যাস ব্রডকাস্ট রিসিভার শেখা হয়ে গেল।</p><p><a href="https://github.com/AliAkberAakash/SampleBroadcastReceiver">সম্পূর্ণ প্রোজেক্টটি পাওয়া যাবে এইখানে।</a></p><p>এ টিউটোরিয়ালটিতে আমি শুধুমাত্র ব্রডকাস্ট রিসিভার এর সাথে পরিচিত করলাম। যতটুকু সহজ এবং সিম্পল রাখা যায় আমি চেষ্টা করেছ। কোনোরকম ভুল ত্রুটি চোখে পরলে অবশ্যই আমাকে অবগত করবেন, আমি সংশোধন করার চেষ্টা করব। আশা করি পরবর্তীতে এ টপিকে আরও বিস্তারিত লিখব। টিউটোরিয়ালটি পড়ার জন্যে সকলকে ধন্যবাদ।</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bd3e2590f5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ডায়াক্সট্রা’র এলগরিদম!!]]></title>
            <link>https://medium.com/@ali852609/%E0%A6%A1%E0%A6%BE%E0%A7%9F%E0%A6%BE%E0%A6%95%E0%A7%8D%E0%A6%B8%E0%A6%9F%E0%A7%8D%E0%A6%B0%E0%A6%BE%E0%A6%B0-%E0%A6%8F%E0%A6%B2%E0%A6%97%E0%A6%B0%E0%A6%BF%E0%A6%A6%E0%A6%AE-2d9df781a635?source=rss-5882a491e8e5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d9df781a635</guid>
            <category><![CDATA[pathfinder]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[bangla]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[dijkstra]]></category>
            <dc:creator><![CDATA[Ali Akber]]></dc:creator>
            <pubDate>Wed, 28 Mar 2018 13:35:46 GMT</pubDate>
            <atom:updated>2018-03-28T13:36:46.068Z</atom:updated>
            <content:encoded><![CDATA[<p>(প্রায়োরিটি কিউ ব্যাবহার ছাড়া)</p><p>পূর্বশর্ত : ফাংশন, টু ডাইমেনশনাল অ্যারে এর মাধ্যমে গ্রাফ রিপ্রেজেন্টেশন।</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*XjlFhOB-wXntpVOBmwe0ug.png" /></figure><p>ডোরেমন ও তার বন্ধুদেরকে আমরা সবাই কম বেশী চিনি। ডোরেমন তার দুই বন্ধু নোবিতা ও সিজুকার কাছে যাবে। ডোরেমন যেখানে আছে সেখান থেকে নোবিতার বাসায় যেতে লাগে ১০ মিনিট আর সিজুকার বাসায় যেতে লাগে ২০ মিনিট। আবার, নোবিতার বাসা থেকে সিজুকার বাসায় যেতে ৫ মিনিট লাগে। এখন, ডোরেমন যদি আগে নোবিতার বাসায় যায় এবং সেখান থেকে সিজুকার বাসায় যায়, তাহলে সিজুকার বাসায় যেতে তার ১০+৫ = ১৫ মিনিট সময় লাগবে। যা আগের তুলনায় কম। এটিই হচ্ছে সিজুকার বাসায় যাওয়ার শর্টেস্ট (shortest) পথ।</p><p>ডোরেমনের বাসা থেকে তার বন্ধুদের বাসায় যাওয়ার পথটিকে আমরা নিচের গ্রাফটির সাথে তুলনা করতে পারি। তাহলে a নোড থেকে b ও c নোড এ যাওয়ার শর্টেস্ট পাথ কস্ট(cost) হচ্ছে যথাক্রমে 10 ও 15 ।</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*gQs8x9EDiY6Z937IaVCXZg.png" /></figure><p>একটি নোড থেকে অন্য নোড এ যাওয়ার সময়, যদি এমন কোন নোড পাওয়া যায় যেটি দিয়ে গেলে আরও কম খরচে যাওয়া যাবে, তাহলে আমরা ওই পথটিই বেছে নিবো। আর এ প্রক্রিয়াটিই হল ডায়াক্সট্রা’র এলগরিদম। এটি একটি সিঙ্গেল সোর্স শর্টেস্ট পাথ এলগরিদম। কোন গ্রাফ এর একটি নির্দিষ্ট নোড থেকে বাকি সকল নোডে সবচেয়ে কম কস্ট এ যাওয়ার জন্য যে সকল এলগরিদম রয়েছে তাদেরকে সিঙ্গেল সোর্স শর্টেস্ট পাথ এলগরিদম বলা হয়।</p><p>ডায়াক্সট্রা’র এলগরিদম সাধারণত প্রায়োরিটি কিউ ব্যাবহার করে ইমপ্লিমেন্ট (Implement) করা হয়। কিন্তু আমরা এখানে প্রায়োরিটি কিউ ব্যাবহার ছাড়াই এলগরিদমটি ইমপ্লিমেন্ট করব।</p><p>তো এবার কোড শুরু করা যাক।</p><pre>int adj[100][100];<br>int dist[100];<br>bool visited[100];</pre><p>আমরা একটি টু ডাইমেনশনাল অ্যারে নিব adj[][] নামের এবং এর মধ্যে প্রত্যেকটা নোড থেকে অন্য নোড এ যাওয়ার কস্ট রাখব। অর্থাৎ adj[a][b] হবে a নোড থেকে b নোড এ যাওয়ার কস্ট। আমরা একটি অ্যারে নিব dist[] নামের, যা আমাদের সোর্স থেকে বাকি সকল নোড এর দূরত্ব সেভ(save) করে রাখবে। কোনো নোড ভিজিট (visit) করা হয়েছে কিনা তার ট্র্যাক (track) রাখতে আমরা বুলিয়ান টাইপের visited[] অ্যারেটি ব্যাবহার করব।</p><pre>void dijkstra(int source, int vertices)<br>{<br>    for(int i=0; i&lt;vertices; i++)<br>    {<br>        dist[i]=INT_MAX;<br>        visited[i]=false;<br>    } <br>    dist[source]=0;</pre><p>আমাদের ডায়াক্সট্রা ফাংশনটি আর্গুমেন্ট হিসেবে সোর্স নোড এবং মোট নোডের সংখ্যা নিবে, এদেরকে আমরা যথাক্রমে source এবং vertices দ্বারা প্রকাশ করব। শুরুতেই আমরা dist[] অ্যারের সকল এলিমেন্ট(element) INT_MAX দ্বারা পূর্ণ করব। এখানে INT_MAX অনেক বড় একটি ভ্যালু প্রকাশ করে যা সাধারণত নোড গুলোর কস্ট থেকে অনেক বড় হয়। visited[] অ্যারের সকল এলিমেন্ট false দ্বারা পূর্ণ করব। এবার আমরা সোর্স এর ডিস্টেন্স (distance) 0 করে দিব, কেননা কোনো নোড থেকে ওই নোডেই যেতে কোনো কস্ট লাগে না।</p><pre>int u=minDist(vertices); <br>visited[u]=true;</pre><p>এবার আমরা minDist() ফাংশন এর সাহায্যে dist[] অ্যারের সবচেয়ে কম কস্ট এর নোডটি বের করব এবং তা u তে রাখবো। এ ফাংশনটি সবগুলো vertices থেকে যারা এখনো ভিজিটেড না , তাদের মধ্যে সবচেয়ে কম খরচের নোডটির ইনডেক্স রিটার্ন (return) করে। visited[u] কে আমরা true করে দিবো, কারণ আমরা এখন এই নোডটি ভিজিট করেছি।</p><pre>int minDist(int vertices)<br>{    <br>    int mini=INT_MAX, minNode;     <br>    for(int i=0; i&lt;vertices; i++)    <br>    {        <br>        if(!visited[i] &amp;&amp; dist[i]&lt;mini)        <br>        {            <br>            mini=dist[i];            <br>            minNode=i;        <br>        }     <br>    }     <br>    return minNode;<br>}</pre><p>একটি ফর লুপ এর সাহায্যে আমরা u এর সকল অ্যাডজেসেন্ট নোড চেক করব এবং খুঁজবো এদের মধ্যে কারা এখনো ভিজিটেড (visited) নয়। adj[u][v] &amp;&amp; (!visited[v]) এ কন্ডিশন দুটির মাধ্যমে আমরা তা করতে পারছি। এ নোড গুলোকে আমরা v ধরি। এখানে dist[v] হচ্ছে সোর্স থেকে v নোড এ আসার কস্ট এবং dist[u]+adj[u][v] হচ্ছে সোর্স থেকে u নোড হয়ে v নোড এ আসার কস্ট। এখন যদি dist[v] এর মান , dist[u]+adj[u][v] এর থেকে বড় হয়, তাহলে আমরা dist[v] তে যাওয়ার আরও কম খরচের পথ পেয়ে গেছি। অতএব আমরা dist[v] এর মান dist[u]+adj[u][v] এর মান দ্বারা আপডেট (update) করে দিব ( dist[v]=dist[u]+adj[u][v]; )।</p><pre>for(int v=0; v&lt;vertices; v++)<br>        {<br>            if(adj[u][v] &amp;&amp; (!visited[v]) &amp;&amp; dist[u]!=INT_MAX &amp;&amp; dist[v]&gt;dist[u]+adj[u][v])<br>                dist[v]=dist[u]+adj[u][v];<br>        }</pre><p>এ প্রক্রিয়াটি আমরা vertices-2 বার পুনরাবৃত্তি করব। কেন vertices-2 বার? প্রকৃতপক্ষে কোডটির ইটারেশন হাতে কলমে করলে দেখা যায় যে এই প্রক্রিয়াটি vertices-2 বার পুনরাবৃত্তি করলে সকল নোড ভিজিটেড হয়ে যায়। তাই আমাদের এর থেকে বেশী বার পুনরাবৃত্তি করার প্রয়োজন হয় না।</p><p><a href="https://gist.github.com/AliAkberAakash/1383f5109a921c18d3fd343f4bc97d2f">সম্পূর্ণ কোডটি হবে এইরকম।</a></p><p>vertices-2 বার ইটারেশন (Iteration) শেষ হলে আমাদের dist[] অ্যারে তে সকল নোড এ যাওয়ার শর্টেস্ট কস্ট সেভ হয়ে থাকবে। আমরা print() ফাংশনটির সাহায্যে এটি প্রিন্ট করে নিবো।</p><pre>void printShortestPath(int vertices)<br>{<br>    for(int i=0; i&lt;vertices; i++)<br>    {<br>        printf(&quot;Shortest cost to %d is %d\n&quot;, i, dist[i]);<br>    }<br>    puts(&quot;&quot;);<br>}</pre><p>আশা করি বুঝা গেছে ডায়াক্সট্রা’র এলগরিদম কিভাবে কাজ করছে। আর্টিকেলটিতে কোনো ভুল থাকলে বা কারো কোনো সাজেশন থাকলে অবশই জানাবেন,। অন্য কোনো টপিক নিয়ে আমার লেখা দেখতে চাইলে কমেন্ট এ জানাবেন, আমি সেই টপিক নিয়ে লেখার চেষ্টা করবো। সম্পূর্ণ পোস্টটি পরার জন্য সকলকে ধন্যবাদ।</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d9df781a635" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>