<?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 Nkpozi Marcel Kelechi on Medium]]></title>
        <description><![CDATA[Stories by Nkpozi Marcel Kelechi on Medium]]></description>
        <link>https://medium.com/@captured_heart?source=rss-7fa89a520e0e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GvcQvXj-U2W0X-i0fUvR_A.png</url>
            <title>Stories by Nkpozi Marcel Kelechi on Medium</title>
            <link>https://medium.com/@captured_heart?source=rss-7fa89a520e0e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 11:17:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@captured_heart/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[Integrating FHIR with Flutter + Globe — Part 2 (Finale):]]></title>
            <link>https://medium.com/@captured_heart/integrating-fhir-with-flutter-globe-part-2-finale-861f4c049113?source=rss-7fa89a520e0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/861f4c049113</guid>
            <category><![CDATA[hapi]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[invertase]]></category>
            <category><![CDATA[firefly]]></category>
            <category><![CDATA[fhir]]></category>
            <dc:creator><![CDATA[Nkpozi Marcel Kelechi]]></dc:creator>
            <pubDate>Tue, 17 Mar 2026 10:40:42 GMT</pubDate>
            <atom:updated>2026-03-17T10:40:42.041Z</atom:updated>
            <content:encoded><![CDATA[<h3>Integrating FHIR with Flutter + Globe — Part 2 (Finale):</h3><p>A FHIR Integration continuation Guide in Flutter Using HAPI, Kodjin, and Firefly — with Flutter Web Deployment via Globe</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_G_rvIhrqGoX2oidzL4HSQ.png" /><figcaption>The image was generated using Gemini</figcaption></figure><h3>1. Recap from Part 1</h3><h3>What We Covered</h3><p>In <a href="https://medium.com/@captured_heart/integrating-fhir-with-flutter-part-1-ff63ab3f7df3">Part 1</a>, we established the foundation:</p><p><strong>FHIR Fundamentals:</strong></p><ul><li>Fast Healthcare Interoperability Resources (FHIR) standard</li><li>RESTful API for healthcare data</li><li>Resource-based architecture (Patient, Observation, MedicationRequest, etc.)</li><li>Solving healthcare interoperability problems</li></ul><p><strong>Project Overview:</strong></p><ul><li>Complete healthcare management app</li><li>6 medical forms: Patient, Diagnosis, Prescriptions, Observations, Appointments, Lab Results</li><li>Multi-server support (HAPI, Kodjin, Firefly, Custom)</li></ul><p><strong>Domain Models:</strong></p><ul><li>Entity structure and design patterns</li><li>App entities → FHIR resource conversion</li></ul><p><strong>Tech Stack:</strong></p><ul><li>fhir_r4 for FHIR integration</li><li>Riverpod for state management</li><li>Dio for networking</li><li>Hive for local storage</li></ul><h3>What Part 2 Covers</h3><p>Now we’ll implement everything with <strong>complete, working code</strong>:</p><ul><li>Full project setup</li><li>FHIR Form UI and validation</li><li>Network layer configuration</li><li>Repository implementation</li><li>State Management with Riverpod</li><li>API integration</li><li>Bonus (Flutter Web deployment via Globe)</li></ul><h3>2. Project Setup &amp; Configuration</h3><h3>Initial Setup</h3><h4>To create a Flutter project, copy the command below into the terminal.</h4><pre>flutter create fhir_demo<br>cd fhir_demo</pre><h4>Add Dependencies</h4><p>Update pubspec.yaml: I will be showing only the important dependencies for this project; you can view the full list in the project repository on <a href="https://github.com/Captured-Heart/fhir_demo/blob/main/pubspec.yaml">GitHub</a>. After adding the necessary dependencies, always remember to run flutter pub get to install them.</p><pre>name: fhir_demo<br>description: &quot;FHIR-compliant healthcare management app&quot;<br><br>environment:<br>  sdk: ^3.7.0<br>dependencies:<br>  # FHIR Integration<br>  fhir_r4: ^0.4.3<br>  # State Management<br>  flutter_riverpod: ^2.6.1<br>  # Networking<br>  dio: ^5.9.0<br>  dio_smart_retry: ^7.0.1<br>...<br>  flutter:<br>    sdk: flutter<br>dev_dependencies:<br>  flutter_lints: ^5.0.0<br>  flutter_test:<br>    sdk: flutter<br></pre><h3>Constants Setup</h3><h4>API Constants</h4><p>lib/constants/api_constants.dartI prefer to manage all constants when making network calls from a class. This includes the request duration, headers, and other parameters.</p><p>As seen below, the headers for FHIR servers use a unique content type of <em>“application/fhir+json”</em>. And this projectIdentifier is used to mark all our FHIR resources, allowing us to identify them when fetching from public servers. (It&#39;s not ideal, as every request to servers is supposed to be authenticated and fetched with a unique token. This is my little innovation 😅). I will show the implementation later in this post.</p><pre>import &#39;package:flutter/foundation.dart&#39;;<br><br>class ApiConstants {<br>  // Environment<br>  static const bool isDevelopment = kDebugMode;<br>  static const bool isProduction = false;<br>  // Request Configuration<br>  static const Duration connectTimeout = Duration(seconds: 10);<br>  static const Duration receiveTimeout = Duration(seconds: 15);<br>  static const Duration sendTimeout = Duration(seconds: 10);<br>  // Retry Configuration<br>  static const int maxRetries = 3;<br>  static const List&lt;Duration&gt; retryDelays = [<br>    Duration(seconds: 1),<br>    Duration(seconds: 3),<br>    Duration(seconds: 5),<br>  ];<br>  // Headers<br>  static const Map&lt;String, String&gt; defaultHeaders = {<br>    &#39;Content-Type&#39;: &#39;application/fhir+json&#39;,<br>    &#39;Accept&#39;: &#39;application/fhir+json&#39;,<br>  };<br>  // Project Identifier for filtering resources<br>  static const String projectIdentifier = &#39;fhirdemoproject&#39;;<br>  static const String projectIdentifierLabResult = &#39;fhirdemoprojectlabresult&#39;;<br>}</pre><p><strong>Key Points:</strong></p><ul><li>Centralized configuration</li><li>Type-safe constants</li></ul><h4>FHIR Server Types</h4><p>lib/constants/fhir_server_type_enum.dart: I love enums 😍😜, and in this project, I am using enums to classify the public servers.</p><pre>enum FhirServerType {<br>  hapi(&#39;https://hapi.fhir.org/baseR4&#39;),<br>  kodjin(&#39;https://demo.kodjin.com/fhir&#39;),<br>  firefly(&#39;https://server.fire.ly&#39;),<br>  custom(&#39;&#39;);<br><br>final String baseUrl;<br>  const FhirServerType(this.baseUrl);<br>}</pre><p><strong>Usage: In the code block below, I show the usage of the FhirServer Enum in a dropdown Flutter widget (AppBarServerSwitch).</strong></p><p>settingsState : This is a value/state from watching changes in theFhirSettingsProvider, a Riverpod notifier class that will be explained later in the post.</p><pre>class AppBarServerSwitch extends ConsumerWidget {<br>@override<br>Widget build(BuildContext context, WidgetRef ref) {<br>final serverValues =  FhirServerType.values;<br>final settingState = ref.watch(fhirSettingsProvider);<br>final settingsCtrl = ref.read(fhirSettingsProvider.notifier);<br>DropdownButtonHideUnderline(<br>        child: DropdownButton&lt;FhirServerType&gt;(<br>          value: serverValues.firstWhere((type) =&gt; type.name.toLowerCase() == settingState.serverType.toLowerCase(),<br>            orElse: () =&gt; FhirServerType.values.first),<br>          isDense: true,<br>          isExpanded: false,<br>          items: serverValues.where((type) =&gt; type.baseUrl.isNotEmpty).map((type) {<br>                return DropdownMenuItem(<br>                  value: type,<br>                  child: MoodText.text(<br>                    text: type.name.toUpperCase(),<br>                    context: context,<br>                    textStyle: context.textTheme.bodyMedium,<br>                  ),<br>                );<br>              }).toList(),<br>          onChanged: (value) {<br>            if (value == FhirServerType.custom) return;<br>            if (value != null) {<br>                 settingsCtrl.updateServerType(value).then((value) {<br>                if (value) {<br>                  onServerChanged?.call();<br>                }<br>              });<br>            }<br>          },<br>        ),<br>      );<br>}<br>}</pre><h4>API URLs</h4><p>lib/constants/api_url.dart: FHIR servers maintain the same structure for the URLs. For example, considering any of the base URLs, let&#39;s say HAPI (https://hapi.fhir.org/baseR4). The complete URL for patients would look like this: <a href="https://hapi.fhir.org/baseR4/">https://hapi.fhir.org/baseR4/Patient/</a> and vice versa.</p><pre>enum ApiUrl {<br>  fhirPatient(&#39;/Patient&#39;),<br>  fhirCondition(&#39;/Condition&#39;),<br>  fhirMedicationRequest(&#39;/MedicationRequest&#39;),<br>  fhirObservation(&#39;/Observation&#39;),<br>  fhirAppointment(&#39;/Appointment&#39;),<br>  fhirDiagnosticReport(&#39;/DiagnosticReport&#39;);<br><br>final String url;<br>  const ApiUrl(this.url);<br>}</pre><h3>Full Project Architecture</h3><p>The wonderful fact about the structure tree below was that it was generated by AI. That’s magical, yeah? 😁</p><pre>lib/<br>├── main.dart<br>├── constants/<br>│   ├── api_constants.dart<br>│   ├── api_url.dart<br>│   ├── app_colors.dart<br>│   ├── fhir_server_type_enum.dart<br>│   └── nav_routes.dart<br>├── hive_helper/<br>│   ├── cache_helper.dart<br>│   └── hive_adapters.dart<br>├── src/<br>│   ├── controller/<br>│   │   ├── patient_controller.dart<br>│   │   ├── prescriptions_controller.dart<br>│   │   └── ...<br>│   ├── domain/<br>│   │   ├── entities/<br>│   │   ├── models/<br>│   │   └── repository/<br>│   └── presentation/<br>│       ├── views/<br>│       └── widgets/<br>└── utils/</pre><h3>3. FHIR Forms UI &amp; Validations</h3><p>The forms in this project were built using simple Flutter inputs, such as TextFormField and DropdownButtonFormField. The more important aspect, however, was the validation layer. Particular attention was given to enforcing correct data types and input constraints to ensure that the payload sent to the FHIR server remained clean and compliant with the expected schema. To achieve this, I implemented a centralised validation utility that standardises input checks across the application. The Validation class below demonstrates how these rules were structured and reused throughout the form layer.</p><pre>final RegExp emailRegex = RegExp(<br>  r&#39;^(([^&lt;&gt;()[\]\\.,;:\s@\&quot;]+(\.[^&lt;&gt;()[\]\\.,;:\s@\&quot;]+)*)|(\&quot;.+\&quot;))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$&#39;,<br>);<br><br>final RegExp passwordRegex = RegExp(r&#39;^(?=.*[A-Z])(?=.*[!@#\$&amp;*~]).+$&#39;);<br>class AppValidations {<br>  const AppValidations._();<br>  static String? validatedName(String? value, {String label = &quot;Name&quot;}) {<br>    String? result;<br>    if (value != null &amp;&amp; value.trim().isEmpty) {<br>      result = &quot;$label can&#39;t be empty&quot;;<br>    } else {<br>      result = null;<br>    }<br>    return result;<br>  }<br>  // Validate phone number<br>  static String? validatePhone(String? value) {<br>    if (value == null || value.isEmpty) {<br>      return &#39;Please enter phone number&#39;;<br>    }<br>    //check if there is a character not a number<br>    final numericRegex = RegExp(r&#39;^[0-9]+$&#39;);<br>    if (!numericRegex.hasMatch(value)) {<br>      return &#39;Phone number must contain only digits&#39;;<br>    }<br>    return null;<br>  }<br>  //120/80<br>  static String? validateBloodPressure(String? value) {<br>    if (value == null || value.isEmpty) {<br>      return null; // Blood Pressure is optional<br>    }<br>    final bpRegex = RegExp(r&#39;^\d{2,3}/\d{2,3}$&#39;);<br>    if (!bpRegex.hasMatch(value)) {<br>      return &#39;format must be (e.g., 120/80)&#39;;<br>    }<br>    return null;<br>  }<br>...<br>}</pre><p>As shown in the code block, regular expressions (regex) are used extensively to enforce input validation rules. These patterns help ensure that user inputs conform to the expected formats before any data is processed or sent to the FHIR server. An example of how these validations are applied within a form is demonstrated below in the validator method.</p><pre>// Phone<br>  Textfield(<br>   labelText: &#39;Phone Number *&#39;,<br>   hintText: &#39;Enter phone number&#39;,<br>   controller: patientCtrl.phoneController,<br>   keyboardType: TextInputType.phone,<br>   prefixIcon: const Icon(Icons.phone),<br>   validator: (value) =&gt; AppValidations.validatePhone(value),<br>),</pre><h3>4. Network Layer Implementation</h3><h3>Dio Setup</h3><p>lib/src/domain/repository/network/network_calls_repository.dart: I set up a lightweight wrapper around Dio to centralise the major HTTP operations required for the project—GET, POST, PUT, and DELETE. This wrapper acts as the single entry point for all network communication, allowing request configuration, error handling, and response parsing to remain consistent across the application.</p><h4>Base Configuration</h4><pre>class NetworkCallsRepository {<br>  late Dio _dio;<br><br>Future&lt;void&gt; initialize(String baseUrl) async {<br>    _dio = Dio(<br>      BaseOptions(<br>        baseUrl: baseUrl,<br>        connectTimeout: ApiConstants.connectTimeout,<br>        receiveTimeout: ApiConstants.receiveTimeout,<br>        sendTimeout: ApiConstants.sendTimeout,<br>        headers: ApiConstants.defaultHeaders,<br>        validateStatus: (status) {<br>          // Accept all status codes so we can handle them<br>          return status != null &amp;&amp; status &lt; 500;<br>        },<br>      ),<br>    );<br>    _setupInterceptors();<br>  }<br>}</pre><h4>Interceptors</h4><ul><li>Logging interceptor for debugging</li><li>Authentication interceptor for tokens</li><li>Error-handling interceptor</li></ul><h3>Smart Retry Mechanism</h3><pre>_dio.interceptors.add(<br>  RetryInterceptor(<br>    dio: _dio,<br>    retries: ApiConstants.maxRetries,<br>    retryDelays: ApiConstants.retryDelays,<br>  ),<br>);</pre><p><strong>Benefits:</strong></p><ul><li>Handles temporary network failures</li><li>Exponential backoff prevents server overload</li></ul><p>The Dio wrapper is exposed through a Riverpod provider, enabling dependency injection throughout the app. This approach keeps the networking client loosely coupled from repositories and other layers, making it easier to test, mock, or swap implementations when necessary.</p><pre>import &#39;package:dio/dio.dart&#39;;<br>import &#39;package:dio_smart_retry/dio_smart_retry.dart&#39;;<br>import &#39;package:flutter_riverpod/flutter_riverpod.dart&#39;;<br>import &#39;package:fhir_demo/constants/api_constants.dart&#39;;<br>import &#39;package:fhir_demo/src/controller/fhir_settings_controller.dart&#39;;<br>import &#39;package:fhir_demo/src/domain/entities/api_response.dart&#39;;<br><br>final networkCallsRepositoryProvider = Provider&lt;NetworkCallsRepository&gt;((ref) {<br>  final settings = ref.watch(fhirSettingsProvider);<br>  return NetworkCallsRepositoryImpl(settings.serverBaseUrl);<br>});<br>abstract class NetworkCallsRepository {<br>  Future&lt;ApiResponse&gt; get(String endpoint, {Map&lt;String, dynamic&gt;? queryParameters});<br>  Future&lt;ApiResponse&gt; post(String endpoint, {required Map&lt;String, dynamic&gt; data});<br>  Future&lt;ApiResponse&gt; put(String endpoint, {required Map&lt;String, dynamic&gt; data});<br>  Future&lt;ApiResponse&gt; delete(String endpoint);<br>}<br>class NetworkCallsRepositoryImpl implements NetworkCallsRepository {<br>  NetworkCallsRepositoryImpl(this.baseUrl) {<br>    _initializeDio();<br>  }<br>  void _initializeDio() {<br>   //Initialize Dio<br>   ...<br>    _setupInterceptors();<br>  }<br>  void _setupInterceptors() {<br>    // Logging Interceptor<br>    _dio.interceptors.add(<br>     ...<br>    );<br>    // Retry Interceptor<br>    _dio.interceptors.add(<br>    ...<br>    );<br>  }<br>  @override<br>  Future&lt;ApiResponse&gt; get(<br>    String endpoint, {<br>    Map&lt;String, dynamic&gt;? queryParameters,<br>  }) async {<br>    try {<br>      final response = await _dio.get(<br>        endpoint,<br>        queryParameters: queryParameters,<br>      );<br>      return _handleResponse(response);<br>    } on DioException catch (e) {<br>      return _handleError(e);<br>    } catch (e) {<br>      return ApiResponse.error(e.toString());<br>    }<br>  }<br>  @override<br>  Future&lt;ApiResponse&gt; post(<br>    String endpoint, {<br>    required Map&lt;String, dynamic&gt; data}) async {<br>   ...<br>  }<br>  @override<br>  Future&lt;ApiResponse&gt; put(<br>    String endpoint, {<br>    required Map&lt;String, dynamic&gt; data}) async {<br>    ...<br>  }<br>  @override<br>  Future&lt;ApiResponse&gt; delete(String endpoint) async {<br>    ...<br>  }<br>}</pre><h3>Error Handling in the Dio Wrapper</h3><h4>Response Normalisation (_handleResponse)</h4><ul><li>Treats 2xx as success and wraps data with ApiResponse.success</li><li>Converts non-2xx responses into ApiResponse.error with status code preserved</li></ul><pre>ApiResponse _handleResponse(Response response) {<br><br>    if (response.statusCode != null &amp;&amp;<br>        response.statusCode! &gt;= 200 &amp;&amp;<br>        response.statusCode! &lt; 300) {<br>      return ApiResponse.success(<br>        response.data,<br>        statusCode: response.statusCode,<br>      );<br>    } else {<br>      return ApiResponse.error(<br>        _getErrorMessage(response),<br>        statusCode: response.statusCode,<br>      );<br>    }<br>  }</pre><h4>Exception Mapping (_handleError)</h4><ul><li>Timeout errors (connectionTimeout, sendTimeout, receiveTimeout) map to ApiConstants.timeoutError</li><li>HTTP protocol errors (badResponse) reuse server payload parsing via _getErrorMessage</li><li>Network failures (connectionError) map to ApiConstants.networkError</li><li>Any unclassified case falls back to error.message or ApiConstants.unknownError</li></ul><pre>ApiResponse _handleError(DioException error) {<br>    log(&#39;[Dio Error] ${error.type}: ${error.message}&#39;);<br><br>switch (error.type) {<br>      case DioExceptionType.connectionTimeout:<br>      case DioExceptionType.sendTimeout:<br>      case DioExceptionType.receiveTimeout:<br>        return ApiResponse.error(<br>          ApiConstants.timeoutError,<br>          statusCode: error.response?.statusCode,<br>        );<br>      case DioExceptionType.badResponse:<br>        return ApiResponse.error(<br>          _getErrorMessage(error.response),<br>          statusCode: error.response?.statusCode,<br>        );<br>      case DioExceptionType.connectionError:<br>        return ApiResponse.error(<br>          ApiConstants.networkError,<br>          statusCode: error.response?.statusCode,<br>        );<br>      default:<br>        return ApiResponse.error(<br>          error.message ?? ApiConstants.unknownError,<br>          statusCode: error.response?.statusCode,<br>        );<br>    }<br>  }</pre><h4>FHIR-Aware Message Extraction (_getErrorMessage)</h4><ul><li>Checks for map payloads and safely parses known error shapes</li><li>Detects FHIR OperationOutcome and extracts issue[0].diagnostics</li><li>Falls back to common keys (error, message) before generic status text</li><li>Ensures the UI always receives a user-facing error string</li></ul><pre>String _getErrorMessage(Response? response) {<br>    if (response?.data is Map) {<br>      final data = response!.data as Map&lt;String, dynamic&gt;;<br><br>      // Try to parse FHIR OperationOutcome<br>      if (data[&#39;resourceType&#39;] == &#39;OperationOutcome&#39;) {<br>        final issues = data[&#39;issue&#39;] as List?;<br>        if (issues != null &amp;&amp; issues.isNotEmpty) {<br>          return issues[0][&#39;diagnostics&#39;] ?? ApiConstants.serverError;<br>        }<br>      }<br>      // Try other common error formats<br>      return data[&#39;error&#39;] ??<br>             data[&#39;message&#39;] ??<br>             &#39;Error ${response.statusCode}&#39;;<br>    }<br>    return &#39;Error ${response?.statusCode ?? &#39;Unknown&#39;}&#39;;<br>  }</pre><h4>Why This Pattern Works</h4><ul><li>Consistent ApiResponse contract across repositories and controllers</li><li>Compatible with mixed backends (FHIR-native and non-FHIR error formats)</li></ul><h3>5. Repository Pattern Implementation</h3><h3>Patient Repository</h3><p>lib/src/domain/repository/fhir_repositories/patient_repository.dart: The PatientRepository follows a clean repository pattern that separates domain logic from networking concerns. An abstract repository defines the contract for all patient-related operations, such as create, read, update, delete, and validation. The concrete PatientRepositoryImpl handles the implementation by delegating HTTP requests to a centralised NetworkCallsRepository.</p><p>Riverpod is used to expose the repository through dependency injection, ensuring easy access across the app while maintaining testability. Domain entities like ProjectPatientEntity are converted into FHIR Patient resources before being sent to the API (remember the modelling in part 1?). Responses from the server are parsed back into typed FHIR models and wrapped in a generic ApiResponse for consistent error and success handling.</p><pre>import &#39;package:fhir_demo/constants/api_constants.dart&#39;;<br>import &#39;package:fhir_demo/constants/api_url.dart&#39;;<br>import &#39;package:fhir_demo/src/domain/entities/api_response.dart&#39;;<br>import &#39;package:fhir_demo/src/domain/entities/project_patient_entity.dart&#39;;<br>import &#39;package:fhir_demo/src/domain/repository/network/network_calls_repository.dart&#39;;<br>import &#39;package:fhir_r4/fhir_r4.dart&#39;;<br>import &#39;package:flutter_riverpod/flutter_riverpod.dart&#39;;<br><br>final patientRepositoryProvider = Provider&lt;PatientRepository&gt;((ref) {<br>  final networkRepository = ref.watch(networkCallsRepositoryProvider);<br>  return PatientRepositoryImpl(networkRepository);<br>});<br>abstract class PatientRepository {<br>  Future&lt;ApiResponse&gt; createPatient(ProjectPatientEntity patientData);<br>  Future&lt;Map&lt;String, dynamic&gt;?&gt; getPatientById(String patientId);<br>  Future&lt;ApiResponse&lt;List&lt;Patient&gt;&gt;&gt; getAllPatientsByIdentifier();<br>  Future&lt;ApiResponse&gt; editPatientById({<br>    required ProjectPatientEntity patientData,<br>    required Patient existingPatient,<br>  });<br>  Future&lt;bool&gt; deletePatientById(String patientId);<br>  Future&lt;bool&gt; validatePatientExists(String patientId);<br>}<br>class PatientRepositoryImpl implements PatientRepository {<br>  final NetworkCallsRepository networkRepository;<br>  PatientRepositoryImpl(this.networkRepository);<br>  @override<br>  Future&lt;ApiResponse&gt; createPatient(ProjectPatientEntity patientData) async {<br>    try {<br>final response = await networkRepository.post(ApiUrl.fhirPatient.url,<br>        data: patientData.addPatient());<br>   if (response.isSuccess) {<br>final data = Patient.fromJson(response.data as Map&lt;String, dynamic&gt;);<br>      return ApiResponse.success(data);<br>  } else {<br> return ApiResponse.error(&#39;Failed to create patient: ${response.statusCode} ${response.error}&#39;,statusCode: response.statusCode);<br>      }<br>    } catch (e) {<br>      return ApiResponse.error(e.toString());<br>    }<br>  }<br>  @override<br>  Future&lt;Map&lt;String, dynamic&gt;?&gt; getPatientById(String patientId) async {<br>    try {<br>    ...<br>    } catch (e) {<br>      return null;<br>    }<br>  }<br>  @override<br>  Future&lt;ApiResponse&lt;List&lt;Patient&gt;&gt;&gt; getAllPatientsByIdentifier() async {<br>    try {<br>      ...<br>    } catch (e) {<br>      return ApiResponse.error(e.toString());<br>    }<br>  }<br>  @override<br>  Future&lt;ApiResponse&gt; editPatientById({<br>    required ProjectPatientEntity patientData,<br>    required Patient existingPatient,<br>  }) async {<br>    try {<br>    ...<br>    } catch (e) {<br>      return ApiResponse.error(e.toString());<br>    }<br>  }<br>  @override<br>  Future&lt;bool&gt; deletePatientById(String patientId) async {<br>    try {<br>    ...<br>    } catch (e) {<br>      return false;<br>    }<br>  }<br>  @override<br>  Future&lt;bool&gt; validatePatientExists(String patientId) async {<br>    try {<br>     ...<br>    } catch (e) {<br>      log(&#39;[Patient Repository] Validation error: $e&#39;);<br>      return false;<br>    }<br>  }<br>}</pre><p><strong>Repository Pattern Benefits:</strong></p><p>This approach keeps the UI layer independent of network logic and FHIR serialisation details. The same architectural pattern is consistently applied across other repositories in the project, ensuring predictable data flow and maintainable code.</p><h3>6. State Management with Riverpod</h3><h3>FHIR Settings Controller</h3><p>lib/src/controller/fhir_settings_controller.dart: I’m using a Riverpod Notifier to manage the state for this feature, taking advantage of the .autoDispose modifier to ensure the state is automatically cleaned up when it is no longer in use. This helps prevent unnecessary memory retention and keeps the state lifecycle aligned with the UI. The _serverUrlController is connected to the custom <strong>base URL</strong> TextField in the settings view, allowing users to configure the FHIR server endpoint used by the application dynamically.</p><pre>import&#39;dart:convert&#39;;<br>import &#39;package:fhir_demo/constants/fhir_server_type_enum.dart&#39;;<br>import &#39;package:flutter/widgets.dart&#39;;<br>import &#39;package:flutter_riverpod/flutter_riverpod.dart&#39;;<br>import &#39;package:fhir_demo/hive_helper/cache_helper.dart&#39;;<br>import &#39;package:fhir_demo/src/domain/entities/fhir_settings_entity.dart&#39;;<br><br>final fhirSettingsProvider = NotifierProvider.autoDispose&lt;FhirSettingsNotifier,FhirSettingsEntity<br>&gt;(FhirSettingsNotifier.new);<br>class FhirSettingsNotifier extends AutoDisposeNotifier&lt;FhirSettingsEntity&gt; {<br>  late TextEditingController _serverUrlController;<br>  late TextEditingController _apiKeyController;<br>  @override<br>  FhirSettingsEntity build() {<br>    _serverUrlController = TextEditingController();<br>    _apiKeyController = TextEditingController();<br>    _loadSettings();<br>    return state;<br>  }<br>  TextEditingController get serverUrlController =&gt; _serverUrlController;<br>  TextEditingController get apiKeyController =&gt; _apiKeyController;<br>  Future&lt;void&gt; _loadSettings() async {<br>...<br>  }<br>  Future&lt;bool&gt; updateServerType(FhirServerType serverType) async {<br>   ...<br>  }<br>  Future&lt;void&gt; _saveSettings() async {<br> ...<br>  }<br>}</pre><ul><li>_loadSettings method: A method that runs in the build method of the class is responsible for recovering saved settings from local storage (HiveFlutter). Such settings include server baseUrl, apiKey, themes, etc.</li></ul><pre>Future&lt;void&gt; _loadSettings() async {<br>    try {<br>      final settingsBox = CacheHelper.themeLocalModel;<br>      final settingsJson = settingsBox.read(_settingsKey);<br><br>if (settingsJson != null &amp;&amp; settingsJson.isNotEmpty) {<br>        final Map&lt;String, dynamic&gt; decoded = jsonDecode(settingsJson);<br>        state = FhirSettingsEntity.fromJson(decoded);<br>        _serverUrlController.text = state.customServerBaseUrl ?? state.serverBaseUrl;<br>        _apiKeyController.text = state.apiKey;<br>      } else {<br>        _backToDefaultSettings();<br>      }<br>    } catch (e) {<br>      // If loading fails, keep default settings<br>      print(&#39;Error loading FHIR settings: $e&#39;);<br>      _backToDefaultSettings();<br>    }<br>  }<br> _backToDefaultSettings() {<br>    state = FhirSettingsEntity(serverBaseUrl: FhirServerType.hapi.baseUrl);<br>    _apiKeyController.clear();<br>    _serverUrlController.text = state.customServerBaseUrl ?? &#39;&#39;;<br>  }</pre><ul><li>_saveSettings: Just like the method above, it makes use of HiveFlutter to save settings to local storage.</li></ul><pre>Future&lt;void&gt; _saveSettings() async {<br>    try {<br>      final settingsBox = CacheHelper.themeLocalModel;<br>      final settingsJson = jsonEncode(state.toJson());<br>      await settingsBox.write(_settingsKey, settingsJson);<br>      print(&#39;[FHIR Settings] Saved successfully&#39;);<br>    } catch (e) {<br>      print(&#39;Error saving FHIR settings: $e&#39;);<br>    }<br>  }</pre><ul><li>updateServerType : This method is called in the AppBarServerSwitch widget onChanged method described at the top of the post. It is responsible for updating the server type.</li></ul><pre>Future&lt;bool&gt; updateServerType(FhirServerType serverType) async {<br>    try {<br>  <br>      _serverUrlController.text = serverType.baseUrl;<br>      state = state.copyWith(<br>        serverType: serverType.name,<br>        serverBaseUrl: serverType.baseUrl,<br>      );<br>      await _saveSettings();<br> <br>      return true;<br>    } catch (e) {<br>      print(&#39;[FHIR Settings] Error: $e&#39;);<br>      return false;<br>    }<br>  }</pre><p>There are additional Notifiers implemented for patients, observations, and other FHIR-related forms in the application. While I won’t cover each of them in this post, they are all available in the project’s GitHub repository. Each follows the same architectural pattern demonstrated in FhirSettingsNotifier, using a combination of Notifier + NotifierProvider + NotifierState to keep state management consistent, predictable, and easy to maintain across the codebase.</p><h3>7. API Integration</h3><h3>End-to-End Request Flow</h3><p>This project uses a clear flow for all FHIR requests:</p><ol><li><strong>UI Form</strong> captures validated input</li><li><strong>Controller</strong> triggers the submit/edit method</li><li><strong>Repository</strong> converts the entity to FHIR JSON and selects the endpoint</li><li><strong>Network layer</strong> handles auth, retries, logging, and error translation</li><li><strong>Repository</strong> parses typed FHIR responses (Patient, Observation, etc.)</li></ol><h3>Repository + Endpoint Integration</h3><p>lib/src/domain/repository/fhir_repositories/patient_repository.dart:</p><pre>final response = await networkCallsRepository.post(<br>  ApiUrl.fhirPatient.url,<br>  data: patientData.addPatient(),<br>);<br><br>if (response.isSuccess) {<br>  final data = Patient.fromJson(response.data as Map&lt;String, dynamic&gt;);<br>  return ApiResponse.success(data);<br>}</pre><h3>8. Bonus (Flutter Web deployment via Globe)</h3><p>For deployment, I hosted the Flutter Web build using <strong>Globe</strong>, a platform developed by <strong>Invertase</strong> that is optimised for hosting Flutter web applications. After generating the production build with flutter build web, the static files were deployed directly to Globe.</p><p><strong>To use Globe:</strong></p><p>The first step is to install the plugin using Dart Pub, which makes the package available to the Flutter project and enables its use within the application code.</p><pre>$ dart pub global activate globe_cli</pre><p>Next, log in to Globe using the CLI. This step assumes that you already have an existing Globe account configured for deployment.</p><pre>$ globe login</pre><p>Finally, deploy the previously generated Flutter Web build to Globe, making the application available for public access.</p><pre>$ globe deploy</pre><p>Once the deployment completes, Globe returns a generated URL for the application. This link can then be opened in any browser to preview and access the deployed Flutter Web app.</p><h3>Resources</h3><p>See the complete resources in <a href="https://medium.com/@captured_heart/integrating-fhir-with-flutter-part-1-ff63ab3f7df3">Part 1</a> of this article.</p><h3>Project Links</h3><ul><li><a href="https://github.com/Captured-Heart/fhir_demo">GitHub Repository</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=861f4c049113" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating FHIR with Flutter — Part 1]]></title>
            <link>https://medium.com/@captured_heart/integrating-fhir-with-flutter-part-1-ff63ab3f7df3?source=rss-7fa89a520e0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff63ab3f7df3</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[fhir-integration]]></category>
            <category><![CDATA[fhir]]></category>
            <category><![CDATA[hapi]]></category>
            <category><![CDATA[healthcare]]></category>
            <dc:creator><![CDATA[Nkpozi Marcel Kelechi]]></dc:creator>
            <pubDate>Fri, 27 Feb 2026 13:54:38 GMT</pubDate>
            <atom:updated>2026-02-27T13:54:38.789Z</atom:updated>
            <content:encoded><![CDATA[<p>A Guide to FHIR Introduction and Setting Up Your Project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S3rfLp5khoiPBGzsQa5FlQ.png" /><figcaption>The image was generated using GPT-5.2</figcaption></figure><h3>1. Introduction</h3><p>In today’s healthcare sector, transfer and access of patient data remain frustratingly inconsistent across different systems, hospitals, and clinics. A patient who visits multiple healthcare providers often finds their medical history scattered across incompatible electronic health records (EHR) systems. Doctors can’t easily access critical information, leading to repeated tests, medication errors, and fragmented care. Also, software developers who wish to build on existing healthcare solutions find it extremely difficult when data is poorly structured, inconsistently labeled, or locked behind proprietary formats. Even when access is granted, the lack of a common data model makes integrating systems slow and expensive.</p><p>This is where <strong>FHIR (Fast Healthcare Interoperability Resources)</strong> comes in — a modern standard that promises to break down these data models and enable seamless healthcare information exchange.</p><h3>My Journey</h3><p>I’ve always been drawn to building mobile products that make a direct impact on human lives. In 2025, that drive led me to work with <strong>ArewaCare</strong>, a medical software company creating digital tools for pregnant women and the physicians who care for them. While working on healthcare workflows, we stumbled on a challenge that quietly underpins almost every medical system: <strong>Data fragmentation</strong>. “Data fragmentation is a term widely used in the field of data management and particularly in databases and file systems. It is a method of storing a single file or a single piece of data into multiple parts on the disk”. Patient records are often scattered across multiple locations, and systems struggle to communicate with one another, which also leads to degradation and increased security risks. I was introduced to the concept of interoperability of data as a solution, and for the first time, I heard the word “FHIR”. This led me to research and build a demo FHIR-compliant healthcare management application using Flutter — and in this two-part series, I’ll share everything I learned.</p><p><strong><em>P.S:</em></strong><em> The very first mobile application I built in 2020 was a healthcare solution — Beata Medrek (An Electronic healthcare record software with an emergency feature that helps one locate the nearest hospital). A solution that was inspired by my first-hand experience with Nigeria’s public hospitals while I was taking care of my then-sick mother. She passed gloriously in 2021 🕊️🕊️(I pray St. Cordelia Nkpozi&#39;s soul rest in peace. Amen); and my solution, although completed then, died as well in my GitHub account 😂😂</em></p><h3>What You’ll Learn in Part 1</h3><ul><li>Understanding FHIR and why it matters in healthcare</li><li>The problem FHIR solves in healthcare interoperability</li><li>Overview of a complete healthcare app built with Flutter, key features, and use cases</li><li>Domain models and entities structure</li><li>Libraries and tools for FHIR development</li><li>Foundation for Part 2’s implementation</li></ul><h3>What to Expect in Part 2</h3><ul><li>Complete implementation with code examples</li><li>Network layer and API integration</li><li>State management with Riverpod</li><li>Form handling and validation</li><li>Testing strategies</li><li>Deployment considerations</li></ul><h3>Target Audience</h3><ul><li>Flutter developers curious about healthcare apps</li><li>Healthcare IT professionals interested in mobile development</li><li>Developers learning about FHIR integration</li><li>Students exploring health tech</li></ul><h3>2. FHIR — Fast Healthcare Interoperability Resources</h3><p><strong>FHIR (Fast Healthcare Interoperability Resources)</strong> is a next-generation standards framework created by <strong>HL7 International</strong> for exchanging healthcare information electronically and consistently between systems. Think of it as the “REST API for healthcare data.”</p><h3>Key Characteristics</h3><h4>RESTful Architecture</h4><ul><li>Uses standard HTTP methods (GET, POST, PUT, DELETE)</li><li>URL-based resource access</li></ul><h4>Resource-Based Model</h4><p>FHIR organizes healthcare data into modular “Resources”:</p><ul><li><strong>Patient</strong>: Demographics, contact information</li><li><strong>Observation</strong>: Vital signs, lab results</li><li><strong>MedicationRequest</strong>: Prescriptions</li><li><strong>Condition</strong>: Diagnoses</li><li><strong>Appointment</strong>: Scheduling information</li><li><strong>DiagnosticReport</strong>: Lab test results</li><li><strong>Practitioner</strong>: Healthcare providers</li></ul><p>and many other resources; see a Swagger view of other possible resources: <a href="https://hapi.fhir.org/baseR4/swagger-ui/?page=System%20Level%20Operations">HAPI FHIR Test/Demo Server R4 Endpoint</a></p><p>Each resource is a self-contained unit of healthcare information with a standardized structure.</p><h4>Modern Data Formats</h4><ul><li><strong>JSON</strong>: Primary format (developer-friendly)</li><li><strong>XML</strong>: Alternative format</li><li>Easy to parse and generate</li></ul><h4>Interoperability</h4><ul><li>Enables different healthcare systems to communicate</li><li>Reduces integration complexity</li><li>Supports mobile and cloud applications</li><li>Industry-wide adoption</li></ul><p><strong>Problem Solved:</strong> Both patients, doctors, and hospitals can access health data on any device.</p><p><strong>Use Cases:</strong></p><ul><li>View medical records on smartphones</li><li>Share data with new doctors</li><li>Track vital signs over time</li><li>Medication reminders</li></ul><p>So a patient can visit ABC hospital and is eventually transferred to XYZ medical center; the latter can easily access all tests, diagnoses, vital signs, history, etc., just by querying the FHIR server of the former. Amazing right? 🥳. In case of an emergency, this tool would be helpful for doctors to make informed decisions.</p><h3>3. Project Overview &amp; Features</h3><h3>What We’re Building</h3><p>A <strong>demo FHIR-compliant healthcare management application</strong> built with Flutter that demonstrates real-world integration with public FHIR servers (HAPI, KODJIN, FIREFLY). The application supports patient registration and record management, diagnosis tracking, prescription and medication orders, vital signs and clinical observations, appointment scheduling, and laboratory results reporting.</p><p>From a Flutter perspective, the focus wasn’t on UI complexity but on modeling healthcare data as domain objects, mapping them cleanly to FHIR resources, and building predictable data flows for creating, reading, and updating clinical records.</p><p>Links to the public servers:<br><strong>HAPI FHIR</strong> (<a href="https://hapi.fhir.org/baseR4">https://hapi.fhir.org/baseR4</a>), <strong>Kodjin</strong> (<a href="https://demo.kodjin.com/">https://demo.kodjin.com</a>), <strong>Firefly</strong> (<a href="https://server.fire.ly/">https://server.fire.ly</a>)</p><h3>Architecture Overview</h3><p>The project follows <strong>Clean Architecture</strong> principles with two main layers:</p><pre>Domain Layer (Core Business Logic &amp;&amp; Implementation) <br>    ↓<br>Presentation Layer (UI)</pre><p><em>Don’t ask about the data layer 😔. I found it too cumbersome for this small project, so all implementation and use cases happen in the domain repository.</em></p><p>In this section, we’ll focus on the <strong>Domain Layer,</strong> which contains our business entities and models.</p><h3>Core Entities Explained</h3><h4>1. ApiResponse Entity</h4><p><strong>Purpose:</strong> Standardizes all API responses for consistent error handling</p><pre>class ApiResponse&lt;T&gt; {<br>  final bool isSuccess;<br>  final T? data;<br>  final String? error;<br>  final int? statusCode;<br><br>const ApiResponse({<br>    required this.isSuccess,<br>    this.data,<br>    this.error,<br>    this.statusCode,<br>  });<br>  // Factory constructors for success and error cases<br>  factory ApiResponse.success(T data) {<br>    return ApiResponse(<br>      isSuccess: true,<br>      data: data,<br>    );<br>  }<br>  factory ApiResponse.error(String error, {int? statusCode}) {<br>    return ApiResponse(<br>      isSuccess: false,<br>      error: error,<br>      statusCode: statusCode,<br>    );<br>  }<br>  // Safe data access<br>  T get safeData =&gt; data as T;<br>}</pre><p><strong>Why This Matters:</strong></p><ul><li>Type-safe response handling</li><li>Consistent error management</li></ul><h4>2. Other project FHIR-related Entities (Patient, Observation, MedicationRequest, Condition, Appointment, DiagnosticReport, Practitioner)</h4><p>There are models from the <strong>fhir_r4</strong> plugin (an Official FHIR R4 implementation for Dart on <a href="https://pub.dev/packages/fhir_r4">pub.dev (fhir_r4)</a>), but they can be very complex to work with; therefore, I created an entity that complements the plugin’s models.</p><p>For Patient Entity:</p><pre>class ProjectPatientEntity {<br>  final String id;<br>  final String firstName;<br>  final String lastName;<br>  final DateTime dateOfBirth;<br>  final String? gender;<br>  final String phoneNumber;<br>  final String? email;<br>  final String? address;<br>  final String? emergencyContactNo;<br><br>ProjectPatientEntity({<br>    required this.id,<br>    required this.firstName,<br>    required this.lastName,<br>    required this.dateOfBirth,<br>    this.gender,<br>    required this.phoneNumber,<br>    this.email,<br>    this.address,<br>    this.emergencyContactNo,<br>  });</pre><p>In the app, the parameters of ProjectPatientEntity are intentionally designed to mirror the input fields in the Register Patient screen. This keeps the Flutter form layer simple and predictable, allowing user input to be captured as a plain domain object without any direct dependency on FHIR.</p><p>Before persisting data, this domain entity is then mapped into a FHIR Patient resource. At this boundary, application-specific fields — such as names, contact details, gender, and date of birth — are translated into their standardized FHIR equivalents. This extra mapping step is deliberate: it decouples the Flutter UI and business logic from the FHIR schema while ensuring that any data sent to the server conforms strictly to interoperability standards.</p><pre>import &#39;package:fhir_r4/fhir_r4.dart&#39; as fhir;<br><br>MapStringDynamic addPatient({fhir.Patient? existingPatient}) {<br>    final body = fhir.Patient(<br>      id: fhir.FhirString(id),<br>      active: fhir.FhirBoolean(true),<br>      name: [<br>        HumanName(family: lastName.toFhirString, given [firstName.toFhirString]),<br>      ],<br>      identifier: [fhir.Identifier(value: ApiConstants.projectIdentifier.toFhirString)],<br>      birthDate: dateOfBirth.toFhirDate,<br>      gender: gender != null ? fhir.AdministrativeGender(gender?.toLowerCase()) : null,<br>      telecom: [<br>        fhir.ContactPoint(system: fhir.ContactPointSystem.email, value: email?.toFhirString),<br>        fhir.ContactPoint(system: fhir.ContactPointSystem.phone, value: phoneNumber.toFhirString),<br>        fhir.ContactPoint(system: fhir.ContactPointSystem.other, value: emergencyContactNo?.toFhirString),<br>      ],<br>      address: address != null ? [fhir.Address(text: address?.toFhirString)] : null,<br>    );<br>// I use the .copyWith() when i am editing an already existing patient data<br>    if (existingPatient != null) {<br>      final updatedPatient = existingPatient.copyWith(<br>        name: body.name,<br>        birthDate: body.birthDate,<br>        gender: body.gender,<br>        telecom: body.telecom,<br>        address: body.address,<br>        active: body.active,<br>      );<br>      return updatedPatient.toJson();<br>    }<br>    return body.toJson();<br>  }</pre><p>For Prescription Entity:</p><pre>class ProjectPrescriptionEntity {<br>  final String patientId;<br>  final String medication;<br>  final int dosage;<br>  final String route;<br>  final int frequency;<br>  final int duration;<br>  final DateTime startDate;<br>  final String prescribingDoctor;<br>  final String? instructions;<br><br>ProjectPrescriptionEntity({<br>    required this.patientId,<br>    required this.medication,<br>    required this.dosage,<br>    required this.route,<br>    required this.frequency,<br>    required this.duration,<br>    required this.startDate,<br>    required this.prescribingDoctor,<br>    this.instructions,<br>  });<br>  // Convert to FHIR MedicationRequest<br>  Map&lt;String, dynamic&gt; addPrescription() {<br>    return MedicationRequest(<br>      status: MedicationrequestStatus.active,<br>      intent: MedicationrequestIntent.order,<br>      subject: Reference(<br>        reference: &#39;Patient/$patientId&#39;.toFhirString,<br>      ),<br>      medicationCodeableConcept: CodeableConcept(<br>        text: medication.toFhirString,<br>      ),<br>      authoredOn: startDate.toFhirDateTime,<br>      requester: Reference(<br>        display: prescribingDoctor.toFhirString,<br>      ),<br>      dosageInstruction: [<br>        Dosage(<br>          text: instructions?.toFhirString,<br>          timing: Timing(<br>            repeat: TimingRepeat(<br>              frequency: frequency.toFhirPositiveInt,<br>              period: 1.toFhirDecimal,<br>              periodUnit: &#39;d&#39;.toFhirString,<br>              duration: duration.toFhirDecimal,<br>              durationUnit: &#39;d&#39;.toFhirString,<br>            ),<br>          ),<br>          route: CodeableConcept(text: route.toFhirString),<br>          doseAndRate: [<br>            DosageDoseAndRate(<br>              doseQuantity: Quantity(<br>                value: dosage.toFhirDecimal,<br>                unit: &#39;mg&#39;.toFhirString,<br>              ),<br>            ),<br>          ],<br>        ),<br>      ],<br>    ).toJson();<br>  }<br>}</pre><p>The same method goes for all the other entities in the project. Check the Entities folder in the project: <a href="https://github.com/Captured-Heart/fhir_demo/tree/main/lib/src/domain/entities">lib/src/domain/entities - Source Code (Github)</a></p><h3>4. Libraries and tools for FHIR development</h3><h3>Core Dependencies</h3><p><strong>1.</strong> <a href="https://pub.dev/packages/fhir_r4"><strong>fhir_r4</strong></a><strong>:</strong> A Dart implementation of the FHIR (Fast Healthcare Interoperability Resources) R4 specification</p><pre>dependencies:<br>  fhir_r4: ^0.4.3</pre><p><strong>Features:</strong></p><ul><li>Complete FHIR R4 resource models</li><li>Type-safe resource creation</li><li>JSON/YAML serialization</li><li>Validation support</li><li>Extension methods</li></ul><p><strong>2.</strong> <a href="https://pub.dev/packages/flutter_riverpod"><strong>flutter_riverpod</strong></a><strong>:</strong> A reactive caching and data-binding framework</p><pre>dependencies:<br>  flutter_riverpod: ^2.6.1</pre><p><strong>Key Features for Our App:</strong></p><ul><li>AutoDisposeNotifier: Automatic controller cleanup</li><li>Provider: Dependency injection</li><li>Type-safe state access</li></ul><p><em>P.S: I am not a big fan of being loyal to a state management solution; you can use any that works! 😅😅</em></p><p><strong>3.</strong> <a href="https://pub.dev/packages/dio"><strong>Dio</strong></a><strong>:</strong> Powerful HTTP client for Dart</p><pre>dependencies:<br>  dio: ^5.9.0</pre><p><strong>Key Features:</strong></p><ul><li>Base URL configuration</li><li>Custom headers (FHIR requires application/fhir+json)</li><li>Retry mechanism</li><li>Progress callbacks</li></ul><p><strong>4.</strong> <a href="https://pub.dev/packages/dio_smart_retry"><strong>dio_smart_retry</strong></a><strong>:</strong> Automatic retry for failed requests</p><pre>dependencies:<br>  dio_smart_retry: ^7.0.1</pre><p><strong>Features:</strong></p><ul><li>Exponential backoff</li><li>Configurable retry count</li><li>Specific error type retry</li></ul><p><strong>Configuration:</strong></p><pre>dio.interceptors.add(<br>  RetryInterceptor(<br>    dio: dio,<br>    retries: 3,<br>    retryDelays: [<br>      Duration(seconds: 1),<br>      Duration(seconds: 3),<br>      Duration(seconds: 5),<br>    ],<br>  ),<br>);</pre><h3>What’s Coming in Part 2: Implementation</h3><p><strong>Part 2 will dive deep into the actual implementation:</strong></p><h4>1. Project Setup &amp; Configuration</h4><ul><li>Installing dependencies</li><li>Platform-specific configuration</li></ul><h4>2. Network Layer Implementation</h4><ul><li>Dio configuration and setup</li><li>FHIR server integration</li><li>Interceptors (logging, retry, auth)</li><li>Dynamic server switching</li><li>Error handling</li></ul><h4>3. Repository Pattern</h4><ul><li>Abstract repositories</li><li>Implementation with dependency injection</li><li>CRUD operations</li><li>API response handling</li></ul><h4>4. State Management with Riverpod</h4><ul><li>Controller setup</li><li>Form state management</li><li>Loading states</li><li>Error handling</li><li>Provider dependency injection</li></ul><h4>5. Building FHIR Forms</h4><p><strong>Complete implementation of:</strong></p><ul><li>Patient registration form</li><li>Prescription form with validation</li><li>Observations form</li><li>Converting form data to FHIR resources</li><li>Submitting to the FHIR server</li><li>Handling responses</li></ul><h3>Prepare for Part 2</h3><p><strong>Recommended Actions:</strong></p><ol><li><strong>Clone the Repository:</strong></li></ol><pre>git clone https://github.com/Captured-Heart/fhir_demo.git <br>cd fhir_demo</pre><p>2.<strong> Explore FHIR Documentation:</strong></p><ul><li><a href="https://hl7.org/fhir/R4/">FHIR R4 Specification</a></li><li><a href="https://hl7.org/fhir/R4/resourcelist.html">FHIR Resources Guide</a></li></ul><p>3.<strong> Try HAPI FHIR Server:</strong></p><ul><li>Visit: <a href="https://hapi.fhir.org/baseR4">https://hapi.fhir.org/baseR4</a></li><li>Explore existing resources</li><li>Try creating a Patient via Swagger UI</li></ul><p>4.<strong> Review Flutter Concepts:</strong></p><ul><li>Form handling</li><li>State management basics</li><li>HTTP requests</li></ul><h3>Resources</h3><h3>FHIR Documentation</h3><ul><li><a href="https://www.hl7.org/fhir/">HL7 FHIR Official</a></li><li><a href="https://hl7.org/fhir/R4/">FHIR R4 Spec</a></li><li><a href="https://hl7.org/fhir/R4/resourcelist.html">Resource Examples</a></li><li><a href="https://fhir-fli.github.io/fhir_fli_documentation/docs">FHIR-FLI</a></li><li><a href="https://medblocks.com/training/courses/fhir-fundamentals/fhir-fun-1-2-what-is-fhir">Medblocks — FHIR Fundamentals Course</a></li><li><a href="https://docs.kodjin.com/kodjin-restful-api/">KODJIN FHIR Server Documentation</a></li><li><a href="https://www.youtube.com/playlist?list=PLKuZNI94tzWbmT8q9M58JSKvhV6DEyt3O">HL7 FHIR DevDays YouTube Playlist</a></li></ul><h3>FHIR Servers</h3><ul><li><a href="https://hapi.fhir.org/baseR4">HAPI FHIR Test Server</a></li><li><a href="https://hapi.fhir.org/baseR4/swagger-ui/">HAPI Swagger UI</a></li><li><a href="https://demo.kodjin.com/">KODJIN Demo Server</a></li><li><a href="https://server.fire.ly/">FIREFLY Server</a></li><li><a href="https://confluence.hl7.org/spaces/FHIR/pages/35718859/Public+Test+Servers">Confluence — Public test servers list</a></li></ul><h3>Flutter Resources</h3><ul><li><a href="https://flutter.dev/docs">Flutter Documentation</a></li><li><a href="https://riverpod.dev/">Riverpod Docs</a></li><li><a href="https://pub.dev/packages/fhir_r4">fhir_r4 Package</a></li></ul><h3>Project Links</h3><ul><li><a href="https://github.com/Captured-Heart/fhir_demo">GitHub Repository</a></li><li>Part 2 (Coming Soon!)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff63ab3f7df3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter meets Igbo:]]></title>
            <link>https://medium.com/@captured_heart/flutter-meets-igbo-5c3e148f81e5?source=rss-7fa89a520e0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c3e148f81e5</guid>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[igbo]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[pubdev]]></category>
            <dc:creator><![CDATA[Nkpozi Marcel Kelechi]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 00:25:59 GMT</pubDate>
            <atom:updated>2025-06-25T08:32:50.821Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flutter meets Igbo: Integrate Igbo and Other Native Languages into Flutter Apps: A Step-by-Step Guide Using easy_localization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tiku7ofe64PpLxdPj-jBjQ.png" /></figure><h3>Multilingual Software Applications: Why We Need Localization.</h3><p>Localization in mobile software development refers to the process of adapting apps to support multiple languages and cultural settings. It emerged alongside the rapid growth of the mobile app ecosystem in the early 2000s. Initially, apps were primarily focused on a global audience, but the need for localization became evident as users from diverse cultural backgrounds began to adopt mobile devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/0*ZjScCTFwupBMpF2K.gif" /></figure><h3>Project Setup</h3><p><em>P.S. I assume the reader of this article is familiar with the Flutter framework.</em> 😅<br><em>A public repository for the full implementation is available on</em> <a href="https://github.com/Captured-Heart/flutter_meets_igbo"><em>GitHub</em></a> <em>for you to follow along.</em></p><h3>Installing 3rd-party plugins</h3><p>The first step is creating a new Flutter project. Run “flutter create &lt;DIRECTORY&gt;” in the command line,</p><pre>flutter create &lt;DIRECTORY&gt;</pre><p>Below is a list of the 3rd-party plugins used in this project:</p><ol><li><a href="https://pub.dev/packages/cached_network_image">Cached_network_image</a>: “<em>A flutter library to show images from the internet and keep them in the cache directory.</em>”</li><li><a href="https://pub.dev/packages/easy_localization">Easy_localization</a>: “<em>A reactive caching and data-binding framework</em>.”</li><li><a href="https://pub.dev/packages/faker">Faker</a>: “<em>Faker is a Python package that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill in your persistence to stress test it, or anonymize data taken from a production service, Faker is for you.</em>”</li><li><a href="https://pub.dev/packages/flutter_widget_from_html">Flutter_widget_from_html</a>: “<em>Flutter package to render HTML as widgets that supports hyperlink, image, audio, video, iframe, and 70+ other tags.</em>”</li><li><a href="https://pub.dev/packages/intl">Intl</a>: “<em>Provides internationalization and localization facilities, including message translation, plurals and genders, date/number formatting and parsing, and bidirectional text.</em>”</li><li><a href="https://pub.dev/packages/carousel_slider">Carousel_slider</a>: “<em>A carousel slider widget</em>”.</li></ol><pre>dependencies:<br>  cached_network_image: ^3.4.1<br>  carousel_slider: ^5.0.0<br>  easy_localization: ^3.0.7+1<br>  faker: ^2.2.0<br>  flutter:<br>    sdk: flutter<br>  flutter_widget_from_html: ^0.16.0<br>  intl: ^0.19.0</pre><p>…</p><h3>Add “Easy_localization” dependency.</h3><p>One can also configure localizations using other plugins on <a href="http://pub.dev/">pub.dev</a>, such as:</p><ul><li><a href="https://pub.dev/packages/flutter_localization">Flutter_localization</a></li><li><a href="https://pub.dev/packages/localization">localization</a></li><li><a href="https://pub.dev/packages/slang">Slang</a></li><li><a href="https://pub.dev/packages/i18n_extension">i18n_extension</a></li><li><a href="https://pub.dev/packages/flutter_translate">flutter_translate</a></li></ul><p>And many more! But for the sake of this project, I have a personal liking for Easy_localization because:</p><ul><li>It is always maintained</li><li>It has comprehensive documentation and is easy to understand for any level of development</li><li>It is also a common choice, as it has the most stats/scores by developers amongst the others on pub (LIKES = 3.59k, PUB POINTS = 150/160, DOWNLOADS = 74.6k) <em>as at 11th June, 2025</em></li><li>It also supports loading translation files with extensions such as JSON, XML, YAML, and CSV</li><li>It supports plural, gender, nesting, and RTL locales (like Arabic)</li><li>It also promotes fallback locale keys redirection; that means if the selected locale isn’t in the list, it falls back to a set locale.</li></ul><p>To install easy_localization in the project, you should start by reading the documentation on <a href="http://pub.dev/">pub.dev</a>: <a href="https://pub.dev/packages/easy_localization">Easy_localization</a>.</p><ul><li>Add the easy_localization ⁣dependency on your “pubspec.yaml” file: dependencies:</li></ul><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>easy_localization: ^3.0.7</pre><p>Run flutter pub get</p><p>…</p><p><strong>In the main.dart:</strong></p><p>Configure the project by initializing it above the <strong>runApp()</strong> method inside the <strong>main()</strong>, and wrap the <strong>MyApp()</strong> root widget with the EasyLocalization widgets.</p><pre>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  runApp(<br>    EasyLocalization(<br>      supportedLocales: const [Locale(&#39;en&#39;, &#39;US&#39;), Locale(&#39;es&#39;, &#39;ES&#39;), Locale(&#39;ig&#39;, &#39;NG&#39;)],<br>      saveLocale: true,<br>      path: &#39;assets/l10n&#39;,<br>      fallbackLocale: const Locale(&#39;en&#39;, &#39;US&#39;),<br>      child: const MyApp(),<br>    ),<br>  );<br>}</pre><p>The EasyLocalization Widget has a couple of parameters with some required*:</p><ul><li>supportedLocales*: List of supported locales.</li><li>path*: Path to your folder with localization files.</li><li>savedLocale: Save locale in device storage.</li><li>fallbackLocale: Returns the locale when the locale is not in the list of supportedLocales.</li><li>startLocale: Overrides device locale.</li><li>assetLoader: Class loader for localization files. You can use custom loaders from <a href="https://github.com/aissat/easy_localization_loader">Easy Localization Loader</a> <a href="https://github.com/aissat/easy_localization_loader">or create your clas</a>s.</li><li>errorWidget: Shows a custom error widget when an error occurs.</li></ul><p>On the pubspec.yaml, adding the path of the translation files to “assets”</p><pre>flutter:<br>  uses-material-design: true<br>  assets:<br>    - assets/images/<br>    - assets/l10n/</pre><p>In the <strong>MaterialApp()</strong> widget, we will configure the localizationDelegates, supportedLocales, and locale. Since we are using the easy_localization plugin, we can get these parameters via its extension to the build context, courtesy of the plugin.</p><pre>MaterialApp(<br>     // ...<br>      localizationsDelegates: context.localizationDelegates,<br>      supportedLocales: context.supportedLocales,<br>      locale: context.locale,<br>     // ...<br>);</pre><p>Looking at the Easy_localization codebase, we discover that the context.localizationDelegates is a getter for the MaterialLocalization classes, so we don’t need to pass the Flutter material localizations to supported locales in the MaterialApp Widget.</p><pre><br>class _EasyLocalizationProvider extends InheritedWidget {<br>  final EasyLocalization parent;<br>  final EasyLocalizationController _localeState;<br>  final Locale? currentLocale;<br>  final _EasyLocalizationDelegate delegate;<br><br>  /// {@macro flutter.widgets.widgetsApp.localizationsDelegates}<br>  ///<br>  /// ```dart<br>  ///   delegates = [<br>  ///     delegate<br>  ///     GlobalMaterialLocalizations.delegate,<br>  ///     GlobalWidgetsLocalizations.delegate,<br>  ///     GlobalCupertinoLocalizations.delegate<br>  ///   ],<br>  /// ```<br>  List&lt;LocalizationsDelegate&gt; get delegates =&gt; [<br>        delegate,<br>        GlobalMaterialLocalizations.delegate,<br>        GlobalWidgetsLocalizations.delegate,<br>        GlobalCupertinoLocalizations.delegate,<br>      ];<br><br>  /// Get List of supported locales<br>  List&lt;Locale&gt; get supportedLocales =&gt; parent.supportedLocales;<br><br>...<br><br>}</pre><p><strong>Please Note</strong> ⚠️ : For translation to work on **iOS,** you need to add supported locales to `ios/Runner/Info.plist` as shown below:</p><pre> &lt;key&gt;CFBundleLocalizations&lt;/key&gt;<br>  &lt;array&gt;<br>   &lt;string&gt;en&lt;/string&gt;<br>   &lt;string&gt;es&lt;/string&gt;<br>   &lt;string&gt;ig&lt;/string&gt;<br>  &lt;/array&gt;</pre><p>To start the translations, we create a class to hold the keys of the text to be translated into any language.</p><pre>abstract class TextConstant {<br>  static const appTitle = &#39;appTitle&#39;;<br>  static const createYourAcct = &#39;createYourAcct&#39;;<br>  static const haveAnAcct = &quot;haveAnAcct&quot;;<br>  static const login = &#39;login&#39;;<br>  static const firstName = &#39;firstName&#39;;<br>  static const enterFullNameAsWritten = &#39;enterFullNameAsWritten&#39;;<br>  static const lastName = &#39;lastName&#39;;<br>  static const userName = &#39;userName&#39;;<br>  static const emailAddress = &#39;emailAddress&#39;;<br>  static const password = &#39;password&#39;;<br>  static const emailHint = &#39;emailHint&#39;;<br>  static const confirmPassword = &#39;confirmPassword&#39;;<br>  static const createAccount = &#39;createAccount&#39;;<br>  static const passwordMustBe = &#39;passwordMustBe&#39;;<br>  static const loginToYourAccount = &#39;loginToYourAccount&#39;;<br>  static const dontHaveAnAcct = &quot;dontHaveAnAcct&quot;;<br>// ... // ADD AS MUCH YOU WANT                                                                                                                        <br>}</pre><p><strong>Create the “L10n folder.”</strong></p><p>The “L10n” folder contains the translation files (en-US, es-ES, ig-NG), and for the sake of this project, I will be using the JSON file type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/0*4txoWII4ejvSAdSl.png" /><figcaption>codesnap of L10n directory</figcaption></figure><p>According to the Easy_localization documentation on <a href="http://pub.dev/">pub.dev</a>, the translation files can be named in two ways:</p><ol><li>only language code + extension: such as (en.json, ig.json, es.json)</li><li>Language code — country code + extension: such as (en-US.json, es-ES.json, ig-NG.json)</li></ol><p>We create the JSON files:</p><pre>// en-US.json, The english file<br>{<br>    &quot;appTitle&quot;: &quot;Igbo Flutter Locale Demo&quot;,<br>    &quot;weAreGladYouAreHere&quot;: &quot;We are glad you are here&quot;,<br>    &quot;createYourAcct&quot; : &quot;Create your account&quot;,<br>    &quot;haveAnAcct&quot; : &quot;Have an account?&quot;,<br>    &quot;login&quot; : &quot;Login&quot;,<br>    &quot;firstName&quot; : &quot;First Name&quot;,<br>    &quot;enterFullNameAsWritten&quot; : &quot;enter your full name as its written on your id card&quot;,<br>    &quot;lastName&quot; : &quot;Last Name&quot;,<br>    &quot;userName&quot; : &quot;Username&quot;,<br>    &quot;emailAddress&quot; : &quot;Email address&quot;<br>// ...<br>}</pre><pre>//es-ES.json, The Spanish file<br>{<br>  &quot;appTitle&quot;: &quot;Demostración de localización Flutter Igbo&quot;,<br>  &quot;confirm&quot;: &quot;Confirmar&quot;,<br>  &quot;confirmPassword&quot;: &quot;confirmar Contraseña&quot;,<br>  &quot;createAccount&quot;: &quot;Crear una cuenta&quot;,<br>  &quot;createYourAcct&quot;: &quot;Crea tu cuenta&quot;,<br>  &quot;dontHaveAnAcct&quot;: &quot;¿No tienes una cuenta?&quot;,<br>  &quot;emailAddress&quot;: &quot;Dirección de correo electrónico&quot;<br>// ...<br>}</pre><pre>//ig-NG.json. The Igbo file<br>{<br>    &quot;appTitle&quot;: &quot;Ngosipụta Asụsụ Igbo Flutter&quot;,<br>    &quot;alreadyHaveAnAcct&quot;: &quot;Ị nweelarị akaụntụ?&quot;,<br>    &quot;signUp&quot;: &quot;Debanye aha&quot;,<br>    &quot;createYourAcct&quot; : &quot;Mepụta akaụntụ gị&quot;,<br>    &quot;haveAnAcct&quot; : &quot;Ị nwere akaụntụ?&quot;,<br>    &quot;login&quot; : &quot;Banye&quot;,<br>    &quot;firstName&quot; : &quot;Aha mbụ&quot;,<br>    &quot;enterFullNameAsWritten&quot; : &quot;Tinye aha gị zuru oke dịka edere ya na kaadị njirimara gị.&quot;,<br>    &quot;lastName&quot; : &quot;Aha nna&quot;,<br>    &quot;userName&quot; : &quot;Aha njirimara&quot;,<br>    &quot;emailAddress&quot; : &quot;Adreesị ozi-e&quot;<br>// ...<br>}</pre><p>Create Locale Switch</p><p>I created an enum to contain the Flag, Title and Locale for every language. This would be helpful in the locale switch.</p><pre>enum L10nEnum {<br>  enUS(&#39;🇺🇸&#39;, &#39;English&#39;, Locale(&#39;en&#39;, &#39;US&#39;)),<br>  esES(&#39;🇪🇸&#39;, &#39;Spanish&#39;, Locale(&#39;es&#39;, &#39;ES&#39;)),<br>  igNG(&#39;🇳🇬&#39;, &#39;Igbo&#39;, Locale(&#39;ig&#39;, &#39;NG&#39;));<br> <br>const L10nEnum(this.flag, this.lang, this.locale);<br>  final String flag;<br>  final String lang;<br>  final Locale locale;<br>  static L10nEnum fromLocale(Locale locale) {<br>    return L10nEnum.values.firstWhere(<br>      (e) =&gt; e.locale.languageCode == locale.languageCode &amp;&amp; e.locale.countryCode == locale.countryCode,<br>      orElse: () =&gt; L10nEnum.enUS,<br>    );<br>  }<br>}</pre><p>In the profile_screen, I created a Widget that allows me to change between locales.</p><pre>showModalBottomSheet(  <br> context: context,<br>  isDismissible: false,<br>  elevation: 4,<br>  backgroundColor: themeContext.scaffoldBackgroundColor,<br>  shape: RoundedRectangleBorder(<br>    borderRadius: const BorderRadius.only(topLeft: Radius.circular(20), topRight: Radius.circular(20)),<br>    side: BorderSide(color: themeContext.primaryColor, width: 0.2),<br>  ),<br>  builder: (context) =&gt; Column(<br>    mainAxisAlignment: MainAxisAlignment.center,<br>    crossAxisAlignment: CrossAxisAlignment.stretch,<br>    mainAxisSize: MainAxisSize.min,<br>    children: context.supportedLocales.map((locale) {<br>      final L10nEnum localeEnum = L10nEnum.fromLocale(locale);<br>      final flag = localeEnum.flag;<br>      final lang = localeEnum.lang;<br><br>      return ListTile(<br>        onTap: () {<br>          context.setLocale(locale);<br>          chatController.setL10nEnum(localeEnum, context: context);<br>        },<br>        contentPadding: const EdgeInsets.symmetric(vertical: 5),<br>        leading: Container(<br>          padding: const EdgeInsets.all(10),<br>          decoration: BoxDecoration(<br>            color: themeContext.scaffoldBackgroundColor,<br>            border: Border.all(color: themeContext.primaryColor),<br>            borderRadius: BorderRadius.circular(10),<br>          ),<br>          child: Text(flag, textScaleFactor: 1.6),<br>        ),<br>        title: Text(lang, textAlign: TextAlign.start, textScaleFactor: 1.3),<br>      );<br>    }).toList(),<br>),<br>)</pre><p>Using the showModalBottomSheet, a standard Material Design widget, to present users with a list of supported languages or regional formats. This modal interface slides up from the bottom of the screen, offering an intuitive way for users to view and potentially select their preferred locale. To streamline the handling and representation of these locales within the codebase, the enum L10nEnumis employed. This enum is designed to correspond to the Locale objects retrieved from context.supportedLocales. This approach facilitates more robust and type-safe logic when working with different localizations, for instance, when displaying localized names for each language or managing locale-specific resources and behaviours within the application.</p><p>context.setLocale(locale): This is a method provided by the plugin; it saves the selected locale and triggers the translations.</p><p>chatController.setL10nEnum(localeEnum, context: context): It is a ChangeNotifier class I created in the ChatController file to trigger translation in the Chat_View. You can view the contents of the chatController class here on <a href="https://github.com/Captured-Heart/flutter_meets_igbo/blob/main/lib/src/chat/controller/chat_controller.dart">GitHub</a>.</p><p><strong>On the Text Widget</strong></p><p>In reviewing localization strategies, I will cover the various methods outlined in the documentation. However, for optimal reliability and to prevent common pitfalls, my preferred approach is to utilise statically defined string constants as translation keys. This practice significantly reduces the risk of typographical errors, a frequent cause of failed translations.</p><pre>//METHOD 1: Wrapping the translation with context.tr()<br>Text(context.tr(&#39;settings&#39;))<br><br>//METHOD 2: using the tr() without [Context] as a static function<br> Text(&#39;settings&#39;).tr() //Text widget<br><br> var settings = tr(&#39;settings&#39;);// As String; tr() returns a String<br> Text(settings);<br><br>//METHOD 3: MY Preferred approach<br>Text(TextConstant.settings.tr(),)</pre><p><strong>Please Note</strong> ⚠️ : The documentation warns against Method 2, saying <em>it’s not recommended in build methods because the widget won’t rebuild when the language changes.</em></p><p><strong>The tr() method</strong></p><p>The tr() method is a static method from the easy_localization plugin that returns a String. It also takes other arguments, such as args, namedArgs⁣, and gender.</p><p>Continue with the example, and I will explain the arguments above. We will edit any of the JSON files that contain the translations. In this case, I will edit the en-US.json.</p><pre>{<br>//...<br><br>//ARGS 1 &amp; 2<br> &quot;settings&quot; : &quot;{} Settings&quot;<br> &quot;settings&quot; : &quot;{} Settings is {}&quot;<br><br>//NAMED_ARGS<br>&quot;settings&quot; : &quot;{name} Settings&quot;<br><br>//GENDER<br>&quot;settings&quot; : {<br>    &quot;male&quot;: &quot;His Settings&quot;,<br>    &quot;female&quot;: &quot;Her Settings&quot;,<br>    &quot;other&quot;: &quot;Settings&quot;<br>}<br>//...<br>}</pre><p><strong>View Results</strong></p><ol><li>FOR ARGS</li></ol><pre>//ARGS 1<br>Text(<br>TextConstant.settings.tr(args: [&#39;My&#39;]), // OUTPUT: &quot;My Settings&quot;<br>),<br>//ARGS 2<br>Text(<br>TextConstant.settings.tr(args: [&#39;My&#39;, &#39;Open&#39;]), // OUTPUT: &quot;My Settings is Open&quot;<br>),</pre><ol><li>FOR NAMED ARGS</li></ol><pre>Text(<br>TextConstant.settings.tr(namedArgs: {&#39;name&#39;: &#39;Marcel&#39;}), // OUTPUT: &quot;Marcel Settings&quot;<br>),</pre><ol><li>GENDER</li></ol><pre>Text(<br>TextConstant.settings.tr(gender: &#39;male&#39;), // OUTPUT: &quot;His Settings&quot;<br>),<br><br>Text(<br>TextConstant.settings.tr(gender: &#39;female&#39;), // OUTPUT: &quot;Her Settings&quot;<br>),</pre><h3>Observation</h3><p>When we switched between locales, it worked until we switched to “Igbo” language, and a widget exception occurred, saying:</p><p>═══════Exception caught by the widgets library══════</p><p>No MaterialLocalizations found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/0*HsHzBKl38_k2fHWq.png" /></figure><p>At its core, this error means a widget from Flutter’s Material library (like TextField, AlertDialog, or the back button&#39;s tooltip) tried to display a piece of text, but couldn&#39;t find the translation for the app&#39;s current language.The MaterialLocalizations class is responsible for providing these framework-level strings. To do this, MaterialApp needs a &quot;delegate&quot; that knows how to load these strings for a given locale.</p><p>To fix the “No MaterialLocalization found” Error:</p><ol><li>We create the translations class, which is similar to our translations JSON files, but here we extend the class to DefaultMaterialLocalizations and translate to the Igbo language.</li></ol><pre>class IgboMaterialLocalizations extends DefaultMaterialLocalizations {<br>  @override<br>  String get openAppDrawerTooltip =&gt; &#39;Mepee drawer nnabata&#39;;<br><br>  @override<br>  String get backButtonTooltip =&gt; &#39;Azụ&#39;;<br>  <br>  @override<br>  String get closeButtonTooltip =&gt; &#39;Mechie&#39;;<br>  <br>  @override<br>  String get deleteButtonTooltip =&gt; &#39;Hichapụ&#39;;<br>  <br>  @override<br>  String get nextMonthTooltip =&gt; &#39;Ọnwa na-esote&#39;;<br>  <br>  @override<br>  String get previousMonthTooltip =&gt; &#39;Ọnwa gara aga&#39;;<br>  <br>  @override<br>  String get nextPageTooltip =&gt; &#39;Ibe na-esote&#39;;<br>  <br>  @override<br>  String get previousPageTooltip =&gt; &#39;Ibe gara aga&#39;;<br>  <br>  @override<br>  String get showMenuTooltip =&gt; &#39;Gosi menu&#39;;<br>  <br>  @override<br>  String get cancelButtonLabel =&gt; &#39;Kagbuo&#39;;<br>  static const LocalizationsDelegate&lt;MaterialLocalizations&gt; delegate = _IgboMaterialLocalizationsDelegate();<br><br>//... AND MANY OTHHER OVERRIDES<br>}</pre><p>The DefaultMaterialLocalizations is a concrete class provided by Flutter that contains all the required strings in English. By extending it, we only need to @override the strings we want to translate into Igbo. If you happen to miss one, it will safely fall back to the English version from the parent class, rather than causing an error.</p><p>2. We create the delegate, which tells Flutter how and when to load our IgboMaterialLocalizations class. MaterialApp maintains a list of these delegates and consults them whenever the locale changes.</p><pre>class _IgboMaterialLocalizationsDelegate extends LocalizationsDelegate&lt;MaterialLocalizations&gt; {<br>  const _IgboMaterialLocalizationsDelegate();<br><br>  @override<br>  bool isSupported(Locale locale) =&gt; locale.languageCode == &#39;ig&#39;;<br><br>  @override<br>  Future&lt;MaterialLocalizations&gt; load(Locale locale) async =&gt; IgboMaterialLocalizations();<br><br>  @override<br>  bool shouldReload(_IgboMaterialLocalizationsDelegate old) =&gt; false;<br>}</pre><p>This class has three essential methods:</p><ul><li>isSupported(Locale locale): This is the first method Flutter calls. It asks the delegate, &quot;Can you handle this language?&quot; Here, it simply checks if the language code is &#39;ig&#39;. If it returns trueFlutter proceeds to the next step.</li><li>load(Locale locale): Since isSupported returned trueFlutter now calls load to get the actual translation object. This method&#39;s only job is to create and return an instance of our IgboMaterialLocalizations class.</li><li>shouldReload(...): This is an optimization. It asks if the translations need to be reloaded when the widget tree rebuilds. Since our Igbo strings are hard-coded and won&#39;t change at runtime, I set it to false.</li></ul><p>Finally, I expose a static instance of the delegate for easy access, which can be found in my MaterialApp like IgboMaterialLocalizations.delegate.</p><p>3. Repeating the Pattern for Widgets and Cupertino</p><p>I have identified that Material isn&#39;t the only widget set. The same pattern is repeated for:</p><ul><li>IgboWidgetsLocalizations: For basic, non-styled widgets (handles things like text direction).</li><li>IgboCupertinoLocalizations: For iOS-style widgets.</li></ul><p>By providing delegates for all three, we ensure that our app is fully and correctly localized, regardless of the Flutter widgets we use.</p><p>Our main.dart now looks like this:</p><pre>MaterialApp(<br>      //...<br>      localizationsDelegates: [<br>        IgboCupertinoLocalizations.delegate,<br>        IgboMaterialLocalizations.delegate,<br>        IgboWidgetsLocalizations.delegate,<br>        ...context.localizationDelegates,<br>      ],<br>      supportedLocales: context.supportedLocales,<br>      locale: context.locale,<br>      //...<br>);</pre><p>Voila ✅ 🥳🥳, Everything works well now!</p><h3>Conclusion</h3><p>This article provides a comprehensive guide to setting up a Flutter project with Easy Localization integration, highlighting essential steps such as creating a new Flutter project, installing third-party plugins like Shared_Preferences, faker, and flutter_widget_from_html, and configuring Android and iOS platforms for locale functionality.</p><p>In conclusion, effectively localizing a Flutter application is paramount for reaching a global audience, and the easy_localization package emerges as a powerful and developer-friendly solution to achieve this. As we’ve explored, its straightforward setup, coupled with robust features like automatic locale saving, fallback mechanisms, and support for various translation file formats, significantly streamlines the internationalization workflow.</p><p>👉 <strong>Ready to get started?</strong> Check out the full implementation on <a href="https://github.com/Captured-Heart/flutter_meets_igbo">GitHub(Flutter_meets_igbo)</a> and bring your maps to life!</p><h3>References</h3><p><a href="https://github.com/Captured-Heart/flutter_meets_igbo">Flutter Meets Igbo Github Repository</a></p><p><a href="https://poeditor.com/blog/mobile-app-localization/#:~:text=Mobile%20app%20localization%20is%20the,and%20other%20culturally%20specific%20components.">Mobile app localization: Importance and steps</a></p><p><a href="https://vistatec.com/visiting-the-history-of-localization-to-understand-the-future/">Visiting the History of Localization to Understand the Future</a></p><p><a href="https://pub.dev/packages/easy_localization">Easy Localization (pub.dev)</a></p><p><a href="https://pub.dev/packages/faker">faker (pub.dev)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c3e148f81e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhance Your Google Maps with Dynamic Themes Using Riverpod]]></title>
            <link>https://medium.com/@captured_heart/enhance-your-google-maps-with-dynamic-themes-using-riverpod-e3d509ca1e1a?source=rss-7fa89a520e0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3d509ca1e1a</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[riverpod]]></category>
            <category><![CDATA[google-map-platform]]></category>
            <dc:creator><![CDATA[Nkpozi Marcel Kelechi]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 00:47:25 GMT</pubDate>
            <atom:updated>2025-04-23T01:10:18.913Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*ImTurAgP9cJ8rSChCq_iTw.jpeg" /><figcaption>Enhance Your Google Maps with Dynamic Themes Using Riverpod</figcaption></figure><h3>Google maps</h3><p>Since its launch in 2005, Google Maps has transformed from just a basic online mapping tool to a central part of modern mobile apps, used in everything from ride-sharing to travel guides and healthcare platforms. While Google Maps provides powerful default visuals, its generic theme may not always align with your app’s branding or user experience goals. This leads to our topic of improving the user’s experience by adopting different map themes via the Google Maps Styling Wizard. Below is a working sample:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPvpo-xKCIqc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FPvpo-xKCIqc%3Ffeature%3Dshare&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPvpo-xKCIqc%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b60daba59aa8b5a42253633ce0a5965a/href">https://medium.com/media/b60daba59aa8b5a42253633ce0a5965a/href</a></iframe><h3>Project Setup</h3><p><em>P.S. I assume this article’s reader is familiar with the Flutter framework.</em> 😅<br><em>There is a public repository for the full implementation on</em> <a href="https://github.com/Captured-Heart/dynamic_map_themes"><em>GitHub</em></a> <em>to follow along.</em></p><h3>Installing 3rd-party plugins</h3><p>The first step is creating a new Flutter project. Run “flutter create &lt;DIRECTORY&gt;” in the command line,</p><pre>flutter create &lt;DIRECTORY&gt;</pre><p>and add the necessary dependencies. Below is a list of the 3rd-party plugins used in this project:</p><ol><li><a href="https://pub.dev/packages/shared_preferences">Shared_Preferences</a>: “<em>Wraps platform-specific persistent storage for simple data (NSUserDefaults on iOS and macOS, SharedPreferences on Android, etc)</em>”</li><li><a href="https://pub.dev/packages/flutter_riverpod">Flutter_Riverpod</a>: “<em>A reactive caching and data-binding framework</em>.”</li><li><a href="https://pub.dev/packages/geolocator">Geolocator</a>: “<em>A Flutter geolocation plugin that provides easy access to platform-specific location services (FusedLocationProviderClient or, if unavailable, the LocationManager on Android and CLLocationManager on iOS).</em>”</li><li><a href="https://pub.dev/packages/google_maps_flutter">Google_Maps_Flutter</a>: “<em>A Flutter plugin that provides a Google Maps widget.</em>”</li><li><a href="https://pub.dev/packages/flutter_expandable_fab">Flutter_expandable_fab</a>: “<em>A speed dial FAB (Floating Action Button) that can animate the display and hiding of multiple action buttons</em></li></ol><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  flutter_riverpod: ^2.6.1<br>  flutter_expandable_fab: ^2.4.1<br>  geolocator: ^13.0.4 # for location access<br>  shared_preferences: ^2.5.3</pre><h3>Add Google Maps Dependency</h3><p>To install Flutter Google Maps in the project, you should start by reading the documentation on pub: <a href="https://pub.dev/packages/google_maps_flutter">Google Maps Flutter</a></p><ul><li>Add the google_maps_flutter ⁣dependency on your “pubspec.yaml” file: dependencies:</li></ul><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  google_maps_flutter: ^2.12.1</pre><p>Run flutter pub get</p><p><strong>Get an API key</strong>:</p><ol><li>Go to the Google Cloud Console.</li><li>Create or select a project.</li><li>Enable the Maps SDK for Android and Maps SDK for iOS.</li><li>Create API credentials.</li><li>Copy the API key.</li></ol><p><strong>Configure Android</strong></p><ol><li>Open android/app/src/main/AndroidManifest.xml</li><li>Add the API key inside the &lt;application&gt;tag:</li></ol><pre>&lt;application<br>      android:label=&quot;Map Themes&quot;<br>      android:name=&quot;${applicationName}&quot;<br>      android:icon=&quot;@mipmap/ic_launcher&quot;&gt;<br>  // ADD API KEY AS SEEN BELOW.....<br>      &lt;meta-data android:name=&quot;com.google.android.geo.API_KEY&quot;<br>              android:value=&quot;${google.maps.api.key}&quot;/&gt;</pre><p><strong>Configure iOS</strong></p><ol><li>Open ios/Runner/AppDelegate.swift.</li><li>Add the following import:</li></ol><pre>import Flutter<br>import UIKit<br>// ---------  IMPORT GOOGLE MAPS LIBRARY<br>import GoogleMaps<br><br>@main<br>@objc class AppDelegate: FlutterAppDelegate {<br>  override func application(<br>    _ application: UIApplication,<br>    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?<br>  ) -&gt; Bool {<br>  if let path = Bundle.main.path(forResource: &quot;Info&quot;, ofType: &quot;plist&quot;),<br>   let dict = NSDictionary(contentsOfFile: path),<br> // ------ ADD GOOGLE MAPS KEY HERE AS SEEN BELOW ......... <br>     let apiKey = dict[&quot;GOOGLE_MAPS_API_KEY&quot;] as? String {<br>    GMSServices.provideAPIKey(apiKey)<br>}<br>    GeneratedPluginRegistrant.register(with: self)<br>    return super.application(application, didFinishLaunchingWithOptions: launchOptions)<br>  }<br>}</pre><p>3. Open ios/Runner/Info.plist</p><p>4. Add the following key inside the &lt;/dict&gt;tag:</p><pre>...<br>&lt;key&gt;GOOGLE_MAPS_API_KEY&lt;/key&gt;<br>    &lt;string&gt;${API_KEY}&lt;/string&gt; // insert your key here<br>&lt;/dict&gt;<br>...<br>&lt;/plist&gt;</pre><h3>Map Configurations</h3><pre>abstract class MapRepository {<br>  GoogleMapController setMapController(GoogleMapController controller);<br>  GoogleMapController? getMapController();<br>  (String, Stream&lt;Position&gt;) getLocationStream();<br>  Future&lt;(String, Position?)&gt; getCurrentLocation();<br>  Future&lt;(String, bool)&gt; locationPermissionStatus();<br>}</pre><p>This repository helps maintain clean code by centralizing and abstracting all location-related logic using Google Maps in Flutter, promoting separation of concerns and reusability.<br>In my implementation, the MapRepository handles the following responsibilities using the <a href="https://pub.dev/packages/geolocator">geolocator</a> plugin:</p><ol><li><strong>getLocationStream()</strong>: This method returns a continuous stream of location updates; I use it to update the user’s location on the map as they move.</li><li><strong>getCurrentLocation()</strong>: This method retrieves the user’s current GPS location once; I used it to get the coordinates (latitude and Longitude) of the user on the initState of the map_view</li><li><strong>locationPermissionStatus()</strong>: Before accessing location data, your app must ensure the user has granted the necessary permissions. This method checks the current permission status and optionally prompts the user if needed.</li></ol><p>P.S.: <em>Because this is a demo project, I combined the location methods above with the map methods and called it </em><em>MapRepository. In a larger project, it could be separated into </em><em>MapRepository and </em><em>LocationRepository</em></p><ul><li>Other map methods:</li></ul><p>4. <strong>setMapController(GoogleMapController controller)</strong>: This method is used to store a reference to the GoogleMapController when the map is first created. I save this controller within the repository so it can interact with the map without directly accessing the UI layer.</p><p>5. <strong>getMapController()</strong>: I use this method to retrieve the stored GoogleMapControllerinstance. This allows other classes or services to access the map controller safely and consistently.</p><p>P.S.: <em>See the project </em><em>map_repository.dartfile for MapRepository implementation.</em></p><h3>Creating the Map Provider to access the locationStream() method</h3><p>Utilizing the Riverpod StreamProviderAPI, I access the locationStream from MapRepository via ref</p><pre>// -------- IMPORT THE CLASSES<br>import &#39;package:dynamic_map_themes/repository/map_repository.dart&#39;;<br>import &#39;package:flutter_riverpod/flutter_riverpod.dart&#39;;<br>import &#39;package:geolocator/geolocator.dart&#39;;<br><br>final mapViewProvider = StreamProvider&lt;Position&gt;(<br>  (ref) {<br>    var locationStream = ref.read(mapRepositoryProvider).getLocationStream().$2;<br><br>    return locationStream.handleError((error) {<br>      // Handle the error here<br>      print(&#39;Error: $error&#39;);<br>    });<br>  },<br>);</pre><h3>Creating the map view</h3><pre>import &#39;package:dynamic_map_themes/presentation/widgets/floating_themes_btn.dart&#39;;<br>import &#39;package:dynamic_map_themes/provider/map_styles_provider.dart&#39;;<br>import &#39;package:dynamic_map_themes/provider/map_view_provider.dart&#39;;<br>import &#39;package:dynamic_map_themes/repository/map_repository.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_expandable_fab/flutter_expandable_fab.dart&#39;;<br>import &#39;package:flutter_riverpod/flutter_riverpod.dart&#39;;<br>import &#39;package:google_maps_flutter/google_maps_flutter.dart&#39;;<br><br>class MapView extends ConsumerStatefulWidget {<br>  const MapView({<br>    super.key,<br>  });<br><br>  @override<br>  ConsumerState&lt;MapView&gt; createState() =&gt; _MapViewState();<br>}<br><br>class _MapViewState extends ConsumerState&lt;MapView&gt; {<br>  @override<br>  void initState() {<br>    ref.read(mapRepositoryProvider).getCurrentLocation();<br>    super.initState();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    final mapStyles = ref.watch(mapStyleProvider).mapStyle; <br>    final mapView = ref.watch(mapViewProvider); <br>    return Scaffold(<br>      key: UniqueKey(),<br>      floatingActionButtonLocation: ExpandableFab.location,<br>      floatingActionButton: FloatingThemeBtnsWidget(),<br>      body: mapView.when(<br>        data: (data) {<br>          return GoogleMap(<br>            initialCameraPosition: CameraPosition(<br>              target: LatLng(data.latitude, data.longitude),<br>              zoom: 13,<br>            ),<br>            style: mapStyles.isEmpty == true ? null : mapStyles,<br>            myLocationButtonEnabled: false,<br>            mapType: MapType.normal,<br>            onMapCreated: (controller) {<br>              ref.read(mapRepositoryProvider).setMapController(controller);<br>            },<br>            myLocationEnabled: true,<br>          );<br>        },<br>        error: (error, stackTrace) {<br>          return const Center(<br>            child: Text(<br>              &#39;Please enable your location, and try again!&#39;,<br>              style: TextStyle(color: Colors.red),<br>            ),<br>          );<br>        },<br>        loading: () =&gt; const Center(child: CircularProgressIndicator()),<br>      ),<br>    );<br>  }<br>}</pre><ul><li>In the initState(), we can create the map view by using a stateful widget, which gives us access to the initState, a lifecycle method that is called when a state object is created. It is called only once, and it’s best for initializing our getCurrentLocation() method, which requests permission and retrieves the user&#39;s location. This is why we used ref.read; it is used to access the current value of a provider without listening to it for changes.</li><li>In the build() method, we are permitted to use the Riverpod ref.watch method that listens to changes in providers. <a href="http://ref.watch/">ref.watch</a>(mapStyleProvider).mapStyle listens to the current map style, while the</li><li><a href="http://ref.watch/">ref.watch</a>(mapViewProvider) listens to the live stream of the user’s location.</li><li>The Google Map Widgetdynamically updates:</li></ul><ol><li><strong>initialCameraPosition</strong>: uses the current coordinates from the mapViewProvider.</li><li><strong>style</strong>: uses the dynamic map style (null if not set).</li><li><strong>onMapCreated</strong>: stores the controller in the repository for later use.</li><li><strong>mapType</strong>: Google Maps provides this enum that contains four values (hybrid, satellite, normal, terrain). For this project, we would be using the normal type to access the themes JSON. The ExpandableFab renders floating buttons (defined in FloatingThemeBtnsWidget) to switch between themes dynamically.</li></ol><p><em>See the </em><em>lib/presentation/widgets/floating_themes_btn.dart in the project repository for the implementation of the custom floating action button used.</em> <em>You can also find the plugin on pub: </em><a href="https://pub.dev/packages/flutter_expandable_fab"><em>flutter_expandable_fab</em></a></p><h3>Creating the Map Styles</h3><p>We download the map styles JSON we need for the project from Google’s Styling Wizard at <a href="https://mapstyle.withgoogle.com/">mapstyle.withgoogle</a> by following these steps:</p><ul><li>Adjust the map features, colors, and elements to match your preference using the available tools.</li><li>Once satisfied with your customizations, click on the “Finish” button.</li><li>Copy the JSON and paste it inside our Flutter project assets folder</li></ul><p>Create a Provider class to manage the map styles; here, we utilize the Notifier class from the Riverpod plugin to manage the state</p><h3>Creating the Map Styles Provider</h3><pre>import &#39;package:dynamic_map_themes/core/constants/asset_images.dart&#39;;<br>import &#39;package:dynamic_map_themes/core/enums/map_enums.dart&#39;;<br>import &#39;package:dynamic_map_themes/utils/shared_pref_helper.dart&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br>import &#39;package:flutter_riverpod/flutter_riverpod.dart&#39;;<br><br>final mapStyleProvider = AsyncNotifierProvider&lt;MapStyleAsyncNotifier, MapStylesState&gt;(<br>  () =&gt; MapStyleAsyncNotifier(),<br>);<br><br>class MapStyleAsyncNotifier extends AsyncNotifier&lt;MapStylesState&gt; {<br>  @override<br>  Future&lt;MapStylesState&gt; build() async {<br>    final style = await _getSelectedMapStyle();<br>    return MapStylesState(mapStyle: style);<br>  }<br><br>  Future&lt;String&gt; _getSelectedMapStyle() async {<br>    final savedMapStyleName = SharedPreferencesHelper.getString(key: SharedKeys.mapStyle.name);<br>    final mapStyleEnum = MapStyles.styleName(savedMapStyleName ?? MapStyles.original.name);<br><br>    return switch (mapStyleEnum) {<br>      MapStyles.dark =&gt; await rootBundle.loadString(AssetImages.darkMapStylesJson),<br>      MapStyles.night =&gt; await rootBundle.loadString(AssetImages.nightMapStylesJson),<br>      MapStyles.nightBlue =&gt; await rootBundle.loadString(AssetImages.nightBlueMapStylesJson),<br>      MapStyles.retro =&gt; await rootBundle.loadString(AssetImages.retroMapStylesJson),<br>      MapStyles.original =&gt; &#39;&#39;,<br>    };<br>  }<br><br>  Future&lt;void&gt; setMapStyles(String mapStyleName) async {<br>    // Save preference<br>    await SharedPreferencesHelper.setString(<br>      key: SharedKeys.mapStyle.name,<br>      value: mapStyleName,<br>    );<br><br>    // Reload the selected style and update state<br>    final style = await _getSelectedMapStyle();<br>    state = AsyncValue.data(MapStylesState(mapStyle: style));<br>  }<br>}<br><br>class MapStylesState {<br>  final String mapStyle;<br>  final bool tapped, isOffline;<br><br>  MapStylesState({<br>    this.mapStyle = &#39;&#39;,<br>    this.tapped = false,<br>    this.isOffline = false,<br>  });<br><br>  MapStylesState copyWith({<br>    String? mapStyle,<br>    bool? tapped,<br>    bool? isOffline,<br>  }) {<br>    return MapStylesState(<br>      mapStyle: mapStyle ?? this.mapStyle,<br>      isOffline: isOffline ?? this.isOffline,<br>      tapped: tapped ?? this.tapped,<br>    );<br>  }<br>}</pre><ul><li><strong>getSelectedMapStyle()</strong>: This method checks for a saved map style in shared preferences, converts it to a MapStyles enum using a static method, then uses a switch expression to load the corresponding style JSON file.</li><li><strong>setMapStyles()</strong>: This method is triggered by the FloatingActionButton to choose a map style and update the state accordingly.</li></ul><p><strong>AsynNotifier</strong>: Riverpod provides multiple state management APIs, such as Notifier, AsyncNotifier, and StateNotifier, each is suited for different use cases. In this case, we use AsyncNotifier because getSelectedMapStyle() returns a Future&lt;String&gt;, and AsyncNotifier is designed to handle asynchronous state by exposing an AsyncValue&lt;T&gt; and supporting build() methods that can be async.</p><p><strong>This is how I defined the MapStyles Enum</strong></p><pre>enum MapStyles {<br>  original,<br>  dark,<br>  night,<br>  nightBlue,<br>  retro;<br><br>  static MapStyles styleName(String name) {<br>    return MapStyles.values.firstWhere(<br>      (e) =&gt; e.name == name,<br>      orElse: () =&gt; MapStyles.original,<br>    );<br>  }<br>}</pre><p><strong>This is how I declare my assets path.</strong></p><pre>class AssetImages {<br>  static const String offlineMapStylesJson = &#39;assets/json/offline_map_style.json&#39;; //<br>  static const String darkMapStylesJson = &#39;assets/json/dark_map_style.json&#39;; //<br>  static const String nightMapStylesJson = &#39;assets/json/night_map_style.json&#39;; //<br>  static const String retroMapStylesJson = &#39;assets/json/retro_map_style.json&#39;; //<br>  static const String nightBlueMapStylesJson = &#39;assets/json/night_blue_map_style.json&#39;; //<br>}</pre><h3>Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*vfZX_LagIPtVO8krlghYOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*2jfMOxdCt0kSEYkH5gmJ0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*CoUDa9_Sk7yuon3jH10Y1g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*F7PSg5p86ji5kAOVc7T4vg.png" /></figure><h3>Conclusion</h3><blockquote>This article provides a comprehensive guide to setting up a Flutter project with Google Maps integration, highlighting essential steps such as creating a new Flutter project, installing third-party plugins like Shared_Preferences, Flutter_Riverpod, Geolocator, and Google_Maps_Flutter, and configuring Android and iOS platforms for map functionality.</blockquote><blockquote>We see that integrating dynamic Google Map themes into your Flutter app with Riverpod is more than just a design enhancement — it’s a powerful way to deliver a seamless, user-centric experience, and Riverpod reactive architecture makes it easy to manage state and update the themes in real time.</blockquote><blockquote>👉 Ready to get started? Check out the full implementation on <a href="https://github.com/Captured-Heart/dynamic_map_themes">GitHub</a> and bring your maps to life!</blockquote><h3>References</h3><p><a href="https://github.com/Captured-Heart/dynamic_map_themes">Dynamic Map Themes Github Repository</a></p><p><a href="https://pub.dev/packages/flutter_riverpod">Flutter_Riverpod (pub.dev)</a></p><p><a href="https://pub.dev/packages/flutter_expandable_fab">Flutter_Expandable_Fab Plugin (pub.dev)</a></p><p><a href="https://pub.dev/packages/shared_preferences">Shared_Preferences (pub.dev)</a></p><p><a href="https://pub.dev/packages/geolocator">Geolocator (pub.dev)</a></p><p><a href="https://pub.dev/packages/google_maps_flutter">Google_Maps_Flutter (pub.dev)</a></p><p><a href="https://mapstyle.withgoogle.com/">Google map style (map style wizard)</a></p><p><a href="https://riverpod.dev/docs/introduction/getting_started">Riverpod Official Docs</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3d509ca1e1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>