<?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 Moamedaliebaid on Medium]]></title>
        <description><![CDATA[Stories by Moamedaliebaid on Medium]]></description>
        <link>https://medium.com/@mo7amedaliebaid?source=rss-dc3945c088ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*M1luwMbGgq8GrI2h0tWsUw.jpeg</url>
            <title>Stories by Moamedaliebaid on Medium</title>
            <link>https://medium.com/@mo7amedaliebaid?source=rss-dc3945c088ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 23:08:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mo7amedaliebaid/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[Why the Observer Pattern is Essential for Flutter Developers?]]></title>
            <link>https://medium.com/@mo7amedaliebaid/why-the-observer-pattern-is-essential-for-flutter-developers-214ce2f5e0d5?source=rss-dc3945c088ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/214ce2f5e0d5</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[observer-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[observer-design-pattern]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Moamedaliebaid]]></dc:creator>
            <pubDate>Fri, 31 Jan 2025 23:44:01 GMT</pubDate>
            <atom:updated>2025-01-31T23:44:01.312Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yMRuyAQsoeRG4DqH8vaqkg.png" /></figure><h4>1. What is Observer Design Pattern?</h4><p>The Observer Design Pattern is a behavioral pattern that defines a one-to-many dependency between objects.<br> when one object (the subject) changes its state, all its observers are notified and updated automatically.</p><h4>2. When to Use the Observer Pattern?</h4><ul><li>when multiple objects need to stay in sync with a subject’s state.</li><li>when the subject doesn’t know in advance how many or which objects depend on it.</li><li>useful in implementing event-driven systems like data streams, or real-time notifications.</li></ul><h4>3. Observer Design Pattern Implementation in dart.</h4><ul><li>Observer : Defines an interface for objects that should be notified of changes in the subject.</li></ul><pre>abstract class Observer {<br>  void update(String news);<br>}</pre><ul><li>Subject : Maintains a list of observers and provides methods to add , remove , and notify them.</li></ul><pre>abstract class Subject {<br>  void addObserver(Observer observer);<br><br>  void removeObserver(Observer observer);<br><br>  void notifyObservers();<br>}</pre><ul><li>Concrete Subject : Implements the subject and maintains its state.</li></ul><pre>class NewsAgency implements Subject {<br>  final List&lt;Observer&gt; _observers = [];<br>  String _latestNews = &#39;&#39;;<br><br>  void publishNews(String news) {<br>    _latestNews = news;<br>    notifyObservers();<br>  }<br><br>  @override<br>  void addObserver(Observer observer) {<br>    _observers.add(observer);<br>  }<br><br>  @override<br>  void notifyObservers() {<br>    for (var observer in _observers) {<br>      observer.update(_latestNews);<br>    }<br>  }<br><br>  @override<br>  void removeObserver(Observer observer) {<br>    _observers.remove(observer);<br>  }<br>}</pre><ul><li>Concrete Observer (Subscriber) : Implements the observer and updates itself based on notifications.</li></ul><pre>class Subscriber implements Observer {<br>  String name;<br><br>  Subscriber(this.name);<br><br>  @override<br>  void update(String news) {<br>    print(&quot;$name received news update : $news&quot;);<br>  }<br>}</pre><ul><li>Client Code.</li></ul><pre>void main() {<br>  // Create the subject<br>  NewsAgency newsAgency = NewsAgency();<br><br>  // Create observers<br>  Subscriber subscriber1 = Subscriber(&quot;Alice&quot;);<br>  Subscriber subscriber2 = Subscriber(&quot;Bob&quot;);<br><br>  // Register observers<br>  newsAgency.addObserver(subscriber1);<br>  newsAgency.addObserver(subscriber2);<br><br>  // Publish news<br>  newsAgency.publishNews(&quot;Breaking: New Dart version released!&quot;);<br><br>  print(&quot;\n--- After some time ---\n&quot;);<br><br>  // Remove an observer and publish more news<br>  newsAgency.removeObserver(subscriber1);<br>  newsAgency.publishNews(&quot;Update: Dart 3.1 is now available!&quot;);<br>}</pre><h4>4. Flutter built-in functionalities that are built on top of the <strong>Observer Design Pattern.</strong></h4><p>Flutter has several built-in functionalities that are built on top of the <strong>Observer Design Pattern</strong>. These functionalities allow widgets to listen for changes and update accordingly. Here are some key examples:</p><ol><li><strong>Listenable &amp; ChangeNotifier</strong> (Foundation of Provider).</li></ol><ul><li>Listenable is a core Flutter class that allows objects to be observed.</li><li>ChangeNotifier extends Listenable and is commonly used with Provider for state management.</li></ul><pre>class Counter extends ChangeNotifier {<br>  int _count = 0;<br>  int get count =&gt; _count;<br><br>  void increment() {<br>    _count++;<br>    notifyListeners();  // Notifies all observers (widgets)<br>  }<br>}</pre><ul><li><strong>Relation to Observer Pattern:</strong> ChangeNotifier is the <strong>subject</strong>, and widgets using Consumer or Provider.of() are <strong>observers</strong>.</li></ul><p>2. <strong>ValueNotifier &amp; ValueListenableBuilder.</strong></p><ul><li>ValueNotifier&lt;T&gt; is a more lightweight version of ChangeNotifier for simple state updates.</li><li>ValueListenableBuilder&lt;T&gt; is a widget that listens to ValueNotifier changes and rebuilds when its value changes.</li></ul><pre>ValueNotifier&lt;int&gt; counter = ValueNotifier&lt;int&gt;(0);<br><br>ValueListenableBuilder&lt;int&gt;(<br>  valueListenable: counter,<br>  builder: (context, value, child) {<br>    return Text(&#39;Counter: $value&#39;);<br>  },<br>);</pre><p>. <strong><em>Relation to Observer Pattern:</em></strong><em> </em><em>ValueNotifier acts as the </em><strong><em>subject</em></strong><em>, and </em><em>ValueListenableBuilder is the </em><strong><em>observer</em></strong><em>.</em></p><p>3. <strong>InheritedWidget &amp; InheritedNotifier.</strong></p><ul><li>InheritedWidget is Flutter’s low-level way to propagate state changes down the widget tree.</li><li>InheritedNotifier extends InheritedWidget but listens to a Listenable object (like ChangeNotifier).</li></ul><pre>class MyInheritedWidget extends InheritedWidget {<br>  final int counter;<br><br>  MyInheritedWidget({required this.counter, required Widget child}) : super(child: child);<br><br>  @override<br>  bool updateShouldNotify(covariant MyInheritedWidget oldWidget) {<br>    return oldWidget.counter != counter;<br>  }<br><br>  static MyInheritedWidget? of(BuildContext context) {<br>    return context.dependOnInheritedWidgetOfExactType&lt;MyInheritedWidget&gt;();<br>  }<br>}</pre><p>. <strong>Relation to Observer Pattern:</strong> Widgets that call context.dependOnInheritedWidgetOfExactType() become <strong>observers</strong> and rebuild when the inherited widget changes.</p><p>4. <strong>NavigationObserver (RouteObserver).</strong></p><ul><li>RouteObserver allows listening to navigation changes (push/pop of routes).</li><li>Used for tracking screen transitions, analytics, or UI state persistence.</li></ul><pre>class MyRouteObserver extends RouteObserver&lt;PageRoute&lt;dynamic&gt;&gt; {<br>  @override<br>  void didPush(Route route, Route? previousRoute) {<br>    print(&quot;Navigated to ${route.settings.name}&quot;);<br>  }<br><br>  @override<br>  void didPop(Route route, Route? previousRoute) {<br>    print(&quot;Returned from ${route.settings.name}&quot;);<br>  }<br>}<br><br>final RouteObserver&lt;PageRoute&gt; routeObserver = RouteObserver&lt;PageRoute&gt;();<br><br>MaterialApp(<br>  navigatorObservers: [routeObserver],<br>);</pre><p>. <strong>Relation to Observer Pattern:</strong> RouteObserver is the <strong>subject</strong>, and all registered routes are <strong>observers</strong>.</p><p>5. <strong>Stream &amp; StreamBuilder.</strong></p><ul><li>Stream allows data to be emitted asynchronously, and StreamBuilder listens for updates.</li><li>Commonly used for handling real-time data updates.</li></ul><pre>Stream&lt;int&gt; numberStream() async* {<br>  for (int i = 0; i &lt; 5; i++) {<br>    await Future.delayed(Duration(seconds: 1));<br>    yield i;<br>  }<br>}<br><br>StreamBuilder&lt;int&gt;(<br>  stream: numberStream(),<br>  builder: (context, snapshot) {<br>    if (snapshot.hasData) {<br>      return Text(&quot;Number: ${snapshot.data}&quot;);<br>    }<br>    return CircularProgressIndicator();<br>  },<br>);</pre><p>. <strong><em>Relation to Observer Pattern:</em></strong><em> </em><em>Stream is the </em><strong><em>subject</em></strong><em>, and </em><em>StreamBuilder is the </em><strong><em>observer</em></strong><em>.</em></p><p>6.<strong> Animation &amp; AnimationController (TickerProvider).</strong></p><ul><li>Flutter’s animation system is based on Listenable, making it observer-based.</li><li>AnimationController notifies listeners when the animation progresses.</li></ul><pre>AnimationController _controller = AnimationController(<br>  vsync: this,<br>  duration: Duration(seconds: 1),<br>)..addListener(() {<br>  setState(() {});  // Observer reacts to animation changes<br>});</pre><p>. <strong>Relation to Observer Pattern:</strong> AnimationController is the <strong>subject</strong>, and addListener() is the <strong>observer</strong>.</p><h4>5. The role of Observer Design Pattern in different State Management Solutions .</h4><ol><li><strong>Provider.</strong></li></ol><p><strong>Package:</strong> provider</p><ul><li><strong>Provider uses the Observer Pattern</strong> to notify UI components when data changes.</li><li><strong>ChangeNotifier</strong> is an implementation of the Observer Pattern where widgets subscribe to state changes.</li><li><strong>notifyListeners()</strong> is the method that updates all registered observers (listeners).</li></ul><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:provider/provider.dart&#39;;<br><br>// Observable: ChangeNotifier acts as Subject<br>class CounterModel extends ChangeNotifier {<br>  int _count = 0;<br>  int get count =&gt; _count;<br><br>  void increment() {<br>    _count++;<br>    notifyListeners(); // Notifies all Observers (listening widgets)<br>  }<br>}<br><br>void main() {<br>  runApp(<br>    ChangeNotifierProvider(<br>      create: (context) =&gt; CounterModel(),<br>      child: MyApp(),<br>    ),<br>  );<br>}<br><br>class MyApp extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      home: CounterScreen(),<br>    );<br>  }<br>}<br><br>class CounterScreen extends StatelessWidget {<br>  @override<br>  Widget build(BuildContext context) {<br>    final counter = Provider.of&lt;CounterModel&gt;(context);<br><br>    return Scaffold(<br>      appBar: AppBar(title: Text(&#39;Observer Pattern with Provider&#39;)),<br>      body: Center(child: Text(&#39;Count: ${counter.count}&#39;)),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: counter.increment,<br>        child: Icon(Icons.add),<br>      ),<br>    );<br>  }<br>}</pre><ul><li><strong>Observer Pattern</strong> is a fundamental design pattern that <strong>Provider</strong> utilizes.</li><li><strong>Provider + ChangeNotifier</strong> follow the same principle: when state changes, all subscribed widgets (observers) are updated automatically.</li><li>This makes <strong>Provider an efficient way to implement the Observer Pattern in Flutter</strong>.</li></ul><p>2. <strong>Riverpod.</strong></p><p><strong>Package:</strong> flutter_riverpod</p><ul><li>Similar to Provider, but offers a more scalable, global state management approach.</li><li>Uses <strong>notifiers</strong> and <strong>listeners</strong> to automatically rebuild UI when state changes.</li></ul><pre>final counterProvider = StateNotifierProvider&lt;CounterNotifier, int&gt;((ref) {<br>  return CounterNotifier();<br>});<br><br>class CounterNotifier extends StateNotifier&lt;int&gt; {<br>  CounterNotifier() : super(0);<br><br>  void increment() =&gt; state++;<br>}</pre><p>. <strong>Relation to Observer Pattern:</strong> StateNotifier is the <strong>subject</strong>, and UI widgets listening to counterProvider are <strong>observers</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=214ce2f5e0d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Google Maps in Flutter]]></title>
            <link>https://medium.com/@mo7amedaliebaid/advanced-google-maps-in-flutter-790c7a1be614?source=rss-dc3945c088ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/790c7a1be614</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[google-maps]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[google-maps-api]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <dc:creator><![CDATA[Moamedaliebaid]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 22:27:36 GMT</pubDate>
            <atom:updated>2024-11-04T15:52:55.183Z</atom:updated>
            <content:encoded><![CDATA[<p>Flutter makes it easy to integrate Google Maps into your apps, but taking it a step further with advanced features can enhance the user experience significantly. Here’s how to implement tap-to-address, custom markers, place search, and custom map styles in a Flutter app.</p><ul><li><strong>The Dependencies we would use through this article</strong></li></ul><pre>dependencies:<br>  google_maps_flutter: ^2.0.10<br>  geolocator: ^9.0.2<br>  geocoding: ^2.0.1<br>  dio: ^4.0.4</pre><ol><li><strong>Applying a Custom Map Style</strong></li></ol><p>To apply a custom style to the map, add a JSON file containing the style<br> (download from <a href="https://mapstyle.withgoogle.com/">Google Maps Styling Wizard</a>) and load it into the map controller.</p><ul><li>Ex. for JSON file containing the style.</li></ul><pre>[<br>  {<br>    &quot;featureType&quot;: &quot;water&quot;,<br>    &quot;elementType&quot;: &quot;geometry&quot;,<br>    &quot;stylers&quot;: [<br>      {<br>        &quot;color&quot;: &quot;#00A9E5&quot;<br>      }<br>    ]<br>  },<br>  {<br>    &quot;featureType&quot;: &quot;landscape&quot;,<br>    &quot;elementType&quot;: &quot;geometry&quot;,<br>    &quot;stylers&quot;: [<br>      {<br>        &quot;color&quot;: &quot;#FFFFFF&quot;<br>      }<br>    ]<br>  },<br>  {<br>    &quot;featureType&quot;: &quot;road&quot;,<br>    &quot;elementType&quot;: &quot;geometry&quot;,<br>    &quot;stylers&quot;: [<br>      {<br>        &quot;color&quot;: &quot;#00A9E5&quot;<br>      },<br>      {<br>        &quot;visibility&quot;: &quot;on&quot;<br>      }<br>    ]<br>  },<br>  {<br>    &quot;featureType&quot;: &quot;road&quot;,<br>    &quot;elementType&quot;: &quot;geometry.stroke&quot;,<br>    &quot;stylers&quot;: [<br>      {<br>        &quot;visibility&quot;: &quot;on&quot;<br>      },<br>      {<br>        &quot;color&quot;: &quot;#006F99&quot;<br>      },<br>      {<br>        &quot;weight&quot;: 0.5<br>      }<br>    ]<br>  },<br>  {<br>    &quot;featureType&quot;: &quot;road.highway&quot;,<br>    &quot;elementType&quot;: &quot;geometry&quot;,<br>    &quot;stylers&quot;: [<br>      {<br>        &quot;color&quot;: &quot;#00A9E5&quot;<br>      },<br>      {<br>        &quot;weight&quot;: 0.8<br>      }<br>    ]<br>  },<br>  {<br>    &quot;featureType&quot;: &quot;poi&quot;,<br>    &quot;elementType&quot;: &quot;geometry&quot;,<br>    &quot;stylers&quot;: [<br>      {<br>        &quot;color&quot;: &quot;#A3E8F1&quot;<br>      }<br>    ]<br>  },<br>  {<br>    &quot;featureType&quot;: &quot;poi.park&quot;,<br>    &quot;elementType&quot;: &quot;geometry&quot;,<br>    &quot;stylers&quot;: [<br>      {<br>        &quot;color&quot;: &quot;#88D2D8&quot;<br>      }<br>    ]<br>  },<br>  {<br>    &quot;featureType&quot;: &quot;transit.line&quot;,<br>    &quot;elementType&quot;: &quot;geometry&quot;,<br>    &quot;stylers&quot;: [<br>      {<br>        &quot;color&quot;: &quot;#00A9E5&quot;,<br>        &quot;visibility&quot;: &quot;on&quot;<br>      },<br>      {<br>        &quot;weight&quot;: 0.5<br>      }<br>    ]<br>  },<br>  {<br>    &quot;featureType&quot;: &quot;administrative.land_parcel&quot;,<br>    &quot;elementType&quot;: &quot;geometry.stroke&quot;,<br>    &quot;stylers&quot;: [<br>      {<br>        &quot;color&quot;: &quot;#00A9E5&quot;,<br>        &quot;visibility&quot;: &quot;on&quot;<br>      },<br>      {<br>        &quot;weight&quot;: 0.5<br>      }<br>    ]<br>  },<br>  {<br>    &quot;featureType&quot;: &quot;administrative&quot;,<br>    &quot;elementType&quot;: &quot;geometry&quot;,<br>    &quot;stylers&quot;: [<br>      {<br>        &quot;visibility&quot;: &quot;on&quot;,<br>        &quot;color&quot;: &quot;#00A9E5&quot;<br>      }<br>    ]<br>  },<br>  {<br>    &quot;featureType&quot;: &quot;administrative.neighborhood&quot;,<br>    &quot;elementType&quot;: &quot;labels.text.fill&quot;,<br>    &quot;stylers&quot;: [<br>      {<br>        &quot;color&quot;: &quot;#00A9E5&quot;<br>      }<br>    ]<br>  },<br>  {<br>    &quot;featureType&quot;: &quot;road.local&quot;,<br>    &quot;elementType&quot;: &quot;geometry&quot;,<br>    &quot;stylers&quot;: [<br>      {<br>        &quot;color&quot;: &quot;#00A9E5&quot;<br>      },<br>      {<br>        &quot;weight&quot;: 0.5<br>      }<br>    ]<br>  }<br><br>]</pre><ul><li>Code Snippet</li></ul><pre>import &#39;package:flutter/services.dart&#39; show rootBundle;<br><br>class CustomMapStyleMap extends StatefulWidget {<br>  @override<br>  _CustomMapStyleMapState createState() =&gt; _CustomMapStyleMapState();<br>}<br><br>class _CustomMapStyleMapState extends State&lt;CustomMapStyleMap&gt; {<br>  late GoogleMapController _mapController;<br><br>  Future&lt;void&gt; _setMapStyle() async {<br>    String style = await rootBundle.loadString(&#39;assets/map_style.json&#39;);<br>    _mapController.setMapStyle(style);<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&#39;Custom Map Style&#39;)),<br>      body: GoogleMap(<br>        onMapCreated: (controller) {<br>          _mapController = controller;<br>          _setMapStyle();<br>        },<br>        initialCameraPosition: CameraPosition(<br>          target: LatLng(37.7749, -122.4194),<br>          zoom: 14.0,<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*MwpoA8O26Wk3WHo4FGmZWw.jpeg" /></figure><p><strong>2. Getting Address on Map Tap.</strong><br>You can allow users to tap on the map and retrieve the address at that location using geocoding:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:google_maps_flutter/google_maps_flutter.dart&#39;;<br>import &#39;package:geocoding/geocoding.dart&#39;;<br><br>class TapToAddressMap extends StatefulWidget {<br>  @override<br>  _TapToAddressMapState createState() =&gt; _TapToAddressMapState();<br>}<br><br>class _TapToAddressMapState extends State&lt;TapToAddressMap&gt; {<br>  late GoogleMapController _mapController;<br>  String? _address;<br><br>  Future&lt;void&gt; _getAddressFromLatLng(LatLng position) async {<br>    List&lt;Placemark&gt; placemarks = await placemarkFromCoordinates(<br>      position.latitude,<br>      position.longitude,<br>    );<br>    setState(() {<br>      _address = &#39;${placemarks.first.street}, ${placemarks.first.locality}&#39;;<br>    });<br>  }<br><br>  void _onMapTap(LatLng tappedPoint) {<br>    _getAddressFromLatLng(tappedPoint);<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&#39;Tap to Get Address&#39;)),<br>      body: Stack(<br>        children: [<br>          GoogleMap(<br>            onMapCreated: (controller) =&gt; _mapController = controller,<br>            initialCameraPosition: CameraPosition(<br>              target: LatLng(37.7749, -122.4194), // San Francisco example<br>              zoom: 14.0,<br>            ),<br>            onTap: _onMapTap,<br>          ),<br>          if (_address != null)<br>            Positioned(<br>              bottom: 50,<br>              left: 15,<br>              right: 15,<br>              child: Container(<br>                padding: const EdgeInsets.all(12.0),<br>                color: Colors.white,<br>                child: Text(_address ?? &#39;Tap on map to get address&#39;),<br>              ),<br>            ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*hEQzOgEb0TFsBCxPDOjDrw.jpeg" /></figure><p><strong>3. Adding Custom Markers</strong><br>Custom markers make maps more engaging. Load custom icons from assets using BitmapDescriptor.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:google_maps_flutter/google_maps_flutter.dart&#39;;<br><br>class CustomMarkersMap extends StatefulWidget {<br>  @override<br>  _CustomMarkersMapState createState() =&gt; _CustomMarkersMapState();<br>}<br><br>class _CustomMarkersMapState extends State&lt;CustomMarkersMap&gt; {<br>  late GoogleMapController _mapController;<br>  BitmapDescriptor? _customMarker;<br><br>  Future&lt;void&gt; _loadCustomMarker() async {<br>    _customMarker = await BitmapDescriptor.fromAssetImage(<br>      ImageConfiguration(size: Size(48, 48)),<br>      &#39;assets/images/custom_marker.png&#39;,<br>    );<br>  }<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _loadCustomMarker();<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&#39;Custom Markers&#39;)),<br>      body: GoogleMap(<br>        onMapCreated: (controller) =&gt; _mapController = controller,<br>        initialCameraPosition: CameraPosition(<br>          target: LatLng(37.7749, -122.4194),<br>          zoom: 14.0,<br>        ),<br>        markers: {<br>          if (_customMarker != null)<br>            Marker(<br>              markerId: MarkerId(&#39;customMarker&#39;),<br>              position: LatLng(37.7749, -122.4194),<br>              icon: _customMarker!,<br>              infoWindow: InfoWindow(title: &#39;Custom Marker&#39;),<br>            ),<br>        },<br>      ),<br>    );<br>  }<br>}</pre><p>This snippet loads a custom marker icon from assets. Make sure the asset path (assets/images/custom_marker.png) is added to your pubspec.yaml under assets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*eu0zTEYD961kVpncvlGl7w.jpeg" /></figure><h4>4. Searching Places Using Google Places API</h4><p>To search for places within a specific radius, use Google’s Places API and Dio for HTTP requests:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:dio/dio.dart&#39;;<br><br>class PlacesSearch extends StatefulWidget {<br>  @override<br>  _PlacesSearchState createState() =&gt; _PlacesSearchState();<br>}<br><br>class _PlacesSearchState extends State&lt;PlacesSearch&gt; {<br>  final TextEditingController _searchController = TextEditingController();<br>  final String _apiKey = &#39;YOUR_GOOGLE_API_KEY&#39;;<br>  List&lt;dynamic&gt; _places = [];<br><br>  Future&lt;void&gt; _searchPlaces(String query) async {<br>    const url = &#39;https://maps.googleapis.com/maps/api/place/autocomplete/json&#39;;<br>    final params = {<br>      &#39;input&#39;: query,<br>      &#39;key&#39;: _apiKey,<br>      &#39;location&#39;: &#39;37.7749,-122.4194&#39;, // Current lat, long example<br>      &#39;radius&#39;: &#39;50000&#39;,<br>    };<br><br>    try {<br>      var response = await Dio().get(url, queryParameters: params);<br>      setState(() {<br>        _places = response.data[&#39;predictions&#39;];<br>      });<br>    } catch (e) {<br>      setState(() {<br>        _places = [];<br>      });<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: const Text(&#39;Search Places&#39;)),<br>      body: Column(<br>        children: [<br>          TextField(<br>            controller: _searchController,<br>            decoration: const InputDecoration(<br>              labelText: &#39;Search for places&#39;,<br>            ),<br>            onChanged: (value) =&gt; _searchPlaces(value),<br>          ),<br>          Expanded(<br>            child: ListView.builder(<br>              itemCount: _places.length,<br>              itemBuilder: (context, index) {<br>                final place = _places[index];<br>                return ListTile(<br>                  title: Text(place[&#39;description&#39;]),<br>                );<br>              },<br>            ),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><p>This code allows users to type a place name, and results are displayed as a list. You can customize this to perform further actions, like moving the map to the selected place.</p><p><strong>5. Nearby Marker Clustering</strong></p><h4>Use Cases for Adding Custom Markers Around a Location</h4><ol><li><strong>Event Check-ins</strong>: Let users view multiple check-in points for an event within walking distance.</li><li><strong>Business Locations</strong>: Display multiple branch locations of a business within a neighborhood.</li><li><strong>Nearby Amenities</strong>: Highlight nearby amenities, like ATMs, stores, or restaurants, relative to a user’s current location.</li></ol><pre>// Import necessary packages<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:google_maps_flutter/google_maps_flutter.dart&#39;;<br>import &#39;package:geolocator/geolocator.dart&#39;;<br>import &#39;package:flutter/services.dart&#39; show rootBundle;<br>import &#39;package:permission_handler/permission_handler.dart&#39;;<br><br>class MapScreen extends StatefulWidget {<br>  const MapScreen({super.key});<br><br>  @override<br>  State&lt;MapScreen&gt; createState() =&gt; _MapScreenState();<br>}<br><br>class _MapScreenState extends State&lt;MapScreen&gt; {<br>  late GoogleMapController _mapController;<br>  final List&lt;Marker&gt; _markers = [];<br>  BitmapDescriptor? _customMarker;<br>  BitmapDescriptor? _largeCurrentLocationMarker;<br><br>  LatLng? _currentPosition;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _initializeMap();<br>  }<br><br>  Future&lt;void&gt; _initializeMap() async {<br>    await _checkLocationPermission();<br><br>    if (_currentPosition != null) {<br>      await _loadCustomMarkers();<br>      _addMarkersNearby(); // Add markers around the current location<br>      _loadMapStyle(); // Load and apply the map style<br>    }<br>  }<br><br>  // Load custom markers from assets<br>  Future&lt;void&gt; _loadCustomMarkers() async {<br>    _customMarker = await BitmapDescriptor.fromAssetImage(<br>      const ImageConfiguration(size: Size(100, 100)),<br>      &#39;assets/images/map_pin.png&#39;,<br>    );<br>    _largeCurrentLocationMarker = await BitmapDescriptor.fromAssetImage(<br>      const ImageConfiguration(size: Size(120, 120)),<br>      &#39;assets/images/map_pin.png&#39;,<br>    );<br>  }<br><br>  // Load the map style from assets<br>  Future&lt;void&gt; _loadMapStyle() async {<br>    String style = await rootBundle.loadString(&#39;assets/jsons/map_style.json&#39;);<br>    _mapController.setMapStyle(style);<br>  }<br><br>  // Check location permission<br>  Future&lt;void&gt; _checkLocationPermission() async {<br>    if (await Permission.location.isGranted) {<br>      await _addCurrentLocationMarker();<br>    } else {<br>      PermissionStatus status = await Permission.location.request();<br>      if (status.isGranted) {<br>        await _addCurrentLocationMarker();<br>      } else {<br>        ScaffoldMessenger.of(context).showSnackBar(<br>          const SnackBar(<br>            content: Text(&#39;Location permission is required to use this feature.&#39;),<br>          ),<br>        );<br>      }<br>    }<br>  }<br><br>  // Add the current location marker<br>  Future&lt;void&gt; _addCurrentLocationMarker() async {<br>    Position position = await Geolocator.getCurrentPosition(<br>        desiredAccuracy: LocationAccuracy.high);<br><br>    _currentPosition = LatLng(position.latitude, position.longitude);<br><br>    setState(() {<br>      _markers.add(<br>        Marker(<br>          markerId: const MarkerId(&#39;current_location&#39;),<br>          position: _currentPosition!,<br>          icon: _largeCurrentLocationMarker ?? BitmapDescriptor.defaultMarker,<br>        ),<br>      );<br>    });<br><br>    // Move camera to the current location<br>    _mapController.animateCamera(CameraUpdate.newLatLng(_currentPosition!));<br>  }<br><br>  // Add markers around the current location<br>  void _addMarkersNearby() {<br>    if (_currentPosition == null) return;<br><br>    setState(() {<br>      _markers.addAll([<br>        Marker(<br>          markerId: const MarkerId(&#39;marker1&#39;),<br>          position: LatLng(_currentPosition!.latitude + 0.011,<br>              _currentPosition!.longitude + 0.011),<br>          icon: _customMarker ??<br>              BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueCyan),<br>        ),<br>        Marker(<br>          markerId: const MarkerId(&#39;marker2&#39;),<br>          position: LatLng(_currentPosition!.latitude - 0.011,<br>              _currentPosition!.longitude - 0.011),<br>          icon: _customMarker ??<br>              BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueCyan),<br>        ),<br>        Marker(<br>          markerId: const MarkerId(&#39;marker3&#39;),<br>          position: LatLng(_currentPosition!.latitude + 0.012,<br>              _currentPosition!.longitude - 0.012),<br>          icon: _customMarker ??<br>              BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueCyan),<br>        ),<br>        Marker(<br>          markerId: const MarkerId(&#39;marker4&#39;),<br>          position: LatLng(_currentPosition!.latitude - 0.102,<br>              _currentPosition!.longitude + 0.102),<br>          icon: _customMarker ??<br>              BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueCyan),<br>        ),<br>      ]);<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: GoogleMap(<br>        initialCameraPosition: CameraPosition(<br>          target: _currentPosition ?? const LatLng(0, 0),<br>          zoom: 12,<br>        ),<br>        markers: Set&lt;Marker&gt;.of(_markers),<br>        onMapCreated: (controller) {<br>          _mapController = controller;<br>        },<br>      ),<br>    );<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*WXJmsRHt-OhxkRUw2OJjyg.jpeg" /></figure><p>Best Regards.<br><a href="https://github.com/mo7amedaliEbaid">Github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=790c7a1be614" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Custom Ticket-Shaped Widget in Flutter]]></title>
            <link>https://medium.com/@mo7amedaliebaid/building-a-custom-ticket-shaped-widget-in-flutter-517eb4283c4b?source=rss-dc3945c088ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/517eb4283c4b</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[clipping-path]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[custom-clipper]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Moamedaliebaid]]></dc:creator>
            <pubDate>Sat, 26 Oct 2024 19:40:04 GMT</pubDate>
            <atom:updated>2024-10-26T19:40:04.811Z</atom:updated>
            <content:encoded><![CDATA[<p>Building a Custom Ticket-Shaped Widget in Flutter</p><p>Ever needed to give a UI element a unique, eye-catching ticket shape in Flutter? This tutorial will guide you through creating a reusable, customizable ticket shape widget perfect for adding that special touch to your app’s design.</p><h3>Step 1: Setting Up a Custom Clipper for the Ticket Shape</h3><p>To achieve the ticket shape, we’ll leverage Flutter’s CustomClipper class. This class allows us to define any custom shape by manipulating the path in a way that standard Flutter shapes, like rounded rectangles or circles, can’t quite handle. Let’s start by defining a CustomTicketShape class to handle this clipping.</p><p>Here’s how it works:</p><pre>class CustomTicketShape extends CustomClipper&lt;Path&gt; {<br> final double borderRadius;<br>CustomTicketShape(this.borderRadius);<br>@override<br> Path getClip(Size size) {<br> final path = Path();<br> final radius = Radius.circular(borderRadius);<br>// Starting point for the clipping path<br> path.moveTo(0, size.height / 2–20);<br>// Create a curved edge on the left side of the ticket<br> path.quadraticBezierTo(<br> size.width * 0.10, size.height / 2, 0, size.height / 2 + 20);<br> <br> // Bottom left corner with rounded edge<br> path.lineTo(0, size.height - borderRadius);<br> path.arcToPoint(<br> Offset(borderRadius, size.height),<br> radius: radius,<br> clockwise: false,<br> );<br>// Bottom side and right corners<br> path.lineTo(size.width - borderRadius, size.height);<br> path.arcToPoint(<br> Offset(size.width, size.height - borderRadius),<br> radius: radius,<br> clockwise: false,<br> );<br>// Right-side curved notch<br> path.lineTo(size.width, size.height / 2 + 20);<br> path.quadraticBezierTo(<br> size.width * 0.90, size.height / 2, size.width, size.height / 2–20);<br>// Finish top edge with rounded corners<br> path.lineTo(size.width, borderRadius);<br> path.arcToPoint(<br> Offset(size.width - borderRadius, 0),<br> radius: radius,<br> clockwise: false,<br> );<br> path.lineTo(borderRadius, 0);<br> path.arcToPoint(<br> Offset(0, borderRadius),<br> radius: radius,<br> clockwise: false,<br> );<br>path.close();<br>return path;<br> }<br>@override<br> bool shouldReclip(CustomClipper&lt;Path&gt; oldClipper) =&gt; true;<br>}<br>This code defines a path that forms the ticket shape, <br>including rounded corners and a custom notch on each side, <br>which visually distinguishes the shape.</pre><p>Step 2: Creating a Border with CustomPainter</p><p>Next, let’s add a border to our ticket shape to make it stand out even more. To do this, we’ll create a CustomPainter class called TicketBorderPainter. It will use the same CustomTicketShape we just created to draw a border along the path.</p><pre>class TicketBorderPainter extends CustomPainter {<br>  @override<br>  void paint(Canvas canvas, Size size) {<br>    final path = CustomTicketShape(10).getClip(size); // Adjust borderRadius as needed<br>    final paint = Paint()<br>      ..color = Colors.blueAccent<br>      ..style = PaintingStyle.stroke<br>      ..strokeWidth = 3;<br><br>    canvas.drawPath(path, paint);<br>  }<br><br>  @override<br>  bool shouldRepaint(covariant CustomPainter oldDelegate) =&gt; false;<br>}<br><br>The TicketBorderPainter uses the CustomTicketShape to get the path,<br> then draws a stroke along this path with a custom width and color.</pre><p>Step 3: Putting It All Together in the OrderItemWidget</p><p>Now we’re ready to create our ticket component, OrderItemWidget, and apply the CustomTicketShape as its clipper. We’ll also overlay the TicketBorderPainter for that outlined effect.</p><pre>class OrderItemWidget extends StatelessWidget {<br>  const OrderItemWidget({Key? key}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Stack(<br>      children: [<br>        // Main ticket-shaped container<br>        ClipPath(<br>          clipper: CustomTicketShape(10),<br>          child: Container(<br>            height: 200,<br>            width: double.infinity,<br>            decoration: BoxDecoration(<br>              color: Colors.grey.shade300,<br>              borderRadius: BorderRadius.circular(10),<br>            ),<br>            padding: const EdgeInsets.all(20),<br>            child: Column(<br>              crossAxisAlignment: CrossAxisAlignment.start,<br>              children: [<br>                Text(&quot;Order ID: #12345&quot;),<br>                const SizedBox(height: 5),<br>                Text(&quot;Customer Name: John Doe&quot;),<br>                const SizedBox(height: 5),<br>                Text(&quot;Order Status: Pending&quot;),<br>              ],<br>            ),<br>          ),<br>        ),<br>        // Border for the ticket shape<br>        CustomPaint(<br>          size: Size(double.infinity, 200),<br>          painter: TicketBorderPainter(),<br>        ),<br>      ],<br>    );<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*ztdMYTZ_9Rev2M-gHXpQZw.png" /></figure><p>The OrderItemWidget now has the ticket shape and border applied to it. We use ClipPath to apply the shape, and then add the border with CustomPaint.</p><p>And there you have it! By combining CustomClipper, CustomPainter, and Stack, we’ve created a visually distinct ticket-shaped widget that can be reused across the app. This custom widget approach is a great way to create unique UI components that make your app stand out. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=517eb4283c4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Relationship Between LSP and Polymorphism]]></title>
            <link>https://medium.com/@mo7amedaliebaid/the-relationship-between-lsp-and-polymorphism-cbb5efd29488?source=rss-dc3945c088ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbb5efd29488</guid>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[liskov-substitution]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[Moamedaliebaid]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 20:16:15 GMT</pubDate>
            <atom:updated>2024-10-25T20:16:15.494Z</atom:updated>
            <content:encoded><![CDATA[<p>The Relationship Between LSP and Polymorphism</p><p>The Liskov Substitution Principle (LSP) and polymorphism are both concepts in object-oriented programming that focus on designing robust and flexible systems, but they serve slightly different purposes and are related in how they ensure proper behavior when substituting objects in a hierarchy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*alHP4C87J62gDZC_jqOrkw.jpeg" /></figure><p><strong>Polymorphism</strong> allows objects of different classes to be treated as objects of a common base class. It enables code to work with objects of various derived types through a single interface, often using methods that are overridden in subclasses. This allows for more flexible and reusable code, as the specific type of object can vary at runtime.</p><p><strong>Liskov Substitution Principle (LSP)</strong> states that objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program. In essence, a subclass should extend the behavior of its parent class without altering its expected behavior.</p><h3>How LSP Relates to Polymorphism</h3><p>Polymorphism provides a way to substitute objects of different classes, but LSP ensures that this substitution is <strong>safe and predictable</strong>. For example:</p><ul><li>When a subclass overrides a method from its superclass, LSP dictates that the new behavior should align with what the clients of the superclass expect.</li><li>Violating LSP often results in unexpected behaviors or errors when polymorphism is applied, as assumptions about how a superclass operates no longer hold for certain subclasses.</li></ul><p>In short, <strong>polymorphism enables substitution</strong>, while <strong>LSP ensures that the substitution behaves correctly</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbb5efd29488" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>