<?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 Haydar Demir on Medium]]></title>
        <description><![CDATA[Stories by Haydar Demir on Medium]]></description>
        <link>https://medium.com/@birhos?source=rss-f0e1d1f2148a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yn4yJWgZbqyVncJQ8G5VFQ.jpeg</url>
            <title>Stories by Haydar Demir on Medium</title>
            <link>https://medium.com/@birhos?source=rss-f0e1d1f2148a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 22:32:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@birhos/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[Mastering Form Validation in Flutter]]></title>
            <link>https://medium.com/@birhos/mastering-form-validation-in-flutter-edcfc38b96ad?source=rss-f0e1d1f2148a------2</link>
            <guid isPermaLink="false">https://medium.com/p/edcfc38b96ad</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[super-app-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[form-validation]]></category>
            <dc:creator><![CDATA[Haydar Demir]]></dc:creator>
            <pubDate>Thu, 26 Jun 2025 05:09:11 GMT</pubDate>
            <atom:updated>2025-06-26T05:09:11.537Z</atom:updated>
            <content:encoded><![CDATA[<p>Tired of writing a separate validator for every form field? The solution is just a few lines away!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-x3Zl0VGFHPdiLeue-UmxA.png" /><figcaption>Created by ChatGPT</figcaption></figure><p>Hello Everyone</p><p>Collecting user input in mobile applications is one of the most common requirements we encounter in almost every project. To handle this need, we often rely on form elements. In Flutter, when we talk about forms, components like TextFormField and DatePicker usually come to mind. However, one of the most critical aspects of form fields is the validation process. Typically, developers use inline or static functions assigned to the validator parameter.</p><p>But what if we could build a more modular, testable, and OOP-friendly structure instead of writing similar validation logic repeatedly for every screen and field?</p><p>In this article, I&#39;ll walk you through how to build a custom form validation architecture in Flutter, how to manage different validators under a unified system, and how to make this structure easily extensible. Let’s dive in!</p><h3>🧱 Basic Implementation</h3><p>Getting started with form validation in Flutter is fairly straightforward. The TextFormField widget provides a validator parameter, which accepts a function that can return an error message when the input is invalid.</p><p>Below is a simple example of email validation. It prompts the user to enter an email address and checks for both emptiness and valid format:</p><pre>TextFormField(<br>  decoration: InputDecoration(<br>    labelText: &#39;Email&#39;,<br>  ),<br>  validator: (value) {<br>    if (value == null || value.isEmpty) {<br>      return &#39;Please enter an email address&#39;;<br>    }<br>    if (!isValidEmail(value)) {<br>      return &#39;Please enter a valid email address&#39;;<br>    }<br>    return null; // Return null for no validation errors<br>  },<br>)</pre><p>Here, two basic checks are performed:</p><ul><li>Is the input empty? → If so, an error message like ‘Please enter an email address’ is shown.</li><li>Is the email format valid? → If not, a second error message is returned.</li></ul><p>This approach may be sufficient for small projects. However, in larger and scalable applications where multiple TextFormFields are used, writing individual validator functions like this for each field leads to code duplication and makes maintenance more difficult.</p><h3>🚀 Advanced Form Validation</h3><p><strong>AppValidator</strong></p><p>Below, you can see the AppValidator class and its related structures, which lay the foundation for a customizable and extensible form validation system:</p><pre>final class AppValidator {<br>  AppValidator._();<br><br>  /// Applies all validation rules in the [validations] list sequentially.<br>  /// If any validation returns an error, that error message is displayed.<br>  static FormFieldValidator&lt;T&gt; apply&lt;T&gt;(<br>    BuildContext context,<br>    List&lt;AppValidation&lt;T&gt;&gt; validations,<br>  ) {<br>    return (T? value) {<br>      for (final validation in validations) {<br>        final error = validation.validate(context, value);<br>        if (error != null) return error;<br>      }<br>      return null; // Returns null if there&#39;s no error, meaning the validation was successful.<br>    };<br>  }<br>}</pre><p>Thanks to this structure, adding a validator to a TextFormField becomes much cleaner. All you need to do is define the rules by implementing the AppValidation interface and pass them to the AppValidator.apply function.</p><p>For example, you can define a helper extension like the one below to display all validation messages in a consistent format:</p><pre>extension FormStringExtension on String {<br>  String get xGetFormString =&gt; &#39;* $this&#39;;<br>}</pre><p><strong>AppValidation Interface</strong></p><p>Each validation rule should extend the AppValidation abstract class. This class is defined as follows:</p><pre>abstract class AppValidation&lt;T&gt; {<br>  /// Validates the given [value].<br>  /// Returns an error message if the validation fails.<br>  /// Returns `null` if the validation succeeds.<br>  String? validate(BuildContext context, T? value);<br>}</pre><p>With this architecture, you can define custom rules such as RequiredValidation, EmailValidation, or PasswordConfirmValidation, and reuse them across different fields as needed.</p><p>Here are the advantages of this structure:</p><ul><li><strong>Reusability:</strong> The same validation rule can be used across multiple form fields.</li><li><strong>Extensibility:</strong> New validation rules can be added easily.</li><li><strong>Testability:</strong> Each validator can be tested independently.</li><li><strong>Readability:</strong> Form fields become cleaner as validation logic is separated.</li></ul><h3>🧪 Example</h3><p>Now, let’s take a look at some example validator classes that demonstrate how the AppValidation structure we defined earlier can be implemented in practice. These classes highlight how simple it is to build a readable and reusable validator architecture.</p><p><strong>EmptyValidation</strong></p><p>This class checks whether a field is empty. A custom error message can be provided via the message parameter; if not provided, a default translated message is used.</p><pre>final class EmptyValidation extends AppValidation&lt;String&gt; {<br>  EmptyValidation({<br>    this.message,<br>  });<br>  final String? message;<br><br>  @override<br>  String? validate(BuildContext context, String? value) {<br>    if (value != null) {<br>      if (value.trim().isEmpty) {<br>        return message ?? AppTranslations.formValidation.validation.xGetFormString;<br>      }<br>    } else {<br>      return message ?? AppTranslations.formValidation.validation.xGetFormString;<br>    }<br>    return null;<br>  }<br>}</pre><blockquote>This class can be used as a basic validator for any type of TextFormField.</blockquote><p><strong>EmailValidation</strong></p><p>Email validation is a common requirement in almost every project. The EmailValidation class only returns an error if the email field is not empty and the format is invalid.</p><pre>final class EmailValidation extends AppValidation&lt;String&gt; {<br>  EmailValidation();<br><br>  @override<br>  String? validate(BuildContext context, String? value) {<br>    if (value == null || value.isEmpty) return null;<br><br>    if (!App.regexp.email.hasMatch(value)) {<br>      return AppTranslations.formValidation.invalidMail.xGetFormString;<br>    } else {<br>      return null;<br>    }<br>  }<br>}</pre><blockquote>Note: The email format is validated using App.regexp.email. If the field is empty, no error message is returned—this responsibility is delegated to EmptyValidation.</blockquote><p><strong>PasswordConfirmValidation</strong></p><p>This class checks whether the entered password matches the confirm password field. The original password is passed as a parameter, and the comparison is made against that value.</p><pre>final class PasswordConfirmValidation extends AppValidation&lt;String&gt; {<br>  PasswordConfirmValidation({required this.password});<br>  final String password;<br><br>  @override<br>  String? validate(BuildContext context, String? value) {<br>    if (value == null || value.isEmpty) return null;<br><br>    if (password.trim() != value.trim()) {<br>      return AppTranslations.formValidation.passwordsNotMatch.xGetFormString;<br>    } else {<br>      return null;<br>    }<br>  }<br>}</pre><blockquote>This validator is typically used in fields like ‘Confirm Password’ and works in conjunction with the main password field.</blockquote><p><strong>EmailFormField</strong></p><pre>final class EmailFormField extends StatelessWidget {<br>  const EmailFormField({<br>    super.key,<br>    required this.controller,<br>    this.labelText = &#39;Email&#39;,<br>  });<br>  final TextEditingController controller;<br>  final String labelText;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return TextFormField(<br>      controller: controller,<br>      decoration: InputDecoration(<br>        labelText: labelText,<br>      ),<br>      keyboardType: TextInputType.emailAddress,<br>      autofillHints: const [AutofillHints.email],<br>      validator: AppValidator.apply&lt;String&gt;(<br>        context,<br>        [<br>          EmptyValidation(),<br>          EmailValidation(),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p><strong>Usage</strong>:</p><p>You can easily use it like this within a form:</p><pre>final emailController = TextEditingController();<br><br>Form(<br>  key: _formKey,<br>  child: Column(<br>    children: [<br>      EmailFormField(controller: emailController),<br>      ElevatedButton(<br>        onPressed: () {<br>          if (_formKey.currentState?.validate() ?? false) {<br>            // Valid email input<br>          }<br>        },<br>        child: const Text(&#39;Submit&#39;),<br>      ),<br>    ],<br>  ),<br>);</pre><h3>Conclusion</h3><p>Thanks to the structure we walked through in this article, you don’t have to write separate validators for every single form field anymore. You can manage all your common validation rules in one place and easily add new ones as needed. Plus, it’s super easy to grow this setup together with your team.</p><p>Remember clean code doesn’t just make your life easier as a developer, it also keeps your app easier to maintain in the long run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E5HUwhF8fcG7EnK5DvtHTg.png" /><figcaption>Created by ChatGPT</figcaption></figure><blockquote>I hope this is helpful to you. :) Don’t forget to follow me, your support and feedback are very important to me, thank you.</blockquote><blockquote>LinkedIn: <a href="https://www.linkedin.com/in/haydardemir/">https://www.linkedin.com/in/haydardemir/</a><br>GitHub: <a href="https://github.com/birhos?tab=repositories">https://github.com/birhos</a></blockquote><blockquote>Enjoy your coding!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edcfc38b96ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Scalable WebSocket Client in Flutter]]></title>
            <link>https://medium.com/@birhos/building-a-scalable-websocket-client-in-flutter-f7a78c4166c5?source=rss-f0e1d1f2148a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7a78c4166c5</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Haydar Demir]]></dc:creator>
            <pubDate>Mon, 26 May 2025 05:15:37 GMT</pubDate>
            <atom:updated>2025-05-26T05:15:37.691Z</atom:updated>
            <content:encoded><![CDATA[<p>Managing real-time message traffic without losing your mind — and reusing your code while you’re at it? Let’s dive in together!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JA60zUe_mGFmNlbP9SwaqQ.png" /><figcaption>Created by ChatGPT</figcaption></figure><p>If you want to implement features like chat, live scores, instant notifications, or real-time data updates in your mobile app, it’s much more efficient to maintain a persistent connection with the server instead of requesting data repeatedly every second. This is exactly what <strong>WebSocket</strong> enables.</p><p>WebSocket is a persistent, bidirectional communication channel established between the phone (client) and the server (backend). Once this connection is established, the app can both receive messages from the server and send messages to it — just like a real phone line.</p><p>In traditional methods, the app repeatedly contacts the server for every new piece of information (a technique known as “polling”). With WebSocket, however, the connection is already open, so data is delivered instantly — without any waiting.</p><h3>Use Cases for WebSocket</h3><p>WebSocket is especially ideal for the following scenarios:</p><ul><li><strong>Chat applications:</strong> New messages are delivered to the other party instantly.</li><li><strong>Live scores:</strong> Real-time score updates in sports apps are displayed without delay.</li><li><strong>Real-time notifications:</strong> Important events are instantly delivered to the user.</li><li><strong>Games or live data dashboards:</strong> Continuously updating data is transmitted quickly and without interruption.</li></ul><h3>How It Works</h3><ol><li>When the app launches or the user logs in, a connection to the server is established using the WebSocketChannel.connect() method. At this point, a persistent channel is created for continuously sending and receiving data.</li><li>After the connection is established, the app authenticates itself by sending an access token (e.g., JWT) to the backend server. This ensures that only authorized users can maintain the connection.</li><li>Once the connection is established, data can flow in real time both from the client to the server and from the server to the client.</li><li>Each incoming message is routed to its handler based on its type (SocketMessageTypes). This way, only the relevant screen or module (e.g., ChatCubit) responds to the message.</li><li>To prevent long-lived connections from being dropped, a “heartbeat” message is sent to the server at regular intervals. This lets the server know that the client is still active.</li><li>If the connection is lost for any reason: the onClose() method is triggered, all handlers are notified, and the heartbeat is stopped.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6fwCOB6zjLAytnuCHbNoYQ.png" /><figcaption>Created by ChatGPT</figcaption></figure><h3>Installation</h3><p>To use WebSocket communication in Flutter, you need to add the <a href="https://pub.dev/packages/web_socket_channel">web_socket_channel</a> package to your project. After adding this package to your pubspec.yaml file and running the flutter pub get command, you can start using it.</p><pre>dependencies:<br>  web_socket_channel: [latest_version]</pre><h3>SocketMessageTypes</h3><p>SocketMessageTypes enum defines the types of messages sent or received over the WebSocket. Each message type is associated with a unique rawValue (an integer), allowing us to easily identify what kind of action the incoming message from the server represents.</p><pre>enum SocketMessageTypes {<br>  heartbeat(1),<br>  authenticate(2),<br>  newChatMessage(3);<br><br>  const SocketMessageTypes(this.rawValue);<br>  final int rawValue;<br><br>  static SocketMessageTypes? fromRawValue(int? rawValue) =&gt; rawValue != null ? values.firstWhereOrNull((e) =&gt; e.rawValue == rawValue) : null;<br>}</pre><h3>SocketMessage</h3><p>SocketMessage class represents the data model for all messages sent and received over the WebSocket. It is built using freezed and json_serializable.</p><pre>@freezed<br>abstract class SocketMessage with _$SocketMessage {<br>  const factory SocketMessage({<br>    @JsonKey(name: &#39;messageType&#39;) int? messageType,<br>    @JsonKey(name: &#39;payload&#39;) Map&lt;String, dynamic&gt;? payload,<br>  }) = _SocketMessage;<br><br>  const SocketMessage._();<br><br>  factory SocketMessage.fromJson(Map&lt;String, dynamic&gt; json) =&gt; _$SocketMessageFromJson(json);<br>  factory SocketMessage.heartbeat() =&gt; SocketMessage(messageType: SocketMessageTypes.heartbeat.rawValue, payload: {&#39;timestamp&#39;: DateTime.now().toIso8601String()});<br>  factory SocketMessage.authenticate({required String accessToken}) =&gt; SocketMessage(messageType: SocketMessageTypes.authenticate.rawValue, payload: {&#39;accessToken&#39;: accessToken});<br><br>  static SocketMessage? fromDynamic(dynamic value) {<br>    try {<br>      if (value case final String value) {<br>        return SocketMessage.fromJson(jsonDecode(value) as Map&lt;String, dynamic&gt;);<br>      }<br>      if (value case final Map&lt;String, dynamic&gt; value) {<br>        return SocketMessage.fromJson(value);<br>      }<br>      return null;<br>    } catch (e) {<br>      return null;<br>    }<br>  }<br><br>  String toMessage() =&gt; jsonEncode({<br>        &#39;messageType&#39;: messageType,<br>        &#39;payload&#39;: payload,<br>      });<br>}</pre><h3>SocketMessageHandler</h3><p>The SocketMessageHandler class is an abstract structure designed to handle WebSocket messages of a specific SocketMessageTypes type. Each handler is identified by an id and made comparable using Equatable.</p><pre>abstract class SocketMessageHandler extends Equatable {<br>  const SocketMessageHandler({required this.id});<br>  final String id;<br><br>  SocketMessageTypes get messageType;<br>  void onMessage(Map&lt;String, dynamic&gt; data);<br>  void onClose();<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [id];<br>}</pre><h3>SocketClientListener</h3><p>The SocketClientListener class is used to listen to lifecycle events of the WebSocket connection.</p><pre>final class SocketClientListener {<br>  SocketClientListener({<br>    required this.onOpen,<br>    required this.onClose,<br>    required this.onError,<br>  });<br>  final void Function() onOpen;<br>  final void Function() onClose;<br>  final void Function(Object error) onError;<br>}</pre><h3>SocketClient</h3><p>The SocketClient provides an abstract structure that enables the app to communicate over WebSocket. Thanks to this interface, different parts of the app can interact with the WebSocket without needing to know the details of the actual implementation.</p><pre>abstract interface class SocketClient {<br>  factory SocketClient.instance() =&gt; _SocketClientImpl();<br><br>  bool get isConnected;<br>  void setListener(SocketClientListener listener);<br>  Future&lt;void&gt; connect();<br>  void disconnect();<br>  Future&lt;void&gt; emit(SocketMessageTypes event, Map&lt;String, dynamic&gt; data, void Function(Object error)? onError);<br>  void addHandler(SocketMessageHandler handler);<br>  void removeHandler(SocketMessageHandler handler);<br>  void removeAllHandlers();<br>  void notifyHandlers(SocketMessageTypes event, Map&lt;String, dynamic&gt; data);<br>  void notifyHandlersOnClose();<br>}</pre><h3>SocketClientImpl</h3><p>This class is the concrete implementation of the SocketClient interface. It handles the actual connection, message sending, listening, and handler management.</p><pre>final class _SocketClientImpl implements SocketClient {<br>  _SocketClientImpl({required this.socketUrl});<br>  final String socketUrl;<br><br>  final _messageHandlers = &lt;SocketMessageTypes, List&lt;SocketMessageHandler&gt;&gt;{};<br>  final _heartbeatInterval = const Duration(minutes: 1);<br><br>  StreamSubscription&lt;dynamic&gt;? _channelSubscription;<br>  SocketClientListener? _listener;<br>  WebSocketChannel? _channel;<br>  Timer? _heartbeatTimer;<br><br>  String get _accessToken =&gt; App.getAccessToken() ?? &#39;&#39;;<br><br>  @override<br>  bool isConnected = false;<br><br>  ...</pre><p><strong>setListener</strong></p><p>Allows assigning a listener to handle WebSocket-related events such as connection opened, closed, or an error occurred.</p><pre>@override<br>void setListener(SocketClientListener listener) {<br>  _listener = listener;<br>}</pre><p><strong>connect</strong></p><p>Initiates the WebSocket connection. If a previous connection exists, it is closed first. Then, a new connection is established using WebSocketChannel.connect. Once ready, it starts listening and sends the token for authentication.</p><pre>@override<br>Future&lt;void&gt; connect() async {<br>  try {<br>    if (_channel != null &amp;&amp; _channel!.closeCode == null) {<br>      _listener?.onOpen();<br>      return;<br>    }<br><br>    if (_channel != null) {<br>      unawaited(_channel!.sink.close());<br>    }<br><br>    _channel = WebSocketChannel.connect(Uri.parse(socketUrl));<br>    await _channel?.ready;<br>    _startListeningChannel();<br>    _sendAuthenticationMessage();<br>  } catch (e) {<br>    isConnected = false;<br>    _listener?.onError(e);<br>  }<br>}</pre><p><strong>disconnect</strong></p><p>Closes the connection by cleaning up all resources, and cancels both the heartbeat and the stream subscription.</p><pre>@override<br>void disconnect() {<br>  _channel?.sink.close();<br>  _channel = null;<br>  isConnected = false;<br>  _stopHeartbeat();<br>  _heartbeatTimer = null;<br>  _channelSubscription?.cancel();<br>  _channelSubscription = null;<br>}</pre><p><strong>emit</strong></p><p>Sends data for a specific SocketMessageTypes. If there is no active WebSocket connection, it throws an error. The message is sent as a SocketMessage object using sink.add().</p><pre>@override<br>Future&lt;void&gt; emit(<br>  SocketMessageTypes event,<br>  Map&lt;String, dynamic&gt; data,<br>  void Function(Object error)? onError,<br>) async {<br>  try {<br>    if (!isConnected) {<br>      throw Exception(&#39;WebSocket is not connected&#39;);<br>    }<br><br>    final message = SocketMessage(<br>      messageType: event.rawValue,<br>      payload: data,<br>    );<br><br>    _channel?.sink.add(message.toMessage());<br>  } catch (e, stackTrace) {<br>    AppLogger.e(&#39;SocketClient-emit() : Error: $e | stackTrace: $stackTrace&#39;);<br>    onError?.call(e);<br>  }<br>}</pre><p><strong>addHandler</strong></p><p>Adds a handler to process incoming messages. Multiple handlers of the same type are supported.</p><pre>@override<br>void addHandler(SocketMessageHandler handler) {<br>  _messageHandlers.putIfAbsent(handler.messageType, () =&gt; []).add(handler);<br>}</pre><p><strong>removeHandler</strong></p><p>Removes a handler with a specific id from the list of handlers for a given message type.</p><pre>@override<br>void removeHandler(SocketMessageHandler handler) {<br>  final handlers = _messageHandlers[handler.messageType];<br>  if (handlers == null) return;<br><br>  handlers.removeWhere((element) =&gt; element.id == handler.id);<br><br>  if (handlers.isEmpty) {<br>    _messageHandlers.remove(handler.messageType);<br>  }<br>}</pre><p><strong>removeAllHandlers</strong></p><p>Clears all event-type → handler mappings.</p><pre>@override<br>void removeAllHandlers() {<br>  _messageHandlers.clear();<br>}</pre><p><strong>notifyHandlers</strong></p><p>Triggers the relevant handlers when a specific event is received. This method dispatches the incoming message to the appropriate handlers based on its SocketMessageTypes.</p><pre>@override<br>void notifyHandlers(SocketMessageTypes event, Map&lt;String, dynamic&gt; data) {<br>  final handlers = _messageHandlers[event];<br>  if (handlers == null) return;<br><br>  for (final handler in handlers) {<br>    handler.onMessage(data);<br>  }<br>}</pre><p><strong>notifyHandlersOnClose</strong></p><p>Calls onClose() on all handlers when the connection is closed. For example, this can be used to show a &quot;Connection lost&quot; warning to the user.</p><pre>@override<br>void notifyHandlersOnClose() {<br>  for (final handlers in _messageHandlers.values) {<br>    for (final handler in handlers) {<br>      handler.onClose();<br>    }<br>  }<br>}</pre><p><strong>Private Methods</strong></p><pre>// After the channel is established, it sends the token to authenticate the session. Then, the connection status is set to `true` and `onOpen()` is called on the listener.<br>void _sendAuthenticationMessage() {<br>  try {<br>    _channel?.sink.add(SocketMessage.authenticate(accessToken: _accessToken).toMessage());<br>    _listener?.onOpen();<br>    isConnected = true;<br>  } catch (e) {<br>    _listener?.onError(e);<br>  }<br>}<br><br>// Starts listening to the WebSocket channel. The heartbeat is also initiated at this point.<br>void _startListeningChannel() {<br>  _channelSubscription = _channel!.stream.listen(<br>    _handleChannelData,<br>    onDone: _handleChannelDone,<br>    onError: _handleChannelError,<br>  );<br>  _startHeartbeat();<br>}<br><br>// Parses the incoming message and triggers the relevant handlers.<br>void _handleChannelData(dynamic message) {<br>  try {<br>    AppLogger.i(&#39;SocketClient-_handleChannelData() : Message: $message&#39;);<br>    final socketMessage = SocketMessage.fromDynamic(message);<br>    if (socketMessage == null) return;<br>    final event = SocketMessageTypes.fromRawValue(socketMessage.messageType);<br>    if (event == null) return;<br>    final payload = socketMessage.payload ?? {};<br>    notifyHandlers(event, payload);<br>  } catch (e) {<br>    AppLogger.e(&#39;SocketClient-_handleChannelData() : Error: $e&#39;);<br>  }<br>}<br><br>// When the connection is closed, `onClose()` is called on all handlers and the heartbeat is stopped.<br>void _handleChannelDone() {<br>  _listener?.onClose();<br>  notifyHandlersOnClose();<br>  _stopHeartbeat();<br>}<br><br>// In case of an error, the listener is notified via `onError()`, and the heartbeat is stopped.<br>void _handleChannelError(Object error) {<br>  _listener?.onError(error);<br>  _stopHeartbeat();<br>}<br><br>// To keep the connection alive, a heartbeat (e.g., a &quot;ping&quot;) is sent to the server at regular intervals.<br>void _startHeartbeat() {<br>  _stopHeartbeat();<br>  _heartbeatTimer = Timer.periodic(<br>    _heartbeatInterval,<br>    (timer) {<br>      _channel?.sink.add(SocketMessage.heartbeat().toMessage());<br>    },<br>  );<br>}<br><br>// When the connection is closed, this timer is stopped.<br>void _stopHeartbeat() {<br>  _heartbeatTimer?.cancel();<br>}</pre><h3>Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mn9XAxJfuaQqVkUQMJwuKQ.png" /><figcaption>Created by ChatGPT</figcaption></figure><p>Below is a sample code block demonstrating how to use the SocketClient architecture with a real chat message example:</p><pre>// 1. An instance of `SocketClient` is being created.<br>final socketClient = SocketClient.instance();<br><br>// 2. Assigning a listener: Monitoring connection status.<br>socketClient.setListener(<br>  SocketClientListener(<br>    onOpen: () =&gt; AppLogger.i(&#39;Connection opened.&#39;),<br>    onClose: () =&gt; AppLogger.i(&#39;Connection closed.&#39;),<br>    onError: (error) =&gt; AppLogger.e(&#39;An error occurred: $error&#39;),<br>  ),<br>);<br><br>// 3. Starting the WebSocket connection.<br>await socketClient.connect();<br><br>// 4. Adding a handler to listen for chat messages.<br>socketClient.addHandler(ChatMessageHandler());<br><br>// 5. Example of sending a chat message.<br>await socketClient.emit(<br>  SocketMessageTypes.newChatMessage,<br>  {<br>    &#39;sender&#39;: &#39;Haydar&#39;,<br>    &#39;text&#39;: &quot;Hello, I&#39;m sending a message via WebSocket!&quot;,<br>    &#39;timestamp&#39;: DateTime.now().toIso8601String(),<br>  },<br>  (error) =&gt; AppLogger.e(&#39;Send error: $error&#39;),<br>);</pre><p>You can create a separate handler class for each message type. For example, a custom handler for newChatMessage:</p><pre>final class ChatMessageHandler extends SocketMessageHandler {<br>  const ChatMessageHandler() : super(id: &#39;chat-handler&#39;);<br><br>  @override<br>  SocketMessageTypes get messageType =&gt; SocketMessageTypes.newChatMessage;<br><br>  @override<br>  void onMessage(Map&lt;String, dynamic&gt; data) {<br>    AppLogger.i(&#39;New message: ${data[&#39;text&#39;]} (Sender: ${data[&#39;sender&#39;]})&#39;);<br>  }<br><br>  @override<br>  void onClose() {<br>    AppLogger.i(&#39;Chat handler: connection closed.&#39;);<br>  }<br>}</pre><h3>Conclusion</h3><p>In this article, we took a detailed look at the modular and scalable WebSocket architecture I use in my Flutter projects. With the SocketClient interface, we abstracted all WebSocket operations from the outside world, while the _SocketClientImpl class handled connection management, authentication, message sending and receiving, handler management, and the heartbeat mechanism.</p><p>WebSocket has become an essential requirement for all mobile applications that rely on real-time features. Whether you’re building a small-scale chat app or a large-scale live data system, this architecture can be easily adapted to suit your needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Bece0_zQqElxE09iftYWA.png" /><figcaption>Created by ChatGPT</figcaption></figure><blockquote>I hope this is helpful to you. :) Don’t forget to follow me, your support and feedback are very important to me, thank you.</blockquote><blockquote>LinkedIn: <a href="https://www.linkedin.com/in/haydardemir/">https://www.linkedin.com/in/haydardemir/</a><br>GitHub: <a href="https://github.com/birhos?tab=repositories">https://github.com/birhos</a></blockquote><blockquote>Enjoy your coding!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7a78c4166c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering In-App Communication with Event Bus]]></title>
            <link>https://medium.com/@birhos/mastering-in-app-communication-with-event-bus-97409a0df199?source=rss-f0e1d1f2148a------2</link>
            <guid isPermaLink="false">https://medium.com/p/97409a0df199</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Haydar Demir]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 06:03:54 GMT</pubDate>
            <atom:updated>2025-04-26T06:10:32.850Z</atom:updated>
            <content:encoded><![CDATA[<p>How to build an event bus for communication in a micro frontend architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EK-CekKluK-l7v91lt45dw.jpeg" /><figcaption>Created by Grok</figcaption></figure><p>Communication in micro frontends is a challenging problem, just like it is in backend systems that use microservices. By using an event bus with a publish-subscribe model, we can enable communication between applications (modules or pages) without establishing direct connections.</p><p>We can also incorporate the <strong>fire-and-forget</strong> principle into this communication model. This principle means that once an application publishes an event, it doesn’t concern itself with whether or not the event is handled by other applications. The publisher does not expect any feedback about the successful receipt or processing of the event. This improves the performance of the publishing application and prevents potential delays caused by communication errors.<br>Event Bus can be used for communication between pages, in-app modules, or even between micro apps.</p><h4>How?</h4><p>A simple micro frontend event bus typically consists of the following core components:</p><ul><li><strong>Central Event Manager:</strong> This is a central object or module responsible for publishing events and distributing them to subscribers. It is typically exposed as a singleton instance that can be accessed by all micro frontends.</li><li><strong>Publish Mechanism:</strong> A function that allows micro frontends to emit events with a specific event name (e.g., &quot;user-logged-in&quot;, &quot;product-added-to-cart&quot;) and optional data. This mechanism enables micro frontends to notify others about certain actions or changes.</li><li><strong>Subscribe Mechanism:</strong> A function that allows micro frontends to subscribe to specific event types. When a micro frontend subscribes to an event, it is notified via a callback function whenever that event is published.</li><li><strong>Unsubscribe Mechanism (Optional):</strong> A function that allows micro frontends to cancel their subscriptions to event types they are no longer interested in. This helps prevent unnecessary notifications and improves performance.</li></ul><h4>Why?</h4><p>There are several important reasons to use a simple event bus in a micro frontend architecture:</p><ul><li><strong>Loose Coupling:</strong> One of the most important reasons. Instead of communicating with each other directly, micro frontends communicate indirectly through events. This reduces the likelihood that a change in one micro frontend will directly impact others, making it easier to develop and deploy them independently.</li><li><strong>Scalability:</strong> Since micro frontends are independent, each one can be scaled individually as needed. The event bus helps maintain this independence and contributes to the overall scalability of the system.</li><li><strong>Reusability:</strong> An event published by one micro frontend can be listened to and used by multiple other micro frontends. This reduces code duplication and makes it easier to integrate different features.</li><li><strong>Technology Diversity:</strong> Different micro frontends can be developed using different technologies. The event bus abstracts the communication between them, allowing these heterogeneous technologies to work together seamlessly.</li><li><strong>Team Autonomy:</strong> Different teams can work independently on their own micro frontends. The event bus reduces the need for coordination between teams, enabling them to work faster and more efficiently.</li></ul><h4>How It Works</h4><ol><li>A specific event occurs in a micro frontend (e.g., a user clicks a button).</li><li>This micro frontend uses the publish mechanism of the event manager to emit the event, along with its name and relevant data.</li><li>The event manager identifies all micro frontends that have subscribed to this event.</li><li>The event manager invokes the registered callback functions of each subscribed micro frontend, passing the event data.</li><li>The subscribed micro frontends can then update their internal state or perform other actions based on the received event information.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7rgBoHHaPvZgBK_AebHww.png" /><figcaption>Created by ChatGPT</figcaption></figure><h4>Installation</h4><p>To use event bus in Flutter, you need to add the <a href="https://pub.dev/packages/event_bus_plus">event_bus_plus</a> package to your project. After adding this package to your pubspec.yaml file and running the flutter pub get command, you can start using it.</p><pre>dependencies:<br>  event_bus_plus: [latest_version]</pre><h4>AppEventBus</h4><p>It is a globally accessible singleton Event Bus manager within the application. It contains dedicated Handler classes that listen to and manage different types of CustomEvents. Each Handler encapsulates and manages the Event Bus communication for a specific module or feature. This structure serves as a central event manager to enable loosely coupled communication between modules.</p><pre>final IEventBus _eventBus = EventBus();<br><br>final class AppEventBus {<br>  AppEventBus._();<br><br>  static final AppEventBus instance = AppEventBus._();<br><br>  final forceUpdate = ForceUpdateBusHandler(_eventBus);<br>  ...<br>}</pre><h4>EventBusHandler</h4><p>This class is a generic base class used by all custom Event Bus handlers. T represents the event type that extends from the AppEvent class. Each EventBusHandler instance encapsulates the listen and fire operations for its own event type T.</p><p>This structure is primarily designed for one-to-one communication scenarios (where a single event is handled by a single listener). However, it can also be used in one-to-many communication scenarios (where an event is listened to by multiple different processes). To achieve this, it is sufficient to override the listen function in the subclasses.</p><pre>base class EventBusHandler&lt;T extends AppEvent&gt; {<br>  EventBusHandler(IEventBus eventBus) : _eventBus = eventBus;<br><br>  final IEventBus _eventBus;<br>  StreamSubscription&lt;T&gt;? _subscription;<br><br>  void fire(T event) =&gt; _eventBus.fire(event);<br><br>  void listen(void Function(T)? onData) {<br>    cancel();<br>    _subscription = _eventBus.on&lt;T&gt;().listen(onData);<br>  }<br><br>  void cancel() {<br>    _subscription?.cancel();<br>  }<br>}</pre><h4>Example: ForceUpdateBusHandler</h4><p>This class, EventBusHandler, manages the event triggered when the user is required to update the app. It works in conjunction with the ForceUpdateEvent and ensures that an update prompt is shown to the user.</p><p>The ForceUpdateEvent is fired with the information about the new version of the app that needs to be updated. This event should be triggered at the appropriate time based on the app&#39;s business logic — for example, as a result of a Firebase Remote Config check or an API call.</p><p>This structure helps decouple the UI layer from the business logic, making the update prompt mechanism modular and reusable.</p><pre>final class ForceUpdateBusHandler extends EventBusHandler&lt;ForceUpdateEvent&gt; {<br>  ForceUpdateBusHandler(super.eventBus);<br>}<br><br>final class ForceUpdateEvent extends AppEvent {<br>  const ForceUpdateEvent({required this.newAppVersion});<br>  final String newAppVersion;<br><br>  @override<br>  List&lt;Object?&gt; get props =&gt; [newAppVersion];<br>}</pre><h4>AppForceUpdateInterceptor</h4><p>For example, a Dio interceptor checks the x-app-version header in every API response and compares it with the current app version installed on the device. If the response version is newer, the ForceUpdateEvent is triggered. This way, the user is centrally and automatically notified that an app update is required.</p><pre>final class AppForceUpdateInterceptor extends Interceptor {<br>  const AppForceUpdateInterceptor();<br><br>  @override<br>  Future&lt;void&gt; onResponse(Response&lt;dynamic&gt; response, ResponseInterceptorHandler handler) async {<br>    final appVersion = response.headers.value(AppConstants.appVersionKey);<br>    final requiredMinVersion = ...;<br>    final currentVersion = ...;<br>    if (requiredMinVersion &gt; currentVersion) {<br>      AppEventBus.instance.forceUpdate.fire(ForceUpdateEvent(newAppVersion: appVersion));<br>    }<br><br>    return handler.next(response);<br>  }<br>}</pre><h4>MainApp</h4><p>Since the forced update event needs to be listened to throughout the entire application, it is subscribed to in the initState method of the MainApp widget, which is launched with runApp.</p><pre>final class MainApp extends StatefulWidget {<br>  const MainApp({super.key});<br><br>  @override<br>  State&lt;MainApp&gt; createState() =&gt; _MainAppState();<br>}<br><br>final class _MainAppState extends State&lt;MainApp&gt; {<br>  Future&lt;void&gt; init() async {<br>    AppEventBus.instance.forceUpdate.listen(<br>      (forceUpdateEvent) {<br>        showDialog(<br>          context: AppConstants.navigatorKey.currentContext!,<br>          builder: (context) =&gt; AppForceUpdateDialog(),<br>        );<br>      },<br>    );<br>  }<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    init();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp.router(...<br>  }<br>}</pre><h4>Conclusion</h4><p>Apart from the force update event, this structure can also be used in scenarios such as inter-module navigation, maintenance mode management, global logout actions, real-time banner notifications, and triggering page-level data refreshes.</p><p>The Event Bus provides a flexible and scalable communication model while preserving modular independence. When properly designed, it simplifies the overall application architecture and enhances reusability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SP3iIF5MS_I1EyviA5BEMw.png" /><figcaption>Created by ChatGPT</figcaption></figure><blockquote>I hope this is helpful to you. :) Don’t forget to follow me, your support and feedback are very important to me, thank you.</blockquote><blockquote>LinkedIn: <a href="https://www.linkedin.com/in/haydardemir/">https://www.linkedin.com/in/haydardemir/</a><br>GitHub: <a href="https://github.com/birhos?tab=repositories">https://github.com/birhos</a></blockquote><blockquote>Enjoy your coding!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97409a0df199" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Quick Actions: Handling Multiple Actions with Scalable Code]]></title>
            <link>https://medium.com/@birhos/flutter-quick-actions-handling-multiple-actions-with-scalable-code-2e6535d67a77?source=rss-f0e1d1f2148a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e6535d67a77</guid>
            <category><![CDATA[software-design-principle]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Haydar Demir]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 04:47:10 GMT</pubDate>
            <atom:updated>2025-04-14T05:28:30.300Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iPAR7eBWE9CSoChg-Y1vDg.png" /><figcaption>Created by ChatGPT</figcaption></figure><p>Hello Everyone</p><p>Nowadays, mobile applications are equipped with constantly evolving technologies to make users’ lives easier. One of these technologies is “quick actions,” which provide shortcuts for fast access to apps directly from the home screen. Flutter offers a powerful tool to integrate this feature into your applications. In this article, we will guide you step by step on how to use quick actions in Flutter to create more user-friendly applications.</p><h4>What Are Quick Actions?</h4><p>Quick actions are customizable shortcuts on Android and iOS that allow users to quickly access apps from the home screen. This enables users to reach their most frequently used features with a single tap. For example, a music app might have a “Recently Played” shortcut, while a news app could offer a “Latest News” shortcut.</p><h4>Why Should We Use Quick Actions?</h4><ul><li><strong>Enhancing User Experience:</strong> Quick actions improve usability by allowing users to access your app more quickly.</li><li><strong>Increasing App Engagement:</strong> When users can easily reach frequently used features, they are more likely to engage with the app regularly.</li><li><strong>Boosting App Visibility:</strong> Shortcuts on the home screen help your app stand out among other applications.</li></ul><h4>Installation:</h4><p>To use quick actions in Flutter, you need to add the <a href="https://pub.dev/packages/quick_actions">quick_actions</a> package to your project. After adding this package to your pubspec.yaml file and running the flutter pub get command, you can start using it.</p><pre>dependencies:<br>  quick_actions: [latest_version]</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FYWy93Zf9eW8RMlK0gK%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fanimecrimesdivision-anime-crimes-division-acd-acds2-YWy93Zf9eW8RMlK0gK&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExYjNweGk0engxbWEzaDVjMWRweDNoeWVhZ2FiM3B2eGFyZmF0bTU5ZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FYWy93Zf9eW8RMlK0gK%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d69552dc070e862b2f9590bf44cb846/href">https://medium.com/media/3d69552dc070e862b2f9590bf44cb846/href</a></iframe><h4>QuickActionsClient</h4><p><strong>QuickActionsClient</strong> is an interface used to manage quick actions in your application. This interface allows dependencies to be easily replaced from the outside, helping to create a flexible structure.</p><p>The main responsibilities of the interface are:</p><ul><li><strong>init</strong> Used to listen for quick actions and perform initialization processes.</li><li><strong>checkAndNavigate</strong> When the application is first opened, it checks the triggered action and navigates to the relevant page.</li><li><strong>setShortcutItems</strong> Creates and updates quick access shortcuts that appear when the app icon is long-pressed.</li><li><strong>clearShortcutItems</strong> Clears and removes all defined quick access shortcuts.</li></ul><pre><br>abstract interface class QuickActionsClient {<br>  factory QuickActionsClient.instance() =&gt; _QuickActionsClientImpl();<br><br>  Future&lt;void&gt; init();<br>  void checkAndNavigate();<br>  Future&lt;void&gt; setShortcutItems(StoreProjectConfigurationModel storeProjectConfiguration);<br>  Future&lt;void&gt; clearShortcutItems();<br>}<br><br>final class _QuickActionsClientImpl implements QuickActionsClient {<br>  final QuickActions _quickActions = const QuickActions();<br><br>  late DateTime initTime;<br>  late DateTime actionTime;<br>  QuickActionClientType? lastAction;<br>  QuickActionClientType? initAction;<br><br>  final threshold = 2; // Seconds<br>  final actionIcon = &#39;quick_actions&#39;;<br><br>  @override<br>  Future&lt;void&gt; init() async {<br>    try {<br>      initTime = DateTime.now();<br>      await _quickActions.initialize((String newActionStr) {<br>        final newAction = QuickActionClientType.fromString(newActionStr);<br>        if (newAction != null) {<br>          actionTime = DateTime.now();<br>          lastAction = newAction;<br>          _checkLastAction(newAction);<br>        }<br>      });<br>    } catch (e) {<br>      AppLogger.e(e);<br>    }<br>  }<br><br>  @override<br>  void checkAndNavigate() {<br>    if (initAction != null) {<br>      PlatformQuickActionNavigator.instance.execute(initAction!, isInitial: true);<br>      initAction = null;<br>    }<br>  }<br><br>  @override<br>  Future&lt;void&gt; setShortcutItems(StoreProjectConfigurationModel storeProjectConfiguration) async {<br>    try {<br>      await _quickActions.setShortcutItems(<br>        &lt;ShortcutItem&gt;[<br>          ShortcutItem(<br>            type: QuickActionClientType.home.name,<br>            localizedTitle: &#39;Home&#39;,<br>            icon: actionIcon,<br>          ),<br>          ShortcutItem(<br>            type: QuickActionClientType.settings.name,<br>            localizedTitle: &#39;Settings&#39;,<br>            icon: actionIcon,<br>          ),<br>        ],<br>      );<br>    } catch (e) {<br>      AppLogger.e(e);<br>    }<br>  }<br><br>  @override<br>  Future&lt;void&gt; clearShortcutItems() async {<br>    try {<br>      await _quickActions.clearShortcutItems();<br>    } catch (e) {<br>      AppLogger.e(e);<br>    }<br>  }<br><br>  void _checkLastAction(QuickActionClientType newAction) {<br>    final diff = actionTime.difference(initTime).inSeconds;<br>    if (diff &lt; threshold) {<br>      // Initial Launch<br>      initAction = newAction;<br>    } else {<br>      // Launched<br>      PlatformQuickActionNavigator.instance.execute(newAction, isInitial: false);<br>    }<br>  }<br>}</pre><h4>IPlatformQuickAction</h4><p>The IPlatformQuickAction interface is designed to define a separate action for each type of quick action. This structure is based on the <strong>Command Pattern</strong>, ensuring that each action operates according to specific criteria.</p><ul><li><strong>isSatisfied</strong>Checks whether the incoming action meets the specified criteria. The QuickActionClientType type parameter determines for which client type the action is valid.</li><li><strong>execute</strong>Executes the defined action. The isInitial parameter indicates whether the action is triggered at the initial launch or at a later time.</li></ul><p>With this interface, quick action management in your application becomes more flexible and organized. You can define custom actions for different client types, ensuring that each action functions independently within its scope.</p><blockquote><em>Let’s not get hung up on the method names; different names can be used without compromising the overall meaning.</em></blockquote><pre>abstract interface class IPlatformQuickAction {<br>  bool isSatisfied(QuickActionClientType type);<br>  Future&lt;void&gt; execute({required bool isInitial});<br>}</pre><h4>QuickActionClientType</h4><p>QuickActionClientType is an enum structure used to define the types of quick actions supported in your application. This structure helps manage specific action types and determine the appropriate actions to be executed.</p><ul><li><strong>home</strong> Represents a quick action type for the home screen.</li><li><strong>settings</strong> Represents a quick action type for the settings screen.</li></ul><p>This enum allows you to manage quick actions in your application within a structured system.</p><pre>import &#39;package:collection/collection.dart&#39;;<br><br>enum QuickActionClientType {<br>  home,<br>  settings;<br><br>  static QuickActionClientType? fromString(String? value) =&gt; QuickActionClientType.values.firstWhereOrNull((element) =&gt; element.name == value);<br>}</pre><h4>HomePlatformQuickAction</h4><p>HomePlatformQuickAction is an action class designed to open the home screen.</p><pre>final class HomePlatformQuickAction implements IPlatformQuickAction {<br>  @override<br>  bool isSatisfied(QuickActionClientType type) =&gt; type == QuickActionClientType.home;<br><br>  @override<br>  Future&lt;void&gt; execute({required bool isInitial}) async {<br>    unawaited(App.router.push(const HomeGuardRoute()));<br>  }<br>}</pre><h4>SettingsPlatformQuickAction</h4><p>SettingsPlatformQuickAction is an action class designed to open the settings screen.</p><pre>final class SettingsPlatformQuickAction implements IPlatformQuickAction {<br>  @override<br>  bool isSatisfied(QuickActionClientType type) =&gt; type == QuickActionClientType.settings;<br><br>  @override<br>  Future&lt;void&gt; execute({required bool isInitial}) async {<br>    unawaited(App.router.push(const SettingsGuardRoute()));<br>  }<br>}</pre><h4>PlatformQuickActionNavigator</h4><p>PlatformQuickActionNavigator is a central routing structure used for handling quick actions, determining the appropriate action for incoming quick actions and executing the corresponding process.</p><ul><li><strong>items</strong> list contains all the quick actions in the application (e.g., HomePlatformQuickAction, SettingsPlatformQuickAction).</li><li><strong>execute</strong> method checks the incoming quick action type (QuickActionClientType) and executes the appropriate action.</li></ul><p>This structure centralizes the management of quick actions, making the code more organized and extensible.</p><pre>import &#39;package:collection/collection.dart&#39;;<br>import &#39;package:fpdart/fpdart.dart&#39; as fpdart;<br><br>final class PlatformQuickActionNavigator {<br>  PlatformQuickActionNavigator._();<br><br>  static final PlatformQuickActionNavigator instance = PlatformQuickActionNavigator._();<br><br>  final items = &lt;IPlatformQuickAction&gt;[<br>    HomePlatformQuickAction(),<br>    SettingsPlatformQuickAction(),<br>  ];<br><br>  Future&lt;void&gt; execute(QuickActionClientType type, {required bool isInitial}) async {<br>    fpdart.Either.tryCatch(<br>      () async {<br>        await items.firstWhereOrNull((element) =&gt; element.isSatisfied(type))?.execute(isInitial: isInitial);<br>      },<br>      (e, s) =&gt; AppLogger.e(&#39;PlatformQuickActionNavigator-execute() | Error: $e, StackTrace: $s&#39;),<br>    );<br>  }<br>}</pre><h4>Conclusion</h4><p>In this article, we explored how to implement <strong>quick actions</strong> in Flutter to enhance user experience with home screen shortcuts. We introduced a structured approach using the <strong>Command Pattern</strong>, ensuring flexibility and maintainability.</p><p>The <strong>QuickActionsClient</strong> manages quick actions, while <strong>IPlatformQuickAction</strong> defines specific actions for different shortcuts. Finally, <strong>PlatformQuickActionNavigator</strong> centralizes execution, making the system scalable. Implementing quick actions improves usability, increases engagement, and provides a seamless user experience.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FPvvSfSDFoAL5e%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FPvvSfSDFoAL5e&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcXJteHB4bXFkdXU0cWw1ODVhbnk5MDdiYzBubTdwMmVjN2FpMDFqbSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FPvvSfSDFoAL5e%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f34031a14efbd3d0fa33073d7d7e8f9/href">https://medium.com/media/0f34031a14efbd3d0fa33073d7d7e8f9/href</a></iframe><blockquote>I hope this is helpful to you. :) Don’t forget to follow me, your support and feedback are very important to me, thank you.</blockquote><blockquote>LinkedIn: <a href="https://www.linkedin.com/in/haydardemir/">https://www.linkedin.com/in/haydardemir/</a><br>GitHub: <a href="https://github.com/birhos?tab=repositories">https://github.com/birhos</a></blockquote><blockquote>Enjoy your coding!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e6535d67a77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auto Route: Navigation Systems in Modular Architecture with Flutter]]></title>
            <link>https://medium.com/@birhos/auto-route-navigation-systems-in-modular-architecture-with-flutter-82178d41ad3b?source=rss-f0e1d1f2148a------2</link>
            <guid isPermaLink="false">https://medium.com/p/82178d41ad3b</guid>
            <category><![CDATA[modular-architecture]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[software-design-principle]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Haydar Demir]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 04:29:43 GMT</pubDate>
            <atom:updated>2025-04-14T05:34:21.693Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4nvI08nOWuPsNURKIJKHEg.jpeg" /><figcaption>Created by ChatGPT</figcaption></figure><p>Hello Everyone!</p><p>Navigation is a crucial aspect of any front-end framework, enabling seamless transitions between screens and supporting various layouts, such as tabs and flows, within the same scene. In iOS, navigation is managed using SwiftUI’s NavigationLink and Coordinators, while Android (or KMP) utilizes solutions like Decompose and other frameworks.</p><p>In Flutter, managing navigation in a scalable and modular way can be challenging, especially when working with large applications. That’s where <strong>Auto Route</strong> comes in — a powerful routing library that simplifies navigation, offering both simple and complex navigation stack management with automatic route generation. In this article, we will explore how <strong>Auto Route</strong> can be leveraged in a <strong>modular architecture</strong>, making navigation more efficient and maintainable.</p><h3>Modular Navigation Example in Super App Architecture (Trendyol, etc.)</h3><p>Large-scale applications like Trendyol have a modular architecture. To better illustrate how to manage this structure using Auto Route, we can take Trendyol as an example.</p><h4>Modular Structure</h4><p><strong>CoreModule (The core infrastructure of the application)</strong></p><ul><li>Theme, language management</li><li>General services (API calls, error management)</li><li>AppRouter etc.</li></ul><p><strong>ShoppingModule (Trendyol)</strong></p><ul><li>Home page,</li><li>Product listing,</li><li>Product details,</li><li>Cart management,</li><li>Payment processing, etc.</li></ul><p><strong>FoodModule (Trendyol Yemek)</strong></p><ul><li>Home page,</li><li>Restaurant listing,</li><li>Order tracking, etc.</li></ul><p>When the user opens the Trendyol application, the <strong>ShoppingModule</strong> (Trendyol Shopping) is loaded first. Here, the user can browse products, shop, and add items to the cart.</p><p>If the user wants to order food through <strong>Trendyol Go</strong> (<strong>FoodModule — Trendyol Food</strong>), a different module is opened. This module displays the list of restaurants and manages the ordering process.</p><p>Both modules operate independently, but thanks to the <strong>core module</strong>, general settings such as user session, theme, and language are preserved.</p><p>Additionally, some buttons in the interface allow direct navigation to different pages within a module. This means that the initial route screen of the module does not always need to be opened; the user can directly access a specific page.</p><p>You can find more details about the package installation in the <a href="https://pub.dev/packages/auto_route">documentation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1FACgiuB04UqbymzVNM87Q.png" /></figure><h4>Installation</h4><p>In each module, we load the following dependencies.</p><pre>dependencies:<br> auto_route: [latest_version]<br><br>dev_dependencies:<br> auto_route_generator: [latest_version]<br> build_runner:</pre><h4>Setup and Usage</h4><ol><li>Create a router class and annotate it with @AutoRouterConfig then extend &quot;RootStackRouter&quot; from The auto_route package</li><li>Override the routes getter and start adding your routes.</li></ol><h4>AppRouter</h4><pre>// modules/core/lib/navigation/app_router.dart<br><br>import &#39;package:auto_route/auto_route.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:module_food/module_food.dart&#39;;<br>import &#39;package:module_shopping/module_shopping.dart&#39;;<br><br>final shoppingModule = ShoppingModule();<br>final foodModule = FoodModule();<br><br>@AutoRouterConfig(replaceInRouteName: Routers.replaceInRouteName)<br>final class AppRouter extends RootStackRouter {<br>  AppRouter() : super(navigatorKey: Routers.navigatorKey);<br><br>  @override<br>  RouteType get defaultRouteType =&gt; const RouteType.adaptive();<br><br>  @override<br>  final List&lt;AutoRoute&gt; routes = [<br>    ...shoppingModule.routes,<br>    ...foodModule.routes,<br>  ];<br>}<br><br>final class Routers {<br>  Routers._();<br><br>  static const String replaceInRouteName = &#39;Page|Screen,Route&#39;;<br>  static final navigatorKey = GlobalKey&lt;NavigatorState&gt;();<br>}</pre><h4>ShoppingModule</h4><pre>// modules/shopping/lib/module_shopping.dart<br><br>import &#39;package:auto_route/auto_route.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:module_core/module_core.dart&#39;;<br><br>import &#39;module_shopping.gr.dart&#39;;<br><br>export &#39;core/core.dart&#39;;<br>export &#39;module_shopping.gr.dart&#39;;<br>export &#39;shopping_cart_screen.dart&#39;;<br>export &#39;shopping_checkout_screen.dart&#39;;<br>export &#39;shopping_home_screen.dart&#39;;<br>export &#39;shopping_product_detail_screen.dart&#39;;<br>export &#39;shopping_product_list_screen.dart&#39;;<br><br>@AutoRouterConfig(replaceInRouteName: Routers.replaceInRouteName)<br>final class ShoppingModule extends RootStackRouter {<br>  @override<br>  List&lt;AutoRoute&gt; get routes =&gt; [<br>        AutoRoute(<br>          initial: true,<br>          path: ShoppingModule.shopping,<br>          page: ShoppingGuardRoute.page,<br>          children: [<br>            AutoRoute(<br>              initial: true,<br>              path: ShoppingModule.home,<br>              page: ShoppingHomeRoute.page,<br>            ),<br>            AutoRoute(<br>              path: ShoppingModule.productList,<br>              page: ShoppingProductListRoute.page,<br>            ),<br>            AutoRoute(<br>              path: ShoppingModule.productDetail,<br>              page: ShoppingProductDetailRoute.page,<br>            ),<br>            AutoRoute(<br>              path: ShoppingModule.cart,<br>              page: ShoppingCartRoute.page,<br>            ),<br>            AutoRoute(<br>              path: ShoppingModule.checkout,<br>              page: ShoppingCheckoutRoute.page,<br>            ),<br>          ],<br>        ),<br>      ];<br><br>  static const String shopping = &#39;/shopping&#39;;<br>  static const String home = &#39;shopping-home&#39;;<br>  static const String productList = &#39;shopping-product-list&#39;;<br>  static const String productDetail = &#39;shopping-product-detail&#39;;<br>  static const String cart = &#39;shopping-cart&#39;;<br>  static const String checkout = &#39;shopping-checkout&#39;;<br><br>  static final routerKey = GlobalKey&lt;AutoRouterState&gt;();<br>}</pre><h4>ShoppingGuardScreen</h4><pre>// modules/shopping/lib/shopping_guard_screen.dart<br><br>import &#39;package:auto_route/auto_route.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:module_shopping/module_shopping.dart&#39;;<br><br>@RoutePage()<br>final class ShoppingGuardScreen extends StatelessWidget {<br>  const ShoppingGuardScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return AutoRouter(key: ShoppingModule.routerKey);<br>  }<br>}</pre><h4>FoodModule</h4><pre>// modules/food/lib/module_food.dart<br><br>import &#39;package:auto_route/auto_route.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:module_core/module_core.dart&#39;;<br><br>import &#39;module_food.gr.dart&#39;;<br><br>export &#39;core/core.dart&#39;;<br>export &#39;food_home_screen.dart&#39;;<br>export &#39;food_order_tracking_screen.dart&#39;;<br>export &#39;food_restaurant_list_screen.dart&#39;;<br>export &#39;module_food.gr.dart&#39;;<br><br>@AutoRouterConfig(replaceInRouteName: Routers.replaceInRouteName)<br>final class FoodModule extends RootStackRouter {<br>  @override<br>  List&lt;AutoRoute&gt; get routes =&gt; [<br>        AutoRoute(<br>          path: FoodModule.food,<br>          page: FoodGuardRoute.page,<br>          children: [<br>            AutoRoute(<br>              initial: true,<br>              path: FoodModule.home,<br>              page: FoodHomeRoute.page,<br>            ),<br>            AutoRoute(<br>              path: FoodModule.restaurantList,<br>              page: FoodRestaurantListRoute.page,<br>            ),<br>            AutoRoute(<br>              path: FoodModule.orderTracking,<br>              page: FoodOrderTrackingRoute.page,<br>            ),<br>          ],<br>        ),<br>      ];<br><br>  static const String food = &#39;/food&#39;;<br>  static const String home = &#39;food-home&#39;;<br>  static const String restaurantList = &#39;food-restaurant-list&#39;;<br>  static const String orderTracking = &#39;food-order-tracking&#39;;<br><br>  static final routerKey = GlobalKey&lt;AutoRouterState&gt;();<br>}</pre><h4>FoodGuardScreen</h4><pre>// modules/food/lib/food_guard_screen.dart<br><br>import &#39;package:auto_route/auto_route.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:module_food/module_food.dart&#39;;<br><br>@RoutePage()<br>final class FoodGuardScreen extends StatelessWidget {<br>  const FoodGuardScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return AutoRouter(key: FoodModule.routerKey);<br>  }<br>}</pre><ul><li>ShoppingGuardScreen and FoodGuardScreen serve as the main container within a module.</li><li>Since AutoRouter is used inside, the navigations within ShoppingModule and FoodModule take place here.</li><li>This way, the routes within ShoppingModule and FoodModule can function separately, without being dependent on the global application router.</li><li>In these guard pages, only module-specific <strong>Provider</strong> or <strong>Cubit</strong> structures can be created, allowing independent management mechanisms that concern only that module to be established.</li></ul><p>I have similarly created the other pages as well. After all pages are prepared, we need to run the following command in each module’s terminal to generate the routes.</p><pre>flutter pub run build_runner build --delete-conflicting-outputs</pre><figure><img alt="ShoppingHomeScreen" src="https://cdn-images-1.medium.com/max/1024/1*kdstYGT-LMDe2x2Dia_oyA.png" /></figure><pre>// modules/shopping/lib/shopping_home_screen.dart<br><br>import &#39;package:auto_route/auto_route.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:module_food/module_food.dart&#39;;<br>import &#39;package:module_shopping/module_shopping.dart&#39;;<br><br>@RoutePage()<br>final class ShoppingHomeScreen extends StatelessWidget {<br>  const ShoppingHomeScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: _buildAppBar(),<br>      body: _buildBody(context),<br>    );<br>  }<br><br>  PreferredSizeWidget _buildAppBar() {<br>    return AppBar(<br>      title: const Text(&#39;Shopping Home&#39;),<br>    );<br>  }<br><br>  Widget _buildBody(BuildContext context) {<br>    return Padding(<br>      padding: const EdgeInsets.symmetric(horizontal: 40),<br>      child: Column(<br>        crossAxisAlignment: CrossAxisAlignment.stretch,<br>        children: [<br>          // 📍 Navigation: ShoppingHomeRoute → ShoppingProductListRoute (with context)<br>          ElevatedButton(<br>            onPressed: () =&gt; context.router.push(const ShoppingProductListRoute()),<br>            child: const Text(&#39;Product List&#39;),<br>          ),<br><br>          //<br>          _buildVerticalSpacer(),<br><br>          // 📍 Navigation: ShoppingHomeRoute → ShoppingCartRoute (with routerKey)<br>          ElevatedButton(<br>            onPressed: () =&gt; ShoppingModule.routerKey.currentState?.controller?.push(const ShoppingCartRoute()),<br>            child: const Text(&#39;Cart&#39;),<br>          ),<br><br>          //<br>          _buildVerticalSpacer(),<br><br>          // 📍 Navigation: ShoppingHomeRoute → FoodGuardRoute -&gt; FoodHomeRoute<br>          ElevatedButton(<br>            onPressed: () =&gt; context.router.push(const FoodGuardRoute()),<br>            child: const Text(&#39;Food&#39;),<br>          ),<br><br>          //<br>          _buildVerticalSpacer(),<br><br>          // 📍 Navigation: ShoppingHomeRoute → FoodGuardRoute -&gt; FoodRestaurantListRoute<br>          ElevatedButton(<br>            onPressed: () =&gt; context.router.push(const FoodGuardRoute(children: [FoodRestaurantListRoute()])),<br>            child: const Text(&#39;Food Restaurant List&#39;),<br>          ),<br><br>          //<br>          _buildVerticalSpacer(),<br><br>          // 📍 Navigation: ShoppingHomeRoute → FoodGuardRoute -&gt; FoodHomeRoute -&gt; FoodRestaurantListRoute<br>          ElevatedButton(<br>            onPressed: () =&gt; context.router.push(const FoodGuardRoute(children: [FoodHomeRoute(), FoodRestaurantListRoute()])),<br>            child: const Text(&#39;Food Home -&gt; Restaurant List&#39;),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br><br>  Widget _buildVerticalSpacer() =&gt; const SizedBox(height: 20);<br>}</pre><ol><li>You can manage navigation operations either using context or routerKey.</li><li>When FoodGuardRoute is opened, FoodHomeRoute, which is set as <strong>initial: true</strong>, is automatically loaded.</li><li>If you want to open a different page instead of the initial page within a module, you can use the <strong>children</strong> property.</li></ol><figure><img alt="FoodRestaurantListScreen" src="https://cdn-images-1.medium.com/max/1024/1*UZsJFB4k96e3P1FTt3NAyg.png" /></figure><pre>// modules/food/lib/food_restaurant_list_screen.dart<br><br>import &#39;package:auto_route/auto_route.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:module_core/module_core.dart&#39;;<br><br>@RoutePage()<br>final class FoodRestaurantListScreen extends StatelessWidget {<br>  const FoodRestaurantListScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: _buildAppBar(),<br>      body: _buildBody(context),<br>    );<br>  }<br><br>  PreferredSizeWidget _buildAppBar() {<br>    return AppBar(<br>      leading: const AutoLeadingButton(),<br>      title: const Text(&#39;Food RestaurantList&#39;),<br>    );<br>  }<br><br>  Widget _buildBody(BuildContext context) {<br>    return Padding(<br>      padding: const EdgeInsets.symmetric(horizontal: 40),<br>      child: Column(<br>        crossAxisAlignment: CrossAxisAlignment.stretch,<br>        children: [<br>          // Closes the current food module by popping the parent route using auto_route<br>          ElevatedButton(<br>            onPressed: () =&gt; context.router.parent()?.maybePop(),<br>            child: const Text(&#39;Close Food Module&#39;),<br>          ),<br><br>          //<br>          _buildVerticalSpacer(),<br><br>          // Closes the current food module by popping all routes until reaching the first route in the navigation stack<br>          ElevatedButton(<br>            onPressed: () =&gt; Routers.navigatorKey.currentState?.popUntil((route) =&gt; route.isFirst),<br>            child: const Text(&#39;Close Food Module&#39;),<br>          ),<br><br>          //<br>          _buildVerticalSpacer(),<br><br>          // Closes the current food module by popping all routes until reaching the ShoppingGuardRoute<br>          ElevatedButton(<br>            onPressed: () =&gt; Routers.navigatorKey.currentState?.popUntil((route) =&gt; route.settings.name == &#39;ShoppingGuardRoute&#39;),<br>            child: const Text(&#39;Close Food Module&#39;),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br><br>  Widget _buildVerticalSpacer() =&gt; const SizedBox(height: 20);<br>}</pre><ol><li>You can use <strong>context.router.maybePop()</strong> to navigate back from a page.</li><li>If you want to completely close the module that the page belongs to (e.g., FoodModule), you should use <strong>context.router.parent()?.maybePop()</strong>.</li><li>Similarly, you can use <strong>Routers.navigatorKey</strong> to apply two different <strong>popUntil</strong> approaches to close the module.</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F102h4wsmCG2s12%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fcharlie-hunnam-gif-hunt-102h4wsmCG2s12&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZGlzd3R2ZWU0OXQyeXVudGZ2dG5kZGNrcjQwaDcwY2UwdDMzdTFkaSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F102h4wsmCG2s12%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="287" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbaefa7ba41038dd6830bd2390d2ea9c/href">https://medium.com/media/bbaefa7ba41038dd6830bd2390d2ea9c/href</a></iframe><blockquote><em>I hope this is helpful to you. :) Don’t forget to follow me, your support and feedback are very important to me, thank you.</em></blockquote><blockquote><em>LinkedIn: </em><a href="https://www.linkedin.com/in/haydardemir/"><em>https://www.linkedin.com/in/haydardemir/</em></a><em><br>GitHub: </em><a href="https://github.com/birhos?tab=repositories"><em>https://github.com/birhos</em></a></blockquote><blockquote><em>Enjoy your coding!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82178d41ad3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Deep Link with Command Pattern: Best Practices for Scalability]]></title>
            <link>https://medium.com/@birhos/flutter-deep-link-with-command-pattern-best-practices-for-scalability-04a6c467647a?source=rss-f0e1d1f2148a------2</link>
            <guid isPermaLink="false">https://medium.com/p/04a6c467647a</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[software-design-principle]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Haydar Demir]]></dc:creator>
            <pubDate>Sun, 26 Jan 2025 10:38:16 GMT</pubDate>
            <atom:updated>2025-04-14T05:33:30.889Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZ0gjh6mbw-T7Daa5udO_Q.jpeg" /><figcaption>Created by ChatGPT</figcaption></figure><p>Hello Everyone!</p><p>Today, we’re diving into one of the must-have features of modern mobile applications: deep link management. Deep links provide an impressive mechanism to direct users to specific content within your app with just a single click. Whether you’re on iOS or Android, Flutter offers a robust infrastructure for this.</p><p>So, what exactly is a deep link? Simply put, it’s a link that points to a specific destination within your app, much like a URL for websites. When a user clicks on this link, the operating system steps in to check if your app is installed. If the app is installed, the link opens directly within the app, leading the user to the intended content. If the app isn’t installed, the operating system redirects the user to the appropriate app store.</p><p>This seamless functionality not only optimizes user experience but also provides a valuable gateway for driving traffic to your app. For example, links included in email campaigns or social media posts can guide users to the desired content within seconds.</p><p>In this article, instead of focusing solely on deep link setup, we’ll explore ways to build a more flexible and scalable structure for handling multiple links. To achieve this, we’ll utilize the <a href="https://pub.dev/packages/app_links">app_links</a> package.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FrJsMvyk7AHHiW9qKLM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FPerspectief-camas-perspectief-it-rJsMvyk7AHHiW9qKLM&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExNG5jZ2NseHBxN201emxyODQ5ejY0aWRuNGdiNGljZ2szbnoxeDRwdCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FrJsMvyk7AHHiW9qKLM%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/043c4ed7ee49b2e2eb4715b80b587922/href">https://medium.com/media/043c4ed7ee49b2e2eb4715b80b587922/href</a></iframe><h4>DeepLinkClient</h4><p>DeepLinkClient is an interface used for managing deep links in your application. This interface facilitates the easy replacement of dependencies from the outside and helps create a flexible structure. The main responsibilities of the interface are:</p><ul><li><strong>init</strong>: Initializes the processes needed to listen for deep links and retrieve the initial link.</li><li><strong>checkInitialUri</strong>: Checks the initial URI when the application is first launched.</li><li><strong>dispose</strong>: Cancels listeners to prevent unnecessary resource consumption.</li></ul><pre>import &#39;dart:async&#39;;<br><br>import &#39;package:app_links/app_links.dart&#39;;<br><br>abstract interface class DeepLinkClient {<br>  factory DeepLinkClient.instance() =&gt; _DeepLinkClientImpl();<br><br>  Future&lt;void&gt; init();<br>  void dispose();<br>  void checkInitialUri();<br>}<br><br>final class _DeepLinkClientImpl implements DeepLinkClient {<br>  final AppLinks _appLinks = AppLinks();<br><br>  StreamSubscription&lt;Uri&gt;? _linkSubscription;<br><br>  Uri? initialUri;<br><br>  @override<br>  Future&lt;void&gt; init() async {<br>    initialUri = await _appLinks.getInitialLink();<br>    _linkSubscription = _appLinks.uriLinkStream.listen((uri) {<br>      _checkUri(uri, isInitial: false);<br>    });<br>  }<br><br>  @override<br>  void checkInitialUri() {<br>    if (initialUri != null) {<br>      _checkUri(initialUri, isInitial: true);<br>      initialUri = null;<br>    }<br>  }<br><br>  @override<br>  void dispose() {<br>    _linkSubscription?.cancel();<br>  }<br><br>  void _checkUri(Uri? uri, {required bool isInitial}) {<br>    if (uri == null) return;<br>    unawaited(DeeplinkNavigator.instance.execute(uri.path, isInitial: isInitial));<br>  }<br>}</pre><h4>IDeeplinkAction:</h4><p>IDeeplinkAction is an interface designed to define a separate action for each type of deep link. This structure is based on the Command Pattern design and allows for defining different behaviors for each link.</p><ul><li><strong>isSatisfied</strong>: Checks whether the incoming link matches the criteria for this action.</li><li><strong>execute</strong>: Defines the operation to be performed for a specific link.</li></ul><p>This interface makes the deep link logic in your application more extensible and organized.</p><blockquote><em>Let’s not get hung up on the method names; different names can be used without compromising the overall meaning.</em></blockquote><pre>abstract interface class IDeeplinkAction {<br>  bool isSatisfied(String path);<br>  Future&lt;void&gt; execute(String path, {required bool isInitial});<br>}</pre><h4>DeepLinkType</h4><p>DeepLinkType is an enum that defines the types of deep links supported in your application. This structure is used to easily match links and determine which action should be executed.</p><ul><li><strong>store</strong>: Links starting with /store.</li><li><strong>productDetail</strong>: Links starting with /productDetail.</li><li><strong>getDeepLinkType </strong>: Identifies the type of the incoming link.</li></ul><p>This enum organizes different types of links in your application in a structured and manageable way.</p><pre>import &#39;package:collection/collection.dart&#39;;<br><br>enum DeepLinkType {<br>  store(&#39;/store&#39;),<br>  productDetail(&#39;/productDetail&#39;);<br><br>  const DeepLinkType(this.rawValue);<br>  final String rawValue;<br><br>  static DeepLinkType? getDeepLinkType(String path) {<br>    final type = DeepLinkType.values.firstWhereOrNull((element) =&gt; path.contains(element.rawValue));<br>    return type;<br>  }<br>}</pre><h4>StoreAction</h4><p>StoreAction is an action class designed to open the store screen.</p><pre>final class StoreAction implements IDeeplinkAction {<br>  @override<br>  bool isSatisfied(String path) =&gt; DeepLinkType.getDeepLinkType(path) == DeepLinkType.store;<br><br>  @override<br>  Future&lt;void&gt; execute(String path, {required bool isInitial}) async {<br>    App.router.push(StoreRoute());<br>  }<br>}</pre><h4>ProductDetailAction</h4><p>ProductDetailAction is an action class designed to open the product detail screen.</p><pre>final class ProductDetailAction implements IDeeplinkAction {<br>  @override<br>  bool isSatisfied(String path) =&gt; DeepLinkType.getDeepLinkType(path) == DeepLinkType.productDetail;<br><br>  @override<br>  Future&lt;void&gt; execute(String path, {required bool isInitial}) async {<br>    final productId = path?.split(&#39;/&#39;).last;<br>    if (productId case final String productId) {<br>      App.router.push(ProductDetailRoute(productId: productId));<br>    }<br>  }<br>}</pre><h4>DeeplinkNavigator</h4><p>DeeplinkNavigator is a central routing structure used for handling deep links. This class determines the appropriate action for incoming links and initiates the corresponding process.</p><ul><li><strong>items</strong>: Contains all the deep link actions defined in your application (e.g., StoreAction, ProductDetailAction).</li><li><strong>execute</strong>: Checks the incoming URI and executes the appropriate action.</li></ul><p>This structure centralizes the management of deep links, making the code more organized and extensible.</p><pre>import &#39;package:collection/collection.dart&#39;;<br><br>final class DeeplinkNavigator {<br>  DeeplinkNavigator._();<br><br>  static final DeeplinkNavigator instance = DeeplinkNavigator._();<br><br>  final items = &lt;IDeeplinkAction&gt;[<br>    StoreAction(),<br>    ProductDetailAction(),<br>  ];<br><br>  Future&lt;void&gt; execute(String path, {required bool isInitial}) async {<br>    await items.firstWhereOrNull((element) =&gt; element.isSatisfied(path))?.execute(path, isInitial: isInitial);<br>  }<br>}</pre><h4>Conclusion</h4><p>In this article, we explored the deep linking mechanism and how it can be made flexible and extensible using the Command Pattern. With Flutter’s robust infrastructure, it is possible to quickly direct users to the right content.</p><p>The Command Pattern allows you to define separate actions for each type of link, making the code modular and easily extendable. This approach not only enhances the user experience but also supports the growth of your application.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl41lSzsdFYJVtfx4c%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fvulture-l41lSzsdFYJVtfx4c&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExbTluZXI0MW5sNjV6N2ExMWs5OHBubHpsMDVrdXV1N3M2NnhrYzh6ZSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2Fl41lSzsdFYJVtfx4c%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="246" frameborder="0" scrolling="no"><a href="https://medium.com/media/93d1f5cbea1b0fcca1bf3f412eb39899/href">https://medium.com/media/93d1f5cbea1b0fcca1bf3f412eb39899/href</a></iframe><blockquote><em>I hope this is helpful to you. :) Don’t forget to follow me, your support and feedback are very important to me, thank you.</em></blockquote><blockquote><em>LinkedIn: </em><a href="https://www.linkedin.com/in/haydardemir/"><em>https://www.linkedin.com/in/haydardemir/</em></a><em><br>GitHub: </em><a href="https://github.com/birhos?tab=repositories"><em>https://github.com/birhos</em></a></blockquote><blockquote><em>Enjoy your coding!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04a6c467647a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effortless Lifecycle Management in Flutter Applications]]></title>
            <link>https://medium.com/@birhos/effortless-lifecycle-management-in-flutter-applications-757cc7fc2d96?source=rss-f0e1d1f2148a------2</link>
            <guid isPermaLink="false">https://medium.com/p/757cc7fc2d96</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[software-design-principle]]></category>
            <dc:creator><![CDATA[Haydar Demir]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 02:33:14 GMT</pubDate>
            <atom:updated>2025-04-14T05:37:29.742Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-DI3fwA6GAn1JPds3FGMA.jpeg" /><figcaption>Created by ChatGPT</figcaption></figure><p>Hello Everyone!</p><p>App lifecycle management is a cornerstone in the app development process. As modern mobile applications offer increasingly complex features to meet user needs, they must behave appropriately when in the foreground, background, or closed states. Such scenarios require developers to not only deliver functionality but also to optimize resource management and user experience.</p><p>As your application grows, the operations tied to the app lifecycle can become more complex. For instance, running specific tasks in the background, maintaining sessions while the app is closed, or ensuring a seamless user experience when the app comes to the foreground are all requirements that demand careful structuring and management.</p><p>In this article, we will delve into the details of an abstract class called AppLifecycleManager, designed to make lifecycle management in Flutter applications easier and more organized. This structure allows you to manage lifecycle-related operations from a central point, making your development process more modular and sustainable.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FBpGWitbFZflfSUYuZ9%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FBpGWitbFZflfSUYuZ9&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExMW9xaXUwaHZxeWY3c2k0azBnY3B5N2ZxNG85OXc3MTl6YjBjYm5iYyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FBpGWitbFZflfSUYuZ9%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="361" frameborder="0" scrolling="no"><a href="https://medium.com/media/10bd0fd3d7da7e925c9cc7ca636352ea/href">https://medium.com/media/10bd0fd3d7da7e925c9cc7ca636352ea/href</a></iframe><h4><strong>What is AppLifecycleManager?</strong></h4><p>By using AppLifecycleListener, you can make your code more organized and readable, focusing only on specific events you are interested in, thus managing your code in a more sustainable way.</p><p>For this reason, AppLifecycleManager incorporates the AppLifecycleListener class to effectively manage operations tied to your app&#39;s lifecycle. This structure allows you to organize and control actions triggered during different app states (e.g., resume, pause, hide, etc.)</p><p>AppLifecycleManager provides three core methods:</p><ol><li><strong>Adding lifecycle functions (</strong><strong>add)</strong>: You can add functions that will be triggered during lifecycle events, such as when your app goes to the background or comes to the foreground.</li><li><strong>Removing functions (</strong><strong>remove)</strong>: You can remove lifecycle functions that are no longer needed.</li><li><strong>Clearing all functions (</strong><strong>clear)</strong>: You can clear all lifecycle functions at once.</li></ol><pre>abstract interface class AppLifecycleManager {<br>  factory AppLifecycleManager.instance() =&gt; _AppLifecycleManagerImpl();<br><br>  Future&lt;void&gt; add(IAppLifecycleUseCase usecase);<br>  void remove(IAppLifecycleUseCase usecase);<br>  void clear();<br>}</pre><h4><strong>AppLifecycleManager </strong>Concrete Class</h4><pre>final class _AppLifecycleManagerImpl implements AppLifecycleManager {<br>  _AppLifecycleManagerImpl() {<br>    _listenLifecycle();<br>  }<br><br>  final List&lt;IAppLifecycleUseCase&gt; _usecases = [];<br><br>  @override<br>  Future&lt;void&gt; add(IAppLifecycleUseCase usecase) async {<br>    try {<br>      if (!_usecases.any((element) =&gt; element.id == usecase.id)) {<br>        _usecases.add(usecase);<br>        await usecase.init();<br>      }<br>    } catch (e) {<br>      AppLogger.e(e);<br>    }<br>  }<br><br>  @override<br>  void remove(IAppLifecycleUseCase usecase) {<br>    try {<br>      _usecases.removeWhere((element) =&gt; element.id == usecase.id);<br>      usecase.dispose();<br>    } catch (e) {<br>      AppLogger.e(e);<br>    }<br>  }<br><br>  void _listenLifecycle() {<br>    AppLifecycleListener(<br>      onDetach: () async {<br>        for (final usecase in _usecases) {<br>          await usecase.onDetach();<br>        }<br>      },<br>      onResume: () async {<br>        for (final usecase in _usecases) {<br>          await usecase.onResume();<br>        }<br>      },<br>      onPause: () async {<br>        for (final usecase in _usecases) {<br>          await usecase.onPause();<br>        }<br>      },<br>      onHide: () async {<br>        for (final usecase in _usecases) {<br>          await usecase.onHide();<br>        }<br>      },<br>      onInactive: () async {<br>        for (final usecase in _usecases) {<br>          await usecase.onInactive();<br>        }<br>      },<br>      onShow: () async {<br>        for (final usecase in _usecases) {<br>          await usecase.onShow();<br>        }<br>      },<br>    );<br>  }<br><br>  @override<br>  void clear() {<br>    _usecases.clear();<br>  }<br>}</pre><h4><strong>IAppLifecycleUseCase</strong></h4><p>Each use case implements the IAppLifecycleUseCase interface. This structure provides methods to handle lifecycle events:</p><pre>abstract class IAppLifecycleUseCase {<br>  AppLifecycleUseCase get id;<br>  Future&lt;void&gt; init() {}<br>  void dispose() {}<br>  Future&lt;void&gt; onDetach() {}<br>  Future&lt;void&gt; onResume() {}<br>  Future&lt;void&gt; onPause() {}<br>  Future&lt;void&gt; onHide() {}<br>  Future&lt;void&gt; onInactive() {}<br>  Future&lt;void&gt; onShow() {}<br>}</pre><h4>AppLifecycleUseCase</h4><p>AppLifecycleUseCase is an AppLifecycleUseCase that defines different use cases responding to the application&#39;s lifecycle events. This enum provides a unique identifier for each use case, enabling them to be easily managed and distinguished by AppLifecycleManager and IAppLifecycleUseCase.</p><pre>enum AppLifecycleUseCase {<br>  sessionTimeout;<br>}</pre><h4><strong>Example: SessionTimeoutUseCase</strong></h4><p>Below is an example of a separate class that implements the IAppLifecycleUseCase interface. This class provides functionality to check if the user&#39;s session has timed out and redirect the user to the login screen.</p><pre>final class SessionTimeoutUseCase extends IAppLifecycleUseCase {<br>  SessionTimeoutUseCase({<br>    required AuthFacade authFacade,<br>    required NavigationService navigationService,<br>  })  : _authFacade = authFacade,<br>        _navigationService = navigationService;<br><br>  final AuthFacade _authFacade;<br>  final NavigationService _navigationService;<br><br>  @override<br>  AppLifecycleUseCase id = AppLifecycleUseCase.sessionTimeout;<br><br>  @override<br>  Future&lt;void&gt; onInactive() async {<br>    // Checks if the user&#39;s session is active.<br>    final isSessionActive = await _authFacade.isSessionActive();<br>    if (!isSessionActive) {<br>      // Session has ended, redirect the user to the login screen.<br>      await _navigateToLogin();<br>    }<br>  }<br><br>  @override<br>  Future&lt;void&gt; onResume() async {<br>    // Can refresh the user&#39;s session duration.<br>    await _authFacade.refreshSession();<br>  }<br><br>  Future&lt;void&gt; _navigateToLogin() async {<br>    // Performs the redirection process.<br>    await _navigationService.navigateToLogin();<br>  }<br>}</pre><p><strong>Use Case:</strong></p><pre>final lifecycleManager = AppLifecycleManager.instance();<br><br>final sessionTimeoutUseCase = SessionTimeoutUseCase(<br>  authFacade: AuthFacade(),<br>  navigationService: NavigationService(),<br>);<br><br>lifecycleManager.add(sessionTimeoutUseCase);</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FMQnmKbh8A9n9kT4Ua5%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FCleverCodeLab-fire-work-crazy-MQnmKbh8A9n9kT4Ua5&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExYW5uajVmMzBxejd2aHZmcWZteWk2c2FlY2t6Njhkcm1xczV3ZWZrZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FMQnmKbh8A9n9kT4Ua5%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e5c6ef2c2e54f8dd29070d87eee06ad/href">https://medium.com/media/2e5c6ef2c2e54f8dd29070d87eee06ad/href</a></iframe><blockquote>I hope this is helpful to you. :) Don’t forget to follow me, your support and feedback are very important to me, thank you.</blockquote><blockquote>LinkedIn: <a href="https://www.linkedin.com/in/haydardemir/">https://www.linkedin.com/in/haydardemir/</a><br>GitHub: <a href="https://github.com/birhos?tab=repositories">https://github.com/birhos</a></blockquote><blockquote>Enjoy your coding!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=757cc7fc2d96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Method Channel: A Chain of Responsibility Approach]]></title>
            <link>https://medium.com/@birhos/flutter-method-channel-a-chain-of-responsibility-approach-f5a622028c1d?source=rss-f0e1d1f2148a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5a622028c1d</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[software-design-principle]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Haydar Demir]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 13:51:35 GMT</pubDate>
            <atom:updated>2025-04-14T05:35:57.056Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WC2zB_Lt7BOEF4_oyRCcoA.jpeg" /><figcaption>Bu görsel, ChatGPT tarafından üretilmiştir. 😊</figcaption></figure><p>Herkese merhaba!</p><p>Sabah uyanıyorsunuz, mutfağa gidiyorsunuz ve kahve yapmak istiyorsunuz. Ama kahve makinesi bozulmuş. Ne yaparsınız? Önce kahve makinesini kontrol edersiniz. Çalışmıyorsa, kettle’a yönelirsiniz. O da mı bozuk? Bu sefer, filtre kahve düşünürsünüz. En sonunda, kahveyi dışarıdan almaya karar verirsiniz. İşte bu, hayatımızdaki küçük bir <strong>Chain of Responsibility</strong> (Sorumluluk Zinciri) örneği!</p><p>Her bir adım, zincirin bir halkasıdır ve talep, bu zincirdeki halkalar arasında dolaşır. Eğer bir adımda başarı sağlanırsa, işlem orada durur. Eğer başarı sağlanamazsa, istek sıradaki halkaya geçer.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F5173071&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fthis-is-fine-fire-crisis-chill-coffee-gif-5173071&amp;image=https%3A%2F%2Fmedia.tenor.com%2Fd7NEyU1mKXIAAAAN%2Fthis-is-fine-fire.png&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d547c4bd8494eb994acc34e62fda14d9/href">https://medium.com/media/d547c4bd8494eb994acc34e62fda14d9/href</a></iframe><h4>Peki, Flutter’da Method Channel ile bunun ne ilgisi bar?</h4><p>Aslında, oldukça fazla! <a href="https://docs.flutter.dev/platform-integration/platform-channels">Method Channel</a> ile Flutter’dan Android ya da iOS’a bir talep gönderdiğinizde, bu talep doğrudan işlenecek bir yer arar. Eğer istek bir yönteme uymuyorsa, sıradaki işleyiciye geçer. İşte bu noktada <a href="https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern?useskin=vector"><strong>Chain of Responsibility Pattern</strong></a> devreye girer.</p><p>Flutter uygulamalarında Dart koduyla yerel platformlar (Android/iOS) arasında iletişim kurarken, gelen Method Channel çağrılarının farklı senaryolar için ele alınması gerekir. Bu işlemi bir zincire dönüştürdüğümüzde, her bir istek bir sonraki halkaya geçirilir. Her halka, kahve makinesine, kettle’a ya da filtre kahveye benzer şekilde bir görevi üstlenir. Her istek bir zincir boyunca dolaşır ve doğru işleyici tarafından ele alınır.</p><h4>Method Channel Nedir?</h4><p>MethodChannel, Flutter uygulamasında Dart kodunu Android (Kotlin/Java) veya iOS (Swift/Objective-C) koduyla entegre etmek için kullanılır. Bir Method Channel, Dart tarafından bir çağrıyı tetikler ve native platformda karşılık gelen bir işlemi gerçekleştirir.</p><p>Hazırsanız, şimdi Android ve iOS kodlarımızı yazmaya başlayalım ve bu yapıyı hayata geçirelim!</p><h4>IAction</h4><p>IAction arayüzü, native işlevlerin modüler bir şekilde yönetilmesini sağlar. Her bir işlev, bir sınıf ile temsil edilir ve belirli bir eylem gerçekleştirilir. Bu tasarım deseni, açık kapalı prensibini (Open/Closed Principle) destekler.</p><pre>interface IAction {<br>  fun isSatisfied(methodName: String): Boolean<br>  fun execute(mainActivity: MainActivity, call: MethodCall, result: MethodChannel.Result)<br>}</pre><pre>protocol IAction {<br>  func isSatisfied(methodName: String) -&gt; Bool<br>  func execute(controller: FlutterViewController, call: FlutterMethodCall, result: FlutterResult)<br>}</pre><ol><li><strong>isSatisfied:</strong> Bu metod, MethodChannel üzerinden gelen çağrının hangi işleme uygun olduğunu belirler.</li><li><strong>execute:</strong> Çağrıyı işleyen ve sonucu Flutter’a geri gönderen metoddur.</li></ol><p><strong>Avantajları:</strong></p><ul><li>Eylemler kolayca eklenebilir veya çıkarılabilir.</li><li>Her işlev kendi sınıfında yönetildiği için kodun bakımı kolaydır.</li><li>execute metodu içinde her işlev için özelleştirilmiş işlemler tanımlanabilir.</li></ul><h4>MethodChannelHandler</h4><p>MethodChannelHandler, bir eylem (action) yöneticisi gibi çalışır. Gelen çağrıları belirli bir eyleme yönlendirir ve modüler yapıyı sağlar.</p><pre>class MethodChannelHandler(private val actions: List&lt;IAction&gt;) {<br>  fun handle(mainActivity: MainActivity, call: MethodCall, result: MethodChannel.Result) {<br>    for (action in actions) {<br>      if (action.isSatisfied(call.method)) {<br>        action.execute(mainActivity, call, result)<br>        return<br>      }<br>    }<br>    result.notImplemented()<br>  }<br>}</pre><pre>class MethodChannelHandler {<br>  private var actions: [IAction]<br><br>  init(actions: [IAction]) {<br>    self.actions = actions<br>  }<br><br>  func handle(controller: FlutterViewController, call: FlutterMethodCall, result: FlutterResult) {<br>    for action in actions {<br>      if action.isSatisfied(methodName: call.method) {<br>        action.execute(controller: controller, call: call, result: result)<br>        return<br>      }<br>    }<br>    result(FlutterMethodNotImplemented)<br>  }<br>}</pre><h3>Kullanım Senaryosu</h3><h4>MoveToBackgroundAction</h4><p>MoveToBackgroundAction sınıfı, uygulamanın arka plana taşınması işlemini yönetir</p><pre>class MoveToBackgroundAction : IAction {<br>  override fun isSatisfied(methodName: String): Boolean {<br>    return methodName == &quot;moveToBackground&quot;<br>  }<br><br>  override fun execute(<br>    mainActivity: MainActivity,<br>    call: MethodCall,<br>    result: MethodChannel.Result<br>  ) {<br>    mainActivity.moveTaskToBack(true)<br>    result.success(null)<br>  }<br>}</pre><pre>class MoveToBackgroundAction: IAction {<br>  func isSatisfied(methodName: String) -&gt; Bool {<br>    return methodName == &quot;moveToBackground&quot;<br>  }<br><br>  func execute(<br>    controller: FlutterViewController,<br>    call: FlutterMethodCall,<br>    result: FlutterResult<br>  ) {<br>    exit(0)<br>    result(nil)<br>  }<br>}</pre><h4>MainActivity ve AppDelegate</h4><p>MainActivity ve AppDelegate içinde IAction örnekleri tanımlanarak MethodChannelHandler’a parametre olarak aktarılır.</p><pre>class MainActivity : FlutterActivity() {<br>  private val CHANNEL = &quot;com.example.sample/channel&quot;<br><br>  override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br><br>    val actions = listOf(<br>      MoveToBackgroundAction(),<br>      GetMicrophonesAction(),<br>    )<br><br>    val handler = MethodChannelHandler(actions)<br><br>    // Method Channel for Flutter communication<br>    flutterEngine?.dartExecutor?.binaryMessenger?.let { binaryMessenger -&gt;<br>      MethodChannel(binaryMessenger, CHANNEL).setMethodCallHandler { call, result -&gt;<br>        handler.handle(this, call, result)<br>      }<br>    }<br>  }<br>}</pre><pre>@main<br>@objc class AppDelegate: FlutterAppDelegate, PKPushRegistryDelegate {<br>  override func application(<br>    _ application: UIApplication,<br>    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?<br>  ) -&gt; Bool {<br>    let controller : FlutterViewController = window?.rootViewController as! FlutterViewController<br>    let channel = FlutterMethodChannel(name: &quot;com.example.sample/channel&quot;, binaryMessenger: controller.binaryMessenger)<br><br>    let actions = [<br>      MoveToBackgroundAction(),<br>      GetMicrophonesAction(),<br>    ]<br><br>    let handler = MethodChannelHandler(actions: actions)<br><br>    // Method Channel for Flutter communication<br>    channel.setMethodCallHandler({<br>      [weak self] (call: FlutterMethodCall, result: FlutterResult) -&gt; Void in<br>      handler.handle(controller: controller, call: call, result: result)<br>    })<br><br>    return super.application(application, didFinishLaunchingWithOptions: launchOptions)<br>  }<br>}</pre><h4>Avantajları</h4><p>IAction ve MethodChannelHandler kullanımı, aşağıdaki avantajları sunar:</p><ol><li><strong>Modülerlik:</strong> Her bir işlev bağımsız bir sınıfta tanımlanır.</li><li><strong>Esneklik:</strong> Yeni bir işlev kolayca eklenebilir.</li><li><strong>Temiz Kod:</strong> Eylem kontrolü ve işleme kodu ayrıştırıldığı için kod okunabilirliği artar.</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FCrFLL3CnRpw5ddlBMm%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FCleverCodeLab-cat-cute-coffee-CrFLL3CnRpw5ddlBMm&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcmo5amJkaDB4bDl4ZXMxdXdlbHp3Z28zdnQ1a3g1cXI5Mnp2ZHVibyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FCrFLL3CnRpw5ddlBMm%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f4061f3b5a34ed6944e66c8fe98a7f4/href">https://medium.com/media/1f4061f3b5a34ed6944e66c8fe98a7f4/href</a></iframe><p>Sonuç olarak, Chain of Responsibility Pattern ile Flutter uygulamanızda Method Channel çağrılarını yönetmek, tıpkı karmaşık bir kahve siparişini düzenlemek kadar eğlenceli ve düzenli olabilir. Şimdi kahvenizi alın ve kod yazmaya devam edin!</p><blockquote>Umarım sizin için faydalı olur. :)<br>Beni takip etmeyi unutmayın, desteğiniz ve geri bildirimleriniz benim için çok önemli, teşekkürler.</blockquote><blockquote>LinkedIn: <a href="https://www.linkedin.com/in/haydardemir/">https://www.linkedin.com/in/haydardemir/</a><br>GitHub: <a href="https://github.com/birhos?tab=repositories">https://github.com/birhos</a></blockquote><blockquote>Keyifli kodlamalar!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5a622028c1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>