<?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 Joseph Onalo on Medium]]></title>
        <description><![CDATA[Stories by Joseph Onalo on Medium]]></description>
        <link>https://medium.com/@onalojoseph96?source=rss-a8e4cc5e0c43------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lCqnHweL7K3evJRi5_SJ4g.jpeg</url>
            <title>Stories by Joseph Onalo on Medium</title>
            <link>https://medium.com/@onalojoseph96?source=rss-a8e4cc5e0c43------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:15:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@onalojoseph96/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[Implementing FCM Push Notifications in Flutter (Android & iOS)— The Complete Guide]]></title>
            <link>https://medium.com/@onalojoseph96/implementing-fcm-push-notifications-in-flutter-android-ios-the-complete-guide-65a4ee7055f1?source=rss-a8e4cc5e0c43------2</link>
            <guid isPermaLink="false">https://medium.com/p/65a4ee7055f1</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[fcm-push-notification]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Joseph Onalo]]></dc:creator>
            <pubDate>Fri, 12 Jun 2026 22:41:56 GMT</pubDate>
            <atom:updated>2026-06-13T09:10:38.948Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X5elfSAFpAGVoCWFIs_Blw.png" /></figure><p><em>From Firebase project setup to background handlers and deep links — everything you need to send push notifications to your Flutter app on iOS and Android.</em></p><p>Push notifications are one of the highest-leverage features you can add to a mobile app. Done right, they bring users back, drive engagement, and deliver timely information exactly when it matters. Done wrong, they get your app deleted.</p><p>This guide covers the full implementation of Firebase Cloud Messaging (FCM) in Flutter — from creating your Firebase project to handling notifications in every app state, including foreground, background, and terminated. By the end, you’ll have a production-ready notification system that works on both iOS and Android.</p><h3>What is FCM and Why Use It?</h3><p>Firebase Cloud Messaging is Google’s free, cross-platform messaging solution. It handles the heavy lifting of delivering messages reliably to devices, even when the app isn’t running. For Flutter developers, it’s the de facto standard for push notifications because:</p><ul><li>It works on both iOS and Android with a single codebase</li><li>It’s free with no meaningful limits for most apps</li><li>It integrates natively with other Firebase services like Analytics and Remote Config</li><li>The firebase_messaging Flutter package is well-maintained and production-tested</li></ul><p>The architecture is straightforward: your backend (or Firebase Console) sends a message to FCM servers, which deliver it to the target device via APNs (iOS) or FCM’s own transport layer (Android).</p><h3>Prerequisites</h3><p>Before writing any Flutter code, you need three things in place:</p><ul><li>A Firebase project (free at console.firebase.google.com)</li><li>For iOS: an Apple Developer account with push notification entitlements configured</li><li>Flutter 3.0+ with a project targeting iOS 13+ and Android API 21+</li></ul><h3>Step 1 — Firebase Project Setup</h3><p>Head to the Firebase Console and create a new project (or use an existing one). Once inside:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Ek731B1m3xhdR3PiSPVDQ.png" /></figure><p><strong>For Android</strong>, click “Add app”, select Android, and enter your package name (e.g., com.yourcompany.yourapp). Download the google-services.json file and place it in android/app/ directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDvQ0_XcXnSoWKTXJzEdIg.png" /></figure><p><strong>For iOS</strong>, add an iOS app with your Bundle ID. Download GoogleService-Info.plist and add it to the ios/Runner/ directory via Xcode — not by dragging it into the folder directly, or the build will fail. What this means is that, you should open your project via Xcode then add the GoogleService-Info.plist and add it to the ios/Runner/ directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s-i65JCZq9nxmNE_RB5egQ.png" /></figure><h3>Step 2 — APNs Configuration (iOS Only)</h3><p>This is the step that trips up most developers. FCM on iOS rides on top of Apple Push Notification service (APNs), which means you need to give Firebase permission to send notifications on your behalf.</p><p>In your Apple Developer account:</p><p><em>Note that you must have purchased an Apple Developer Account before you can proceed for iOS.</em></p><p>Go to <strong>Certificates, Identifiers &amp; Profiles → Keys</strong> and create a new key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vLvdnURILg7h4EEXO72Tng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0JxFURD-BezYeb1aBOrfnA.png" /></figure><p>Enable <strong>Apple Push Notifications service (APNs)</strong> and click on configure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uRGdU-JYvkV6GnsEz3PJ3Q.png" /></figure><p>You are allowed to select an environment for your key , sandbox, production or one key for both. Select an option and save.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aKQyXy9GJzjDVtg3XvUZ9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PkNrToV4WR5nOQ1z8USfKg.png" /></figure><p>Register the key and download the .p8 file. You can only download this once — sop keep it safe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w__KeyGqhI8p2vWa8zDWRQ.png" /></figure><p>Then in Firebase Console, go to <strong>Project Settings → Cloud Messaging → Apple app configuration</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jeT34ZaK4LTw2_5Thndf8w.png" /></figure><p>and upload the .p8 key along with your Key ID and Team ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6estltBm49avO2sUc9AH8A.png" /></figure><p>Also enable Push Notifications and Background Modes in Xcode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gNZRLVGaqtb785w9TaUSng.png" /></figure><p>Incase they are not part of the list of capabilities, go to your Runner target → <strong>Signing &amp; Capabilities</strong> → click <strong>+ Capability</strong> and add both &quot;Push Notifications&quot; and &quot;Background Modes&quot;. Under Background Modes, check &quot;Remote notifications&quot;.</p><h3>Step 3 — Flutter Package Setup</h3><p>Add the required packages to pubspec.yaml:</p><pre>dependencies:<br>  firebase_core: ^2.27.0<br>  firebase_messaging: ^14.7.19<br>  flutter_local_notifications: ^17.0.0  # for foreground notification display on Android</pre><p>Run flutter pub get.</p><p>Now initialize Firebase in main.dart. This must be done before any other Firebase calls:</p><pre>import &#39;package:firebase_core/firebase_core.dart&#39;;<br>import &#39;package:firebase_messaging/firebase_messaging.dart&#39;;<br>import &#39;firebase_options.dart&#39;; // generated by FlutterFire CLI</pre><pre>// Top-level background message handler<br>// Must be a top-level function, NOT a class method<br>@pragma(&#39;vm:entry-point&#39;)<br>Future&lt;void&gt; _firebaseMessagingBackgroundHandler(RemoteMessage message) async {<br>  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);<br>  debugPrint(&#39;Background message: ${message.messageId}&#39;);<br>  // Handle your background logic here<br>}</pre><pre>Future&lt;void&gt; main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);<br>  <br>  // Register background handler BEFORE runApp<br>  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);<br>  <br>  runApp(const MyApp());<br>}</pre><blockquote><strong>⚠️ Critical:</strong> The background message handler must be a top-level function — not a static method, not inside a class. Flutter spawns a separate isolate for background processing, and only top-level functions are accessible across isolates.</blockquote><h3>Step 4 — Requesting Permissions</h3><p>On iOS, push notifications require explicit user permission. On Android 13+, they do too. Always request permission at a moment when the user understands why — not on first launch with zero context.</p><pre>class NotificationService {<br>  static final _messaging = FirebaseMessaging.instance;</pre><pre>  static Future&lt;bool&gt; requestPermission() async {<br>    final settings = await _messaging.requestPermission(<br>      alert: true,<br>      badge: true,<br>      sound: true,<br>      provisional: false, // true = silent delivery without prompting<br>    );</pre><pre>    final granted = settings.authorizationStatus == AuthorizationStatus.authorized<br>        || settings.authorizationStatus == AuthorizationStatus.provisional;</pre><pre>    debugPrint(&#39;Notification permission: ${settings.authorizationStatus}&#39;);<br>    return granted;<br>  }<br>}</pre><p>A good pattern is to show your own “pre-permission” screen first — explaining the value of notifications — before triggering the system dialog. You only get one shot at the system prompt. If the user denies it, they have to go to Settings manually to re-enable it.</p><h3>Step 5 — Getting the FCM Token</h3><p>The FCM token is the unique address of a device. Your backend needs this token to send notifications to a specific user. Fetch and store it after permission is granted:</p><pre>static Future&lt;String?&gt; getToken() async {<br>  // On iOS, getToken() implicitly requests APNs token first<br>  final token = await _messaging.getToken();<br>  debugPrint(&#39;FCM Token: $token&#39;);<br>  return token;<br>}</pre><pre>// Tokens can rotate — always listen for refreshes<br>static void listenForTokenRefresh() {<br>  _messaging.onTokenRefresh.listen((newToken) {<br>    debugPrint(&#39;FCM Token refreshed: $newToken&#39;);<br>    // Send newToken to your backend to update the stored token<br>    _sendTokenToBackend(newToken);<br>  });<br>}</pre><blockquote><strong>💡 Tip:</strong> Tokens rotate when the user reinstalls the app, restores from a backup, or clears app data. If you don’t handle onTokenRefresh, you&#39;ll silently lose the ability to reach that user.</blockquote><h3>Step 6 — Handling Messages in Every App State</h3><p>This is the heart of FCM implementation. Messages behave differently depending on whether your app is in the foreground, background, or fully terminated. You need to handle all three.</p><pre>class NotificationHandler {<br>  static Future&lt;void&gt; initialize() async {<br>    // 1. FOREGROUND — app is open and in focus<br>    FirebaseMessaging.onMessage.listen((RemoteMessage message) {<br>      debugPrint(&#39;Foreground message: ${message.notification?.title}&#39;);<br>      // FCM does NOT show a system notification when app is in foreground<br>      // You must show it manually using flutter_local_notifications<br>      _showLocalNotification(message);<br>    });</pre><pre>    // 2. BACKGROUND TAP — app was in background, user tapped notification<br>    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {<br>      debugPrint(&#39;User tapped background notification&#39;);<br>      _handleNotificationTap(message);<br>    });</pre><pre>    // 3. TERMINATED TAP — app was closed, user tapped notification to open it<br>    final initialMessage = await FirebaseMessaging.instance.getInitialMessage();<br>    if (initialMessage != null) {<br>      debugPrint(&#39;App opened from terminated state via notification&#39;);<br>      _handleNotificationTap(initialMessage);<br>    }<br>  }</pre><pre>  static void _handleNotificationTap(RemoteMessage message) {<br>    final data = message.data;<br>    // Route to the correct screen based on notification data<br>    // e.g., data[&#39;screen&#39;] == &#39;chat&#39; -&gt; navigate to chat screen<br>    // e.g., data[&#39;postId&#39;] -&gt; navigate to that post<br>  }<br>}</pre><p>Call NotificationHandler.initialize() inside your root widget&#39;s initState — after Firebase is initialized and permissions are granted.</p><h3>Step 7 — Showing Foreground Notifications on Android</h3><p>By default, FCM suppresses system notification banners when your app is in the foreground on Android. You need flutter_local_notifications to show them manually:</p><pre>import &#39;package:flutter_local_notifications/flutter_local_notifications.dart&#39;;</pre><pre>final FlutterLocalNotificationsPlugin _localNotifications =<br>    FlutterLocalNotificationsPlugin();</pre><pre>Future&lt;void&gt; _initLocalNotifications() async {<br>  const androidSettings = AndroidInitializationSettings(&#39;@mipmap/ic_launcher&#39;);<br>  const iosSettings = DarwinInitializationSettings();<br>  <br>  await _localNotifications.initialize(<br>    const InitializationSettings(<br>      android: androidSettings,<br>      iOS: iosSettings,<br>    ),<br>    onDidReceiveNotificationResponse: (response) {<br>      // Handle tap on local notification<br>      debugPrint(&#39;Local notification tapped: ${response.payload}&#39;);<br>    },<br>  );</pre><pre>  // Create the notification channel (Android 8+)<br>  const channel = AndroidNotificationChannel(<br>    &#39;high_importance_channel&#39;,<br>    &#39;High Importance Notifications&#39;,<br>    importance: Importance.high,<br>    playSound: true,<br>  );</pre><pre>  await _localNotifications<br>      .resolvePlatformSpecificImplementation<br>          AndroidFlutterLocalNotificationsPlugin&gt;()<br>      ?.createNotificationChannel(channel);<br>}</pre><pre>void _showLocalNotification(RemoteMessage message) {<br>  final notification = message.notification;<br>  if (notification == null) return;</pre><pre>  _localNotifications.show(<br>    notification.hashCode,<br>    notification.title,<br>    notification.body,<br>    NotificationDetails(<br>      android: AndroidNotificationDetails(<br>        &#39;high_importance_channel&#39;,<br>        &#39;High Importance Notifications&#39;,<br>        icon: &#39;@mipmap/ic_launcher&#39;,<br>        importance: Importance.high,<br>        priority: Priority.high,<br>      ),<br>      iOS: const DarwinNotificationDetails(),<br>    ),<br>    payload: jsonEncode(message.data), // pass data through for tap handling<br>  );<br>}</pre><h3>Step 8 — Deep Linking from Notifications</h3><p>The real power of notifications is taking users exactly where they need to go. Use the data payload to encode routing information:</p><pre>// What your backend sends in the FCM payload:<br>// {<br>//   &quot;notification&quot;: { &quot;title&quot;: &quot;New message&quot;, &quot;body&quot;: &quot;Jake: Hey!&quot; },<br>//   &quot;data&quot;: {<br>//     &quot;screen&quot;: &quot;chat&quot;,<br>//     &quot;chatId&quot;: &quot;abc123&quot;,<br>//     &quot;userId&quot;: &quot;xyz789&quot;<br>//   }<br>// }</pre><pre>static void _handleNotificationTap(RemoteMessage message) {<br>  final data = message.data;<br>  final screen = data[&#39;screen&#39;];</pre><pre>  switch (screen) {<br>    case &#39;chat&#39;:<br>      navigatorKey.currentState?.pushNamed(<br>        &#39;/chat&#39;,<br>        arguments: {&#39;chatId&#39;: data[&#39;chatId&#39;]},<br>      );<br>      break;<br>    case &#39;post&#39;:<br>      navigatorKey.currentState?.pushNamed(<br>        &#39;/post&#39;,<br>        arguments: {&#39;postId&#39;: data[&#39;postId&#39;]},<br>      );<br>      break;<br>    case &#39;profile&#39;:<br>      navigatorKey.currentState?.pushNamed(&#39;/profile&#39;);<br>      break;<br>    default:<br>      navigatorKey.currentState?.pushNamed(&#39;/home&#39;);<br>  }<br>}</pre><p>Use a global navigatorKey so you can navigate from outside the widget tree:</p><pre>// In main.dart<br>final GlobalKey&lt;NavigatorState&gt; navigatorKey = GlobalKey&lt;NavigatorState&gt;();</pre><pre>// Pass it to MaterialApp<br>MaterialApp(<br>  navigatorKey: navigatorKey,<br>  // ...<br>)</pre><h3>Step 9 — Topic Subscriptions</h3><p>Instead of managing individual device tokens for broadcast messages, use FCM Topics. Users subscribe to topics and you send one message that FCM fans out to all subscribers:</p><pre>class TopicService {<br>  // Subscribe user to a topic<br>  static Future&lt;void&gt; subscribe(String topic) async {<br>    await FirebaseMessaging.instance.subscribeToTopic(topic);<br>    debugPrint(&#39;Subscribed to topic: $topic&#39;);<br>  }</pre><pre>  // Unsubscribe user from a topic<br>  static Future&lt;void&gt; unsubscribe(String topic) async {<br>    await FirebaseMessaging.instance.unsubscribeFromTopic(topic);<br>    debugPrint(&#39;Unsubscribed from topic: $topic&#39;);<br>  }<br>}</pre><pre>// Usage examples:<br>// TopicService.subscribe(&#39;breaking_news&#39;);<br>// TopicService.subscribe(&#39;user_${userId}_alerts&#39;);<br>// TopicService.unsubscribe(&#39;promotions&#39;);</pre><p>Topics are perfect for news apps, sports scores, product restock alerts, or any broadcast-style notification. They scale to millions of subscribers with no backend work on your end.</p><h3>Step 10 — Sending a Test Notification</h3><p>Before integrating your backend, test using the Firebase Console:</p><p>Go to <strong>Firebase Console → Your Project → Messaging → Create your first campaign</strong>. Choose “Firebase Notification messages”, write a title and body, and target your app. Under “Additional options”, add a custom data key like screen with value home.</p><p>For a quick terminal test using curl:</p><pre>curl -X POST \<br>  https://fcm.googleapis.com/v1/projects/YOUR_PROJECT_ID/messages:send \<br>  -H &#39;Authorization: Bearer YOUR_ACCESS_TOKEN&#39; \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{<br>    &quot;message&quot;: {<br>      &quot;token&quot;: &quot;DEVICE_FCM_TOKEN&quot;,<br>      &quot;notification&quot;: {<br>        &quot;title&quot;: &quot;Hello from FCM&quot;,<br>        &quot;body&quot;: &quot;This is a test notification&quot;<br>      },<br>      &quot;data&quot;: {<br>        &quot;screen&quot;: &quot;home&quot;<br>      }<br>    }<br>  }&#39;</pre><h3>The Complete Notification Service</h3><p>Here’s everything consolidated into a single, reusable service class:</p><pre>import &#39;dart:convert&#39;;<br>import &#39;package:firebase_messaging/firebase_messaging.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_local_notifications/flutter_local_notifications.dart&#39;;</pre><pre>class NotificationService {<br>  static final _messaging = FirebaseMessaging.instance;<br>  static final _localNotifications = FlutterLocalNotificationsPlugin();<br>  static const _channelId = &#39;high_importance_channel&#39;;</pre><pre>  /// Call once at app startup, after Firebase.initializeApp()<br>  static Future&lt;void&gt; initialize() async {<br>    await _requestPermission();<br>    await _initLocalNotifications();<br>    await _setupTokenHandling();<br>    _registerHandlers();<br>  }</pre><pre>  static Future&lt;void&gt; _requestPermission() async {<br>    await _messaging.requestPermission(<br>      alert: true, badge: true, sound: true,<br>    );<br>  }</pre><pre>  static Future&lt;void&gt; _initLocalNotifications() async {<br>    await _localNotifications.initialize(<br>      const InitializationSettings(<br>        android: AndroidInitializationSettings(&#39;@mipmap/ic_launcher&#39;),<br>        iOS: DarwinInitializationSettings(),<br>      ),<br>    );</pre><pre>    await _localNotifications<br>        .resolvePlatformSpecificImplementation<br>            AndroidFlutterLocalNotificationsPlugin&gt;()<br>        ?.createNotificationChannel(<br>          const AndroidNotificationChannel(<br>            _channelId, &#39;High Importance Notifications&#39;,<br>            importance: Importance.high,<br>          ),<br>        );<br>  }</pre><pre>  static Future&lt;void&gt; _setupTokenHandling() async {<br>    final token = await _messaging.getToken();<br>    if (token != null) _sendTokenToBackend(token);<br>    _messaging.onTokenRefresh.listen(_sendTokenToBackend);<br>  }</pre><pre>  static void _registerHandlers() {<br>    // Foreground<br>    FirebaseMessaging.onMessage.listen(_showLocalNotification);</pre><pre>    // Background tap<br>    FirebaseMessaging.onMessageOpenedApp.listen(_handleTap);</pre><pre>    // Terminated tap<br>    _messaging.getInitialMessage().then((message) {<br>      if (message != null) _handleTap(message);<br>    });<br>  }</pre><pre>  static void _showLocalNotification(RemoteMessage message) {<br>    final n = message.notification;<br>    if (n == null) return;<br>    _localNotifications.show(<br>      n.hashCode, n.title, n.body,<br>      NotificationDetails(<br>        android: AndroidNotificationDetails(<br>          _channelId, &#39;High Importance Notifications&#39;,<br>          importance: Importance.high, priority: Priority.high,<br>        ),<br>        iOS: const DarwinNotificationDetails(),<br>      ),<br>      payload: jsonEncode(message.data),<br>    );<br>  }</pre><pre>  static void _handleTap(RemoteMessage message) {<br>    // Add your navigation logic here<br>    debugPrint(&#39;Notification tapped: ${message.data}&#39;);<br>  }</pre><pre>  static void _sendTokenToBackend(String token) {<br>    // POST token to your API<br>    debugPrint(&#39;Token to send to backend: $token&#39;);<br>  }<br>}</pre><h3>Common Pitfalls</h3><p><strong>1. Background handler not firing</strong> The @pragma(&#39;vm:entry-point&#39;) annotation is mandatory. Without it, the Dart tree shaker removes the function in release builds and background messages silently disappear.</p><p><strong>2. iOS notifications not showing in foreground</strong> FCM on iOS also suppresses foreground notifications by default. Add this to your AppDelegate.swift or use flutter_local_notifications as shown in Step 7.</p><p><strong>3. Token not refreshing</strong> Never cache an FCM token permanently. Always listen to onTokenRefresh and update your backend. A stale token means silent notification failure.</p><p><strong>4. Notification not navigating correctly from terminated state</strong> getInitialMessage() returns the message that launched the app. Call it after your navigation system is ready — not in main() before runApp.</p><p><strong>5. Missing android/app/google-services.json</strong> This causes a cryptic build failure. Double-check the file is in android/app/, not android/.</p><h3>Pre-Launch Checklist</h3><ul><li>FCM token fetched and sent to backend on first launch</li><li>onTokenRefresh listener registered and updating backend</li><li>Foreground notifications displaying via flutter_local_notifications</li><li>Background tap navigates to the correct screen</li><li>Terminated state tap navigates to the correct screen</li><li>Permission request shown at a contextual moment, not on cold launch</li><li>Tested on a real iOS device (simulator has limited APNs support)</li><li>Tested on Android 13+ (requires runtime notification permission)</li><li>Topic subscriptions and unsubscriptions working correctly</li><li>Background handler annotated with @pragma(&#39;vm:entry-point&#39;)</li></ul><h4>Wrapping Up</h4><blockquote>FCM push notifications in Flutter follow a clear pattern once you understand the three app states — foreground, background, and terminated — and handle each one explicitly. The firebase_messaging package covers the delivery layer, flutter_local_notifications fills the foreground gap on Android, and a global navigatorKey ties deep linking together cleanly.</blockquote><blockquote>The most common source of bugs isn’t the code — it’s configuration. The APNs key, the google-services.json placement, the @pragma annotation, the background handler being top-level — get those right and the rest falls into place.</blockquote><blockquote>Ship reliable notifications and your users will actually thank you for them.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65a4ee7055f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring a Next.js CRUD Application: Separating UI from Logic.]]></title>
            <link>https://medium.com/@onalojoseph96/refactoring-a-next-js-crud-application-separating-ui-from-logic-a3da733a0ff6?source=rss-a8e4cc5e0c43------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3da733a0ff6</guid>
            <dc:creator><![CDATA[Joseph Onalo]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 09:53:11 GMT</pubDate>
            <atom:updated>2025-03-17T09:54:36.390Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9yf0jnoCtmtGXA3M66NC7w.png" /></figure><h3><strong>Introduction</strong></h3><p>In modern React and Next.js development, a key architectural principle is the separation of concerns — particularly dividing UI components from business logic. While our original blog CRUD application works well, we can improve its maintainability and testability by refactoring it to better separate these concerns.</p><p>This post will walk through how to transform our monolithic components into a cleaner, more modular structure using custom hooks, dedicated UI components, and proper data abstraction.<a href="https://medium.com/@onalojoseph96/building-a-blog-crud-application-with-next-js-and-a-json-server-mock-server-ba1aefff703b"> Check my previous post here to see the previous structure</a></p><h3>Why Separate UI from Logic?</h3><p>Before diving into the refactoring, let’s understand the benefits:</p><ol><li><strong>Improved Testability</strong>: UI components and business logic can be tested independently</li><li><strong>Enhanced Reusability</strong>: Logic can be shared across multiple components</li><li><strong>Better Maintainability</strong>: Changes to either UI or logic have minimal impact on the other</li><li><strong>Cleaner Code</strong>: Components are more focused and easier to understand</li></ol><h3>Project Structure After Refactoring</h3><p>Our refactored project will follow this structure:</p><pre>/app<br>  /components<br>    /ui<br>      /PostTable.jsx       # UI-only table component<br>      /PostForm.jsx        # UI-only form component<br>      /PostView.jsx        # UI-only post display component<br>    /pages<br>      /PostsPage.jsx       # Container component for posts listing<br>      /CreatePostPage.jsx  # Container component for post creation<br>      /PostDetailPage.jsx  # Container component for post details<br>  /hooks<br>    /usePosts.js          # Custom hook for posts operations<br>    /usePostDetail.js     # Custom hook for individual post operations<br>  /services<br>    /api.js               # API service for server communication<br>  /page.js                # Main page entry point<br>  /post<br>    /create<br>      /page.js            # Create post entry point<br>    /[id]<br>      /page.js            # Post detail entry point</pre><h3>Step 1: Creating an API Service</h3><p>First, let’s extract all API calls into a dedicated service:</p><pre>// /services/api.js<br>import axios from &quot;axios&quot;;</pre><pre>const API_URL = &quot;http://localhost:5000&quot;;</pre><pre>export const postService = {<br>  getAllPosts: async () =&gt; {<br>    const response = await axios.get(`${API_URL}/posts`);<br>    return response.data;<br>  },<br>  <br>  getPostById: async (id) =&gt; {<br>    const response = await axios.get(`${API_URL}/posts/${id}`);<br>    return response.data;<br>  },<br>  <br>  createPost: async (postData) =&gt; {<br>    const response = await axios.post(`${API_URL}/posts`, postData);<br>    return response.data;<br>  },<br>  <br>  updatePost: async (id, postData) =&gt; {<br>    const response = await axios.patch(`${API_URL}/posts/${id}`, postData);<br>    return response.data;<br>  },<br>  <br>  deletePost: async (id) =&gt; {<br>    const response = await axios.delete(`${API_URL}/posts/${id}`);<br>    return response.data;<br>  }<br>};</pre><h3>Step 2: Creating Custom Hooks</h3><p>Now, let’s create custom hooks to encapsulate the business logic:</p><pre>// /hooks/usePosts.js<br>import { useState, useEffect } from &quot;react&quot;;<br>import { postService } from &quot;../services/api&quot;;</pre><pre>export function usePosts() {<br>  const [posts, setPosts] = useState([]);<br>  const [loading, setLoading] = useState(false);<br>  const [error, setError] = useState(null);</pre><pre>  const fetchPosts = async () =&gt; {<br>    setLoading(true);<br>    try {<br>      const data = await postService.getAllPosts();<br>      setPosts(data);<br>      setError(null);<br>    } catch (err) {<br>      setError(&quot;Failed to fetch posts&quot;);<br>      console.error(err);<br>    } finally {<br>      setLoading(false);<br>    }<br>  };</pre><pre>  useEffect(() =&gt; {<br>    fetchPosts();<br>  }, []);</pre><pre>  return {<br>    posts,<br>    loading,<br>    error,<br>    refreshPosts: fetchPosts<br>  };<br>}</pre><pre>// /hooks/usePostDetail.js<br>import { useState, useEffect } from &quot;react&quot;;<br>import { useRouter } from &quot;next/navigation&quot;;<br>import { postService } from &quot;../services/api&quot;;</pre><pre>export function usePostDetail(id, initialMode = &quot;read&quot;) {<br>  const router = useRouter();<br>  const [post, setPost] = useState(null);<br>  const [title, setTitle] = useState(&quot;&quot;);<br>  const [content, setContent] = useState(&quot;&quot;);<br>  const [mode, setMode] = useState(initialMode);<br>  const [loading, setLoading] = useState(false);<br>  const [error, setError] = useState(null);</pre><pre>  const fetchPost = async () =&gt; {<br>    setLoading(true);<br>    try {<br>      const data = await postService.getPostById(id);<br>      setPost(data);<br>      setTitle(data.title);<br>      setContent(data.content);<br>      setError(null);<br>    } catch (err) {<br>      setError(&quot;Failed to fetch post&quot;);<br>      console.error(err);<br>    } finally {<br>      setLoading(false);<br>    }<br>  };</pre><pre>  const updatePost = async (e) =&gt; {<br>    if (e) e.preventDefault();<br>    setLoading(true);<br>    try {<br>      await postService.updatePost(id, { title, content });<br>      setMode(&quot;read&quot;);<br>      await fetchPost();<br>      setError(null);<br>    } catch (err) {<br>      setError(&quot;Failed to update post&quot;);<br>      console.error(err);<br>    } finally {<br>      setLoading(false);<br>    }<br>  };</pre><pre>  const deletePost = async () =&gt; {<br>    setLoading(true);<br>    try {<br>      await postService.deletePost(id);<br>      router.push(&quot;/&quot;);<br>      setError(null);<br>    } catch (err) {<br>      setError(&quot;Failed to delete post&quot;);<br>      console.error(err);<br>    } finally {<br>      setLoading(false);<br>    }<br>  };</pre><pre>  useEffect(() =&gt; {<br>    if (id) {<br>      fetchPost();<br>    }<br>  }, [id]);</pre><pre>  return {<br>    post,<br>    title,<br>    content,<br>    mode,<br>    loading,<br>    error,<br>    setTitle,<br>    setContent,<br>    setMode,<br>    updatePost,<br>    deletePost<br>  };<br>}</pre><h3>Step 3: Creating Pure UI Components</h3><p>Next, let’s create pure UI components that receive props without handling business logic:</p><pre>// /components/ui/PostTable.jsx<br>import Link from &quot;next/link&quot;;</pre><pre>export function PostTable({ posts }) {<br>  return (<br>    &lt;table className=&quot;divide-y divide-gray-200 w-full mt-6&quot;&gt;<br>      &lt;thead className=&quot;bg-gray-50&quot;&gt;<br>        &lt;tr&gt;<br>          &lt;th scope=&quot;col&quot; className=&quot;px-6 py-3 text-start font-medium text-gray-500 uppercase&quot;&gt;ID&lt;/th&gt;<br>          &lt;th scope=&quot;col&quot; className=&quot;px-6 py-3 text-start font-medium text-gray-500 uppercase&quot;&gt;Title&lt;/th&gt;<br>          &lt;th scope=&quot;col&quot; className=&quot;px-6 py-3 text-start font-medium text-gray-500 uppercase&quot;&gt;Content&lt;/th&gt;   <br>          &lt;th scope=&quot;col&quot; className=&quot;px-6 py-3 text-start font-medium text-gray-500 uppercase&quot;&gt;Action&lt;/th&gt;<br>        &lt;/tr&gt;<br>      &lt;/thead&gt;</pre><pre>      &lt;tbody className=&quot;divide-y divide-gray-200&quot;&gt;<br>        {posts.map((post) =&gt; (<br>          &lt;tr key={post.id}&gt;<br>            &lt;td className=&quot;px-6 py-3 text-gray-800&quot;&gt;{post.id}&lt;/td&gt;<br>            &lt;td className=&quot;px-6 py-3 text-gray-800&quot;&gt;{post.title}&lt;/td&gt;<br>            &lt;td className=&quot;px-6 py-3 text-gray-800&quot;&gt;{post.content}&lt;/td&gt;<br>            &lt;td className=&quot;space-x-4 px-6 py-3 text-end&quot;&gt;<br>              &lt;Link href={`/post/${post.id}?mode=read`}&gt;&lt;button className=&quot;text-blue-600&quot;&gt;View&lt;/button&gt;&lt;/Link&gt; <br>              &lt;Link href={`/post/${post.id}?mode=edit`}&gt;&lt;button className=&quot;text-green-600&quot;&gt;Edit&lt;/button&gt;&lt;/Link&gt; <br>              &lt;button className=&quot;text-red-600&quot; onClick={() =&gt; onDelete &amp;&amp; onDelete(post.id)}&gt;Delete&lt;/button&gt;<br>            &lt;/td&gt;<br>          &lt;/tr&gt;<br>        ))}<br>      &lt;/tbody&gt;<br>    &lt;/table&gt;<br>  );<br>}</pre><pre>// /components/ui/PostForm.jsx<br>export function PostForm({ <br>  title, <br>  content, <br>  onTitleChange, <br>  onContentChange, <br>  onSubmit, <br>  submitButtonText = &quot;Submit&quot; <br>}) {<br>  return (<br>    &lt;form onSubmit={onSubmit} className=&quot;flex flex-col space-y-4 mt-6 border p-6&quot;&gt;<br>      &lt;input <br>        type=&quot;text&quot;<br>        placeholder=&quot;Title&quot;<br>        value={title}<br>        onChange={(e) =&gt; onTitleChange(e.target.value)}<br>        className=&quot;p-2 border border-slate-500&quot; <br>      /&gt;</pre><pre>      &lt;input <br>        type=&quot;text&quot;<br>        placeholder=&quot;Content&quot;<br>        value={content}<br>        onChange={(e) =&gt; onContentChange(e.target.value)}<br>        className=&quot;p-2 border border-slate-500&quot; <br>      /&gt;</pre><pre>      &lt;button className=&quot;w-full bg-green-300 py-1.5&quot;&gt;{submitButtonText}&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><pre>// /components/ui/PostView.jsx<br>import Link from &quot;next/link&quot;;</pre><pre>export function PostView({ post, onEdit, onDelete }) {<br>  return (<br>    &lt;div&gt;<br>      &lt;h3&gt;{post.title}&lt;/h3&gt;<br>      &lt;p&gt;{post.content}&lt;/p&gt;</pre><pre>      &lt;div className=&quot;flex space-x-10 mt-5&quot;&gt;<br>        &lt;Link href=&quot;/&quot;&gt;<br>          &lt;button className=&quot;text-blue-600 w-full bg-green-400 px-3 py-1.5 text-white&quot;&gt;<br>            Home<br>          &lt;/button&gt;<br>        &lt;/Link&gt;<br>        &lt;button <br>          className=&quot;text-blue-600 w-full bg-blue-300 px-3 py-1.5 text-white&quot;<br>          onClick={onEdit}<br>        &gt;<br>          Edit<br>        &lt;/button&gt;<br>        &lt;button <br>          className=&quot;text-blue-600 w-full bg-red-300 px-3 py-1.5 text-white&quot;               <br>          onClick={onDelete}<br>        &gt;<br>          Delete<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Step 4: Creating Container Components</h3><p>Now, let’s create container components that connect our hooks with the UI components:</p><pre>// /components/pages/PostsPage.jsx<br>&quot;use client&quot;<br>import Link from &quot;next/link&quot;;<br>import { usePosts } from &quot;../../hooks/usePosts&quot;;<br>import { PostTable } from &quot;../ui/PostTable&quot;;</pre><pre>export function PostsPage() {<br>  const { posts, loading, error } = usePosts();</pre><pre>  if (loading) return &lt;p&gt;Loading posts...&lt;/p&gt;;<br>  if (error) return &lt;p&gt;Error: {error}&lt;/p&gt;;</pre><pre>  return (<br>    &lt;div className=&quot;px-48 items-center py-20&quot;&gt;<br>      &lt;div className=&quot;flex justify-between&quot;&gt;<br>        &lt;h1 className=&quot;text-3x1 font-bold&quot;&gt;Blog post&lt;/h1&gt;<br>        &lt;Link href=&quot;/post/create&quot; className=&quot;px-4 py-1.5 bg-green-500 rounded text-white&quot;&gt;New Post&lt;/Link&gt;<br>      &lt;/div&gt;</pre><pre>      &lt;PostTable posts={posts} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>// /components/pages/CreatePostPage.jsx<br>&quot;use client&quot;<br>import { useState } from &quot;react&quot;;<br>import { useRouter } from &quot;next/navigation&quot;;<br>import { postService } from &quot;../../services/api&quot;;<br>import { PostForm } from &quot;../ui/PostForm&quot;;</pre><pre>export function CreatePostPage() {<br>  const router = useRouter();<br>  const [title, setTitle] = useState(&quot;&quot;);<br>  const [content, setContent] = useState(&quot;&quot;);<br>  const [loading, setLoading] = useState(false);<br>  const [error, setError] = useState(null);</pre><pre>  const handleSubmit = async (e) =&gt; {<br>    e.preventDefault();<br>    setLoading(true);<br>    try {<br>      await postService.createPost({ title, content });<br>      router.push(&quot;/&quot;);<br>    } catch (err) {<br>      setError(&quot;Failed to create post&quot;);<br>      console.error(err);<br>    } finally {<br>      setLoading(false);<br>    }<br>  };</pre><pre>  return (<br>    &lt;div className=&quot;px-48 items-center py-20&quot;&gt;<br>      &lt;div&gt;Create new post&lt;/div&gt;<br>      {error &amp;&amp; &lt;p className=&quot;text-red-500&quot;&gt;{error}&lt;/p&gt;}<br>      &lt;PostForm<br>        title={title}<br>        content={content}<br>        onTitleChange={setTitle}<br>        onContentChange={setContent}<br>        onSubmit={handleSubmit}<br>        submitButtonText=&quot;Create&quot;<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>// /components/pages/PostDetailPage.jsx<br>&quot;use client&quot;<br>import { useSearchParams } from &quot;next/navigation&quot;;<br>import { usePostDetail } from &quot;../../hooks/usePostDetail&quot;;<br>import { PostForm } from &quot;../ui/PostForm&quot;;<br>import { PostView } from &quot;../ui/PostView&quot;;</pre><pre>export function PostDetailPage({ id }) {<br>  const searchParams = useSearchParams();<br>  const initialMode = searchParams.get(&quot;mode&quot;) || &quot;read&quot;;<br>  <br>  const {<br>    post,<br>    title,<br>    content,<br>    mode,<br>    loading,<br>    error,<br>    setTitle,<br>    setContent,<br>    setMode,<br>    updatePost,<br>    deletePost<br>  } = usePostDetail(id, initialMode);</pre><pre>  if (loading) return &lt;p&gt;Loading...&lt;/p&gt;;<br>  if (error) return &lt;p&gt;Error: {error}&lt;/p&gt;;<br>  if (!post) return &lt;p&gt;Post not found&lt;/p&gt;;</pre><pre>  return (<br>    &lt;div className=&quot;px-48 items-center py-20&quot;&gt;<br>      {mode === &quot;edit&quot; ? (<br>        &lt;&gt;<br>          &lt;div&gt;Edit {post.title}&lt;/div&gt;<br>          &lt;PostForm<br>            title={title}<br>            content={content}<br>            onTitleChange={setTitle}<br>            onContentChange={setContent}<br>            onSubmit={updatePost}<br>            submitButtonText=&quot;Update&quot;<br>          /&gt;<br>        &lt;/&gt;<br>      ) : (<br>        &lt;PostView<br>          post={post}<br>          onEdit={() =&gt; setMode(&quot;edit&quot;)}<br>          onDelete={deletePost}<br>        /&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Step 5: Updating Page Components</h3><p>Finally, let’s update our main page components to use our new container components:</p><pre>// /app/page.js<br>import { PostsPage } from &quot;./components/pages/PostsPage&quot;;</pre><pre>export default function Home() {<br>  return &lt;PostsPage /&gt;;<br>}</pre><pre>// /app/post/create/page.js<br>import { CreatePostPage } from &quot;../../components/pages/CreatePostPage&quot;;</pre><pre>export default function CreatePost() {<br>  return &lt;CreatePostPage /&gt;;<br>}</pre><pre>// /app/post/[id]/page.js<br>import { PostDetailPage } from &quot;../../components/pages/PostDetailPage&quot;;</pre><pre>export default function PostDetail({ params }) {<br>  return &lt;PostDetailPage id={params.id} /&gt;;<br>}</pre><h3>Analysis of the Refactored Architecture</h3><p>Our refactored application now follows a clean separation of concerns:</p><h3>1. Service Layer</h3><ul><li>api.js centralizes all API calls</li><li>Provides a consistent interface to our backend</li><li>Makes API URL configuration and error handling easier</li></ul><h3>2. Custom Hooks Layer</h3><ul><li>usePosts.js and usePostDetail.js contain all business logic</li><li>Handle state management and data operations</li><li>Provide a simple interface to container components</li></ul><h3>3. UI Components Layer</h3><ul><li>Pure presentation components that receive props</li><li>No direct API calls or complex state management</li><li>Easily reusable and testable</li></ul><h3>4. Container Components Layer</h3><ul><li>Connect hooks with UI components</li><li>Handle the composition of multiple UI components</li><li>Manage route-specific state and side effects</li></ul><h3>5. Page Layer</h3><ul><li>Simple components that import and render containers</li><li>Handle routing parameters</li><li>Keep Next.js routing structure clean</li></ul><h3>Benefits of This Architecture</h3><ol><li><strong>Testability</strong></li></ol><ul><li>UI components can be tested with mock props</li><li>Hooks can be tested independently of UI</li><li>Services can be mocked for testing higher-level components</li></ul><p><strong>2. Reusability</strong></p><ul><li>UI components can be reused across different pages</li><li>Hooks can be used by multiple container components</li><li>API services provide consistent data access patterns</li></ul><p><strong>3. Maintainability</strong></p><ul><li>Changing the UI doesn’t affect business logic</li><li>Updating API endpoints only requires changes to service layer</li><li>Component responsibilities are clearly defined</li></ul><p><strong>4. Scalability</strong></p><ul><li>New features can be added without modifying existing code</li><li>Team members can work on different layers simultaneously</li><li>Code organization scales with application complexity</li></ul><blockquote>Conclusion</blockquote><blockquote>Refactoring our Next.js CRUD application to separate UI from logic has transformed it from a functional but monolithic codebase into a well-structured, maintainable application. By introducing dedicated layers for services, hooks, UI components, and containers, we’ve created a clean architecture that follows best practices and makes the application easier to test, maintain, and extend.</blockquote><blockquote>This approach isn’t just theoretical — it represents how many production-grade React and Next.js applications are structured in professional environments. By following these patterns, you’ll build applications that can evolve with your requirements and keep technical debt to a minimum.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3da733a0ff6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Blog CRUD Application with Next.js and a Json- Server (Mock-Server)]]></title>
            <link>https://medium.com/@onalojoseph96/building-a-blog-crud-application-with-next-js-and-a-json-server-mock-server-ba1aefff703b?source=rss-a8e4cc5e0c43------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba1aefff703b</guid>
            <dc:creator><![CDATA[Joseph Onalo]]></dc:creator>
            <pubDate>Tue, 11 Mar 2025 08:31:33 GMT</pubDate>
            <atom:updated>2025-03-11T08:31:33.482Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z9r1q7jzzEckS9s2dhIsYw.png" /><figcaption>Nextjs &amp; json-server</figcaption></figure><blockquote>Introduction</blockquote><blockquote>In modern web development, creating efficient, responsive applications that properly separate concerns is crucial for maintainability and scalability. This article explores a practical implementation of a blog post management system built with Next.js that follows best practices by separating UI components from business logic.</blockquote><blockquote>We’ll analyze a complete CRUD (Create, Read, Update, Delete) application that interacts with a mock server running on localhost. The application allows users to view, create, edit, and delete blog posts through a clean, intuitive interface.</blockquote><h3>Application Setup Process</h3><p>Before diving into the components, let’s understand how to set up this application:</p><ol><li><strong>Create a Next.js Project</strong>:</li></ol><pre>npx create-next-app blog-crud-app cd blog-crud-app</pre><p><strong>2. Install Dependencies</strong>:</p><pre>npm install axios</pre><p><strong>3. Set Up Mock Server</strong>:</p><ul><li>Install JSON Server for the mock API:</li></ul><pre>npm install -g json-server</pre><ul><li>Create a db.json file in the project root:</li></ul><pre>{<br>  &quot;posts&quot;: [<br>    {<br>      &quot;id&quot;: 1,<br>      &quot;title&quot;: &quot;First Post&quot;,<br>      &quot;content&quot;: &quot;This is my first blog post&quot;<br>    }<br>  ]<br>}</pre><ul><li>Start the mock server:</li></ul><pre>json-server --watch db.json --port 5000</pre><p><strong>4. Create Application Files (</strong>Project Structure<strong>)</strong>:</p><p>The application consists of three main components:</p><pre>/app<br>  /page.js            # Main posts listing page<br>  /post<br>    /create<br>      /page.js        # Create new post page<br>    /[id]<br>      /page.js        # View/edit single post page</pre><ul><li>Set up the file structure as shown above</li><li>Implement the components as detailed below</li></ul><p><strong>5. Run the Application</strong>:</p><pre>npm run dev</pre><h3>The Posts Listing Page</h3><p>The main page displays all blog posts in a tabular format and provides navigation to create new posts.</p><h3>Component Analysis</h3><pre>&quot;use client&quot;<br>import axios from &quot;axios&quot;;<br>import Link from &quot;next/link&quot;;<br>import { useState, useEffect } from &quot;react&quot;;</pre><pre>export default function Posts() {<br>  const [posts, setPosts] = useState([])<br>  <br>  const fetchPost = async () =&gt; {<br>    const response = await axios.get(&quot;http://localhost:5000/posts&quot;);<br>    setPosts(response.data);<br>    console.log(posts);<br>  }<br>  <br>  useEffect(() =&gt; {<br>    fetchPost();<br>  }, [])<br>  <br>  return (<br>    &lt;div className=&quot;px-48 items-center py-20&quot; &gt;<br>      &lt;div className=&quot;flex justify-between&quot;&gt;<br>        &lt;h1 className=&quot;text-3x1 font-bold&quot;&gt;Blog post&lt;/h1&gt;<br>        &lt;Link href=&quot;/post/create&quot; className=&quot;px-4 py-1.5 bg-green-500 rounded text-white&quot;&gt;New Post&lt;/Link&gt;<br>      &lt;/div&gt;</pre><pre>      &lt;table className=&quot;divide-y divide-gray-200 w-full mt-6&quot;&gt;<br>        &lt;thead className=&quot;bg-gray-50&quot;&gt;<br>          &lt;tr&gt;<br>            &lt;th scope=&quot;col&quot; className=&quot;px-6 py-3 text-start font-medium text-gray-500 uppercase&quot;&gt;ID&lt;/th&gt;<br>            &lt;th scope=&quot;col&quot; className=&quot;px-6 py-3 text-start font-medium text-gray-500 uppercase&quot;&gt;Title&lt;/th&gt;<br>            &lt;th scope=&quot;col&quot; className=&quot;px-6 py-3 text-start font-medium text-gray-500 uppercase&quot;&gt;Content&lt;/th&gt;   <br>            &lt;th scope=&quot;col&quot; className=&quot;px-6 py-3 text-start font-medium text-gray-500 uppercase&quot;&gt;Action&lt;/th&gt;<br>          &lt;/tr&gt;<br>        &lt;/thead&gt;</pre><pre>        &lt;tbody className=&quot;divide-y divide-gray-200&quot;&gt;<br>          {<br>            posts.map((post) =&gt; (<br>              &lt;tr key={post.id}&gt;<br>                &lt;td className=&quot;px-6 py-3 text-gray-800&quot;&gt;{post.id}&lt;/td&gt;<br>                &lt;td className=&quot;px-6 py-3 text-gray-800&quot;&gt;{post.title}&lt;/td&gt;<br>                &lt;td className=&quot;px-6 py-3 text-gray-800&quot;&gt;{post.content}&lt;/td&gt;<br>                &lt;td className=&quot;space-x-4 px-6 py-3 text-end&quot;&gt;<br>                  &lt;Link href={`/post/${post.id}?mode=read`}&gt;&lt;button className=&quot;text-blue-600&quot;&gt;View&lt;/button&gt;&lt;/Link&gt; <br>                  &lt;Link href={`/post/${post.id}?mode=edit`}&gt;&lt;button className=&quot;text-green-600&quot;&gt;Edit&lt;/button&gt;&lt;/Link&gt; <br>                  &lt;button className=&quot;text-red-600&quot;&gt;Delete&lt;/button&gt;<br>                &lt;/td&gt;<br>              &lt;/tr&gt;<br>            ))<br>          }<br>        &lt;/tbody&gt;<br>      &lt;/table&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Key Features:</h3><ol><li><strong>Client-Side Rendering</strong>: The &quot;use client&quot; directive indicates this component executes on the client side, enabling interactivity.</li><li><strong>State Management</strong>: The component uses React’s useState hook to manage the posts data.</li><li><strong>Data Fetching</strong>: The fetchPost function uses axios to retrieve post data from the mock server.</li><li><strong>Effect Hook</strong>: The useEffect hook ensures that data is fetched when the component mounts, with an empty dependency array preventing unnecessary re-fetches.</li><li><strong>UI Rendering</strong>:</li></ol><ul><li>The component uses a responsive layout with Tailwind CSS padding and spacing</li><li>A header section with the page title and a “New Post” button</li><li>A structured table with clear column headers</li><li>Dynamic rendering of post data with .map() function</li><li>Action buttons styled with appropriate colors for different operations</li></ul><h3>Creating New Posts</h3><p>The create post component provides a form for users to add new blog entries.</p><h3>Component Analysis</h3><pre>&quot;use client&quot;<br>import axios from &quot;axios&quot;;<br>import { useRouter } from &quot;next/navigation&quot;;<br>import { useState, useEffect } from &quot;react&quot;;</pre><pre>const CreatePost = () =&gt; {<br>  const router = useRouter();<br>  const [title, setTitle] = useState(&#39;&#39;)<br>  const [content, setContent] = useState(&#39;&#39;)<br>  <br>  const handleSubmit = async(e) =&gt; { <br>    e.preventDefault()<br>    const response = await axios.post(&quot;http://localhost:5000/posts&quot;, {title, content});<br>    console.log(response.data);<br>    router.push(&#39;/&#39;)<br>  }<br>  <br>  useEffect(() =&gt; {<br>    // fetchPost();<br>  }, [])</pre><pre>  return (<br>    &lt;div className=&quot;px-48 items-center py-20&quot;&gt;<br>      &lt;div&gt;Create new post&lt;/div&gt;<br> <br>      &lt;form  <br>        onSubmit={handleSubmit} <br>        className=&quot;flex flex-col space-y-4 mt-6 border p-6&quot;<br>      &gt;<br>        &lt;input <br>          type=&quot;text&quot;<br>          placeholder=&quot;Title&quot;<br>          value={title}<br>          onChange={(e) =&gt; setTitle(e.target.value)}<br>          className=&quot;p-2 border border-slate-500&quot; <br>        /&gt;</pre><pre>        &lt;input <br>          type=&quot;text&quot;<br>          placeholder=&quot;Content&quot;<br>          value={content}<br>          onChange={(e) =&gt; setContent(e.target.value)}<br>          className=&quot;p-2 border border-slate-500&quot; <br>        /&gt;</pre><pre>        &lt;button className=&quot;w-full bg-green-300 py-1.5&quot;&gt;Create&lt;/button&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default CreatePost;</pre><h3>Key Features:</h3><ol><li><strong>Form State</strong>: Separate state variables track the title and content inputs.</li><li><strong>Form Submission Function</strong>:</li></ol><ul><li>handleSubmit prevents default form behavior with e.preventDefault()</li><li>Uses axios to send a POST request to the server with form data</li><li>Redirects to the home page using Next.js’s router</li></ul><p><strong>3. UI Rendering</strong>:</p><ul><li>Consistent page layout with padding and spacing</li><li>A form with controlled inputs for title and content</li><li>Input fields with placeholder text and border styling</li><li>Event handlers to update state as the user types</li><li>A full-width submit button with appropriate styling</li></ul><h3>Viewing and Editing Posts</h3><p>This component handles both viewing and editing individual posts based on URL parameters.</p><h3>Component Analysis</h3><pre>&quot;use client&quot;;<br>import axios from &quot;axios&quot;;<br>import { useEffect, useState } from &quot;react&quot;;<br>import { useParams, useRouter, useSearchParams } from &quot;next/navigation&quot;;<br>import Link from &quot;next/link&quot;;</pre><pre>export default function PostView() {<br>  const router = useRouter();<br>  const params = useParams(); <br>  const searchParam = useSearchParams();</pre><pre>  const id = params?.id; <br>  const mode = searchParam.get(&#39;mode&#39;); <br>  <br>  const [post, setPost] = useState(null);<br>  const [editing, setEditing] = useState(mode == &#39;edit&#39;);<br>  const [title, setTitle] = useState(&quot;&quot;);<br>  const [content, setContent] = useState(&quot;&quot;);<br>  <br>  // Function to fetch the specific post<br>  const fetchPost = async () =&gt; {<br>    try {<br>      const response = await axios.get(`http://localhost:5000/posts/${id}`);<br>      setPost(response.data);<br>      setTitle(response.data.title);<br>      setContent(response.data.content);<br>      console.log(response.data);<br>    } catch (error) {<br>      console.error(&quot;Error fetching post:&quot;, error);<br>    }<br>  };</pre><pre>  // Function to update the post<br>  const handleSubmit = async (e) =&gt; { <br>    e.preventDefault();<br>    const response = await axios.patch(`http://localhost:5000/posts/${id}`, {title, content});<br>    console.log(&quot;PUT-FUNC&quot;);<br>    setEditing(false);<br>    fetchPost();<br>  };</pre><pre>  // Function to delete the post<br>  const deletePost = async (e) =&gt; { <br>    const response = await axios.delete(`http://localhost:5000/posts/${id}`);<br>    router.push(&#39;/&#39;);<br>  };</pre><pre>  useEffect(() =&gt; {<br>    if (id) {<br>      fetchPost();<br>    }<br>  }, [id]);</pre><pre>  return (<br>    &lt;div&gt;<br>      {post ? (<br>        &lt;div&gt;<br>          {editing ? (<br>            &lt;div className=&quot;px-48 items-center py-20&quot;&gt;<br>              &lt;div&gt;Edit {post.title}&lt;/div&gt;</pre><pre>              &lt;form<br>                onSubmit={handleSubmit}<br>                className=&quot;flex flex-col space-y-4 mt-6 border p-6&quot;<br>              &gt;<br>                &lt;input<br>                  type=&quot;text&quot;<br>                  placeholder=&quot;Title&quot;<br>                  value={title}<br>                  onChange={(e) =&gt; setTitle(e.target.value)}<br>                  className=&quot;p-2 border border-slate-500&quot;<br>                /&gt;</pre><pre>                &lt;input<br>                  type=&quot;text&quot;<br>                  placeholder=&quot;Content&quot;<br>                  value={content}<br>                  onChange={(e) =&gt; setContent(e.target.value)}<br>                  className=&quot;p-2 border border-slate-500&quot;<br>                /&gt;</pre><pre>                &lt;button className=&quot;w-full bg-green-300 py-1.5&quot;&gt;Update&lt;/button&gt;<br>              &lt;/form&gt;<br>            &lt;/div&gt;<br>          ) : (<br>            &lt;div&gt;<br>              &lt;h3&gt;{post.title}&lt;/h3&gt;<br>              &lt;p&gt;{post.content}&lt;/p&gt;</pre><pre>              &lt;div className=&quot;flex space-x-10 mt-5&quot;&gt;<br>                &lt;Link href=&quot;/&quot;&gt;<br>                  &lt;button className=&quot;text-blue-600 w-full bg-green-400 px-3 py-1.5 text-white&quot;&gt;<br>                    Home<br>                  &lt;/button&gt;<br>                &lt;/Link&gt;<br>                &lt;button <br>                  className=&quot;text-blue-600 w-full bg-blue-300 px-3 py-1.5 text-white&quot;<br>                  onClick={() =&gt; setEditing(!editing)}<br>                &gt;<br>                  Edit<br>                &lt;/button&gt;<br>                &lt;button <br>                  className=&quot;text-blue-600 w-full bg-red-300 px-3 py-1.5 text-white&quot;               <br>                  onClick={() =&gt; deletePost()}<br>                &gt;<br>                  Delete<br>                &lt;/button&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;  <br>          )}<br>        &lt;/div&gt;<br>      ) : (<br>        &lt;p&gt;Loading post...&lt;/p&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Key Features:</h3><ol><li><strong>Dynamic Routing</strong>: Utilizes Next.js’s useParams hook to access the post ID from the URL path.</li><li><strong>Query Parameters</strong>: Uses useSearchParams to determine the display mode (read or edit).</li><li><strong>Data Operation Functions</strong>:</li></ol><ul><li>fetchPost: Retrieves the specific post data and populates state</li><li>handleSubmit: Updates the post with edited content using axios PATCH</li><li>deletePost: Removes the post using axios DELETE and redirects to home</li></ul><p><strong>4. Conditional UI Rendering</strong>:</p><ul><li>Loading state when post data is not yet available</li><li>Edit form with pre-populated fields when in editing mode</li><li>View layout with action buttons when in reading mode</li><li>Consistent styling throughout different states</li></ul><p><strong>5. Form Handling</strong>:</p><ul><li>Controlled inputs connected to state</li><li>Form submission handling with prevent default</li><li>Error handling for API requests</li></ul><h3>Separation of Concerns</h3><p>This application effectively separates concerns in several ways:</p><ol><li><strong>UI/Logic Separation</strong>: Each component handles its own state and operations, with clear delineation between data management and presentation.</li><li><strong>Data Fetching</strong>: API calls are encapsulated in specific functions, isolating server communication from rendering logic.</li><li><strong>Routing Logic</strong>: Next.js’s routing system handles navigation concerns separately from component functionality.</li></ol><h3>Best Practices Demonstrated</h3><ol><li><strong>Client-Side Annotation</strong>: The &quot;use client&quot; directive clearly marks components that require client-side execution(Since Nextjs can also execute server-side functions.).</li><li><strong>Controlled Components</strong>: Form inputs are properly controlled by React state.</li><li><strong>Async/Await Pattern</strong>: Server requests use modern async/await syntax for cleaner, more readable code.</li><li><strong>Effect Management</strong>: Empty dependency arrays prevent unnecessary re-fetching, while specific dependencies ensure timely updates.</li><li><strong>Conditional Rendering</strong>: The application shows different UIs based on current state and modes.</li><li><strong>Error Handling</strong>: The fetch operation includes a try/catch block to handle potential errors.</li></ol><blockquote>Conclusion</blockquote><blockquote>This Next.js blog application demonstrates a well-structured approach to building CRUD applications. By separating UI components from business logic and following React best practices, the code remains maintainable and extensible. The use of modern React patterns like hooks and controlled components, combined with Next.js’s powerful routing system, creates a seamless user experience while keeping the codebase clean and organized.</blockquote><blockquote>For developers looking to build similar applications, this structure provides an excellent template that can be adapted to various data models and backend systems beyond the mock server implementation shown here.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba1aefff703b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Squad in Flutter.]]></title>
            <link>https://medium.com/@onalojoseph96/how-to-use-squad-in-flutter-5751abb096bb?source=rss-a8e4cc5e0c43------2</link>
            <guid isPermaLink="false">https://medium.com/p/5751abb096bb</guid>
            <dc:creator><![CDATA[Joseph Onalo]]></dc:creator>
            <pubDate>Thu, 18 Apr 2024 17:51:50 GMT</pubDate>
            <atom:updated>2024-04-18T18:15:01.495Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yoBkwPaHsQgCxa0ayrGZMQ.png" /></figure><h3><strong>What is Squad?</strong></h3><p><a href="https://squadco.com/">Squad</a> is a payment solution by <a href="https://www.gtcoplc.com/">GTCO</a> that enables businesses and individuals from around the world to make and receive payments in a smarter and simpler way.</p><p>To integrate this great service to your flutter app I created <a href="https://pub.dev/packages/flutter_squad_sdk">flutter_squad_sdk</a>, a Flutter package that gives you the ability to integrate the power of Squad Payment Gateway to your Android and iOS Applications. It is also suitable for developers using Firebase or Supabase for backend. You can initiate payment and also checkout right from your Flutter app.</p><h3>Key Features</h3><p>The package offers functionalities to both initiate payment and facilitate checkouts. If users prefer not to generate from their backend server, they can opt for the checkout-only option when initiating payment. Additionally, the package also supports the verification of payments using transaction references.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*5IsdMmZuWjuB_Bz9BYHGXQ.png" /></figure><h3>Getting started</h3><p>To get started make sure you have created an account on <a href="https://squadco.com/">https://squadco.com/</a> . If you want a test account you can create an account on <a href="https://sandbox.squadco.com/login">https://sandbox.squadco.com/login</a> just for development.</p><h4>Add to your project</h4><p>Run this command in the terminal of your project:</p><pre>$ flutter pub add flutter_squad_sdk</pre><p>This will add a line like this to your package’s pubspec.yaml (and run an implicit flutter pub get):</p><pre>dependencies:<br>  flutter_squad_sdk: ^0.0.4</pre><h4>Import it</h4><p>Now in your Dart code, you can use:</p><pre>import &#39;package:flutter_squad_sdk/flutter_squad_sdk.dart&#39;;</pre><h4>Calling the function</h4><p>To initiate a payment and also checkout you need to call the <em>initializeAndCheckout()</em> function in <em>SquadPay</em> class.</p><pre>//Initiate payment and checkout<br>    SquadPay.initializeAndCheckout(<br>    context, <br>    Environment.test, <br>    &quot;&lt;-Enter your Secret Key here-&gt;&quot;,     //your secret key ca be found on your squadco.com dashboard<br>    InitialPayload(<br>        amount: 55000,<br>        email: &quot;nalz@gmail.com&quot;,<br>        currency: &quot;NGN&quot;,<br>        initiateType: &quot;inline&quot;,<br>        transactionRef: SquadPay.generateTransactionRef(16) , //Generate random transaction reference<br>        callbackUrl: &quot;https://google.com&quot;,<br>        <br>    ));</pre><p>To checkout after initializing payment from another source (i.e your backend server), call <em>checkOut()</em> function like so:</p><pre>//Checkout only<br>    SquadPay.checkOut(<br>      context,<br>    &#39;&lt;-Enter your checkout URL here-&gt;&#39;,<br>    &#39;&lt;-Enter your call-back URL here-&gt;&#39;<br>    );</pre><p>To verify if a transaction is successful or not we use this code snippet below</p><pre>//Verify transaction <br>final transactionResponse = await SquadPay.verifyTransaction(<br>    Environment.test,<br>    &quot;&lt;-SECRET -KEY-&gt;&quot;,<br>    &quot;yVJ2KXwvtc&quot; // transaction Ref<br>);</pre><h4><strong>Full Example</strong></h4><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_squad_sdk/flutter_squad_sdk.dart&#39;;<br>import &#39;package:dio/dio.dart&#39;;    //add dio package to pubspec.yaml <br><br>void main() {<br>  runApp(const MyApp());<br>} <br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br>  // This widget is the root of your application.<br>  @override<br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Flutter Squad SDK Demo&#39;,<br>      theme: ThemeData(<br>        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>        useMaterial3: true,<br>      ),<br>      home: const MyHomePage(title: &#39;Flutter Squad SDK Demo&#39;),<br>    );<br>  }<br>}<br>class MyHomePage extends StatefulWidget {<br>  const MyHomePage({super.key, required this.title});<br>  final String title;<br>  @override<br>  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();<br>}<br>class _MyHomePageState extends State&lt;MyHomePage&gt; {<br><br>  String message = &quot;&quot;;<br>  void initiatePaymentMethod() {<br>    SquadPay.initializeAndCheckout(<br>        context,<br>        Environment.test,<br>        &quot;&lt;-SECRET -KEY-&gt;&quot;,<br>        InitialPayload(<br>          amount: 55000,<br>          email: &quot;nalz@gmail.com&quot;,<br>          currency: &quot;NGN&quot;,<br>          initiateType: &quot;inline&quot;,<br>          transactionRef: SquadPay.generateTransactionRef(16),<br>          callbackUrl: &quot;https://google.com&quot;,<br>        ));<br>  }<br>  void checkOutMethod() async {<br>    String result = await SquadPay.checkOut(context,<br>        &quot;https://checkout.paystack.com/25tw9jvmphdlbkt&quot;, &quot;https://google.com&quot;);<br>    message = result;<br>    // print(result);<br>  }<br>  void verifyPayment() async {<br>    try {<br>      final transactionResponse = await SquadPay.verifyTransaction(<br>          Environment.test, &quot;&lt;-SECRET -KEY-&gt;&quot;, &quot;yVJ2KXwvtc&quot; // transaction Ref<br>          );<br>      setState(() {<br>        message = transactionResponse.data!.transactionStatus!;<br>      });<br>   <br>    } on DioException catch (e) {<br>      message = DioExceptions.fromDioError(e).toString();<br>    }<br>  }<br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        backgroundColor: Theme.of(context).colorScheme.inversePrimary,<br>        title: Text(widget.title),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.spaceAround,<br>          children: &lt;Widget&gt;[<br>            FilledButton(<br>                onPressed: initiatePaymentMethod,<br>                child: const Text(&quot;Initialize payment&quot;)),<br>            FilledButton(<br>                onPressed: checkOutMethod, child: const Text(&quot;Checkout&quot;)),<br>            FilledButton(<br>                onPressed: verifyPayment,<br>                child: const Text(&quot;Verify transaction&quot;)),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>Conclusion.</h3><blockquote>In conclusion, integrating Squad into your Flutter app is a seamless process with the flutter_squad_sdk package. By following the steps outlined in this article, you can easily initiate payments, initiate checkout, and verify transactions right from your app. With Squad’s payment solution, businesses and individuals can streamline their payment processes and improve the overall user experience. Try integrating Squad into your Flutter app today to enhance your payment capabilities.</blockquote><h3>References.</h3><ul><li><a href="https://pub.dev/packages/flutter_squad_sdk">flutter_squad_sdk | Flutter package</a></li><li><a href="https://squadco.com/">Squad</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5751abb096bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The rekindle: When life gives you lemon make lemonade]]></title>
            <link>https://medium.com/@onalojoseph96/when-life-gives-you-lemon-make-lemonade-3ef5f4b17ae5?source=rss-a8e4cc5e0c43------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ef5f4b17ae5</guid>
            <dc:creator><![CDATA[Joseph Onalo]]></dc:creator>
            <pubDate>Sat, 02 Mar 2024 13:47:12 GMT</pubDate>
            <atom:updated>2024-03-02T14:36:09.789Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*0157OmduymzUAkM285BvVg.jpeg" /><figcaption><a href="http://www.istockphoto.com/">www.istockphoto.com</a></figcaption></figure><p>Amina should have been calculating her earnings from the few gigs she got; unfortunately, despite juggling multiple gigs while pursuing her passion for photography, she could barely afford medication for her aging mother, “<em>Iya</em>.” Amina grew up on the streets of “<em>Lasgidi</em>,” admiring murals and graffiti and fixing missing details on billboards, newspapers, and magazine photos. Initially mistaken for a model wannabe, as she got older, Amina made it clear that she wanted to capture the moments that created amazing memories. Photography was her superpower, and the camera made her feel like Wonder Woman with the Midas touch and the lasso of truth. Despite her self-motivation, her “<em>Darkseid</em>” seemed to be winning the battle.</p><p>The harder she worked, the more fruitless her efforts felt. With each click of the camera shutter, the bills piled up like the bricks of the pyramid of Giza, leaving her wondering why everything was falling apart despite her sleepless nights and creative efforts.<br>Due to her recent lack of inspiration, Amina had given up on creating magic with her camera for about three weeks. However, she decided to visit the prestigious Nike Art Gallery to rejuvenate her artistic spirit. While admiring a painting of a young African child blossoming from a hibiscus, she heard a voice behind her saying, “Everyone is like a flower; we all bloom in our season as long as there is water in our roots. It will only take time, but soon the world will experience our beauty and presence.” Turning around, Amina saw Ajibade Akinfolajimi, the renowned painter. She immediately recognized him from following his work, and they engaged in conversation, discussing various works of art in the gallery. Amina confided in Ajibade about her struggles to break even in the industry, and he shared his own story of resilience when he started his journey.<br>Returning home, Amina felt as if Ajibade had reignited the flame of her passion. She was now convinced that she could create magic and find fulfillment, despite life’s challenges.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ef5f4b17ae5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenAI’s Sora: Bringing Stories to Life with Text-to-Video Model]]></title>
            <link>https://medium.com/@onalojoseph96/openais-sora-bringing-stories-to-life-with-text-to-video-model-8125b6c4de95?source=rss-a8e4cc5e0c43------2</link>
            <guid isPermaLink="false">https://medium.com/p/8125b6c4de95</guid>
            <dc:creator><![CDATA[Joseph Onalo]]></dc:creator>
            <pubDate>Fri, 16 Feb 2024 14:07:16 GMT</pubDate>
            <atom:updated>2024-02-16T14:07:16.812Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*lfHTAMjYV0eSkO5NpeupjQ.png" /></figure><p>Imagine describing a scene in detail, and then witnessing it come alive in a high-definition video. This is no longer science fiction, thanks to OpenAI’s latest innovation, the <strong>Sora</strong> text-to-video model. Announced in November 2023, Sora has taken the world of AI by storm, pushing the boundaries of what’s possible with language and visuals.</p><p><strong>What is Sora?</strong></p><p>Sora is a powerful AI model trained on a massive dataset of text and video pairs. It can generate realistic and imaginative scenes from text descriptions, creating videos up to a minute long. Unlike other text-to-video models, Sora excels in capturing complex details, including:</p><ul><li><strong>Multiple characters:</strong> Imagine bustling cityscapes with people going about their day. Sora can handle this with ease.</li><li><strong>Specific movements:</strong> Fancy a dog playfully chasing a butterfly? No problem for Sora.</li><li><strong>Accurate details:</strong> Want a scene set in a specific historical period with accurate clothing and architecture? Sora can do it.</li></ul><p><strong>How Does it Work?</strong></p><p>Sora uses a sophisticated technique called <strong>diffusion modeling</strong>. Essentially, it starts with static noise and gradually refines it based on the text description, until a coherent video emerges. This allows for fine-grained control and ensures that the generated video adheres closely to the user’s prompt.</p><p><strong>The Future of Storytelling and Design</strong></p><p>Sora’s potential applications are vast. It can revolutionize fields like:</p><ul><li><strong>Storytelling:</strong> Imagine creating animated movies or TV shows with just words! Sora could empower new forms of narrative exploration.</li><li><strong>Product design:</strong> Prototyping new products in video form could become significantly faster and easier.</li><li><strong>Education and training:</strong> Imagine creating immersive learning experiences by describing scenarios and letting Sora bring them to life.</li><li><strong>Accessibility:</strong> Sora could help people with visual impairments experience stories and information in a new way.</li></ul><p><strong>Challenges and Considerations</strong></p><p>While the possibilities are exciting, it’s important to remember that Sora is still under development. Like any powerful tool, it comes with potential risks:</p><ul><li><strong>Misinformation and bias:</strong> As with all AI models, ensuring fairness and preventing the spread of misinformation is crucial.</li><li><strong>Ethical considerations:</strong> Deepfakes and other manipulative uses of video technology are a growing concern. OpenAI is actively working on addressing these challenges to ensure responsible development and deployment of Sora.</li></ul><h3>Sora Model in Action</h3><p>PROMPT: A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors.</p><p>GENERATED VIDEO:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*0dSj91Oj_MHpzs9iFBE7qw.gif" /><figcaption><a href="https://openai.com/sora">https://openai.com/sora</a></figcaption></figure><p><strong>Conclusion</strong></p><p>OpenAI’s Sora represents a significant leap forward in text-to-video technology. Its ability to create realistic and complex scenes from mere descriptions opens doors to a world of creative possibilities. While challenges remain, Sora’s potential to transform storytelling, design, and education is undeniable. As OpenAI continues to refine this model and address ethical concerns, we can expect even more groundbreaking applications to emerge in the years to come.</p><p>Reference</p><p><a href="https://openai.com/sora">https://openai.com/sor</a>a</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8125b6c4de95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Upload Images to Cloudinary’s Public API with Flutter.]]></title>
            <link>https://medium.com/@onalojoseph96/uploading-images-to-cloudinarys-public-api-with-flutter-370d9d02cb8a?source=rss-a8e4cc5e0c43------2</link>
            <guid isPermaLink="false">https://medium.com/p/370d9d02cb8a</guid>
            <dc:creator><![CDATA[Joseph Onalo]]></dc:creator>
            <pubDate>Sun, 11 Feb 2024 10:42:49 GMT</pubDate>
            <atom:updated>2024-02-13T12:12:09.260Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWzEFaE_YKwhKYStTkMpGw.png" /></figure><p>In this article, we’ll delve into the process of seamlessly uploading images directly from your Flutter application to Cloudinary using its public API. This approach offers a straightforward solution for integrating image management within your Flutter project.</p><p><strong>Prerequisites:</strong></p><ul><li>A Flutter project (ideally created using the flutter create command)</li><li>A Cloudinary account (create one for free at <a href="https://cloudinary.com/">https://cloudinary.com/</a>)</li><li>An understanding of basic Flutter development and HTTP requests</li></ul><p><strong>Steps:</strong></p><ol><li><strong>Set Up Cloudinary:</strong></li></ol><p>Log in to your Cloudinary account and navigate to the <strong>Cloud Settings</strong> section.</p><p>Goto the <strong>Dashboard</strong> menu, enable the <strong>Public API</strong> option.</p><p>Copy your <strong>Cloud Name</strong> from the <strong>Product Environment Credentials</strong> section. You’ll need this later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bq99A5qVQEEAe4bM54jlcQ.png" /></figure><p><strong>Create an Upload Preset:</strong></p><p>Go to the <strong>Cloud Settings</strong> section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9dLqnnZOhzYaz3ciCIuIQ.png" /></figure><p>Click <strong>Upload </strong>from the side menu then click <strong>Add upload preset</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bP29baA3qvmtfFBTAbhuMA.png" /></figure><p>Select <strong>Unsigned</strong> from the <strong>Signing Mode</strong> dropdown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oe6jBmG0jtLt6llJvFY9Vg.png" /></figure><p>Optionally, choose a folder to store your uploaded images by specifying the <strong>Folder</strong> field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FEGeJ9dsuA3DcjxPVGftHg.png" /></figure><p>Click <strong>Save preset</strong>.</p><p>Copy the <strong>Preset Name</strong> from the list of presets (i.e “jebmtkgx_preset”). This will be used for authentication.</p><p><strong>Install the Package and dio:</strong></p><p>Open your Flutter project’s terminal and run:</p><pre><br>flutter pub add dio</pre><p><strong>Choose an Image:</strong></p><p>Provide a method or widget in your Flutter UI to allow users to select an image from their device or camera. You can use packages like image_picker for this purpose.</p><p><strong>Upload the Image:</strong></p><p>Prepare the upload request parameters:</p><pre>File imageFile = File(imagePath);<br>Map&lt;String, dynamic&gt; uploadParams = <br>{  <br> &#39;file&#39;: await MultipartFile.fromFile(imageFile.path, filename: imageFile.path.split(&quot;/&quot;).last), <br>  &#39;upload_preset&#39;: &#39;YOUR_PRESET_NAME&#39;, <br>};</pre><ul><li>Replace YOUR_PRESET_NAME with the name of the preset you created earlier.</li><li>Make the POST request using the dio package:</li></ul><pre>final response = await Dio().post(  <br> &#39;https://api.cloudinary.com/v1_1/${YOUR_CLOUD_NAME}/upload&#39;,  <br> data: uploadParams,   options: Options(   <br>  headers: {&#39;X-Requested-With&#39;: &#39;XMLHttpRequest&#39;}, <br>), <br>);<br><br>if (response.statusCode == 200) { <br>  // Upload successful   <br>final imageUrl = response.data[&#39;url&#39;]; <br>  print(&#39;Image uploaded successfully: $imageUrl&#39;);  <br> // Use the image URL in your application <br>} else {   <br>// Handle upload error <br>  print(&#39;Error uploading image: ${response.data[&#39;error&#39;][&#39;message&#39;]}&#39;); <br>}</pre><p><strong>Additional Considerations:</strong></p><ul><li>For enhanced security, consider using signed uploads instead of unsigned ones. This involves creating a signature on your server side and including it in the upload request.</li><li>Refer to the Cloudinary documentation for more advanced upload options and transformations: <a href="https://cloudinary.com/documentation/upload_images">https://cloudinary.com/documentation/upload_images</a></li><li>Remember to properly handle errors and provide user feedback during the upload process.</li></ul><p>Reference</p><ul><li><a href="https://cloudinary.com/documentation/upload_images">Programmatically Uploading Images, Videos, and Other Files | Cloudinary</a></li><li><a href="https://cloudinary.com/documentation/image_upload_api_reference">Upload API Reference | Cloudinary</a></li><li><a href="https://cloudinary.com/documentation/flutter_integration">Flutter SDK</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=370d9d02cb8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[List Manipulation in Dart Programming Language.]]></title>
            <link>https://medium.com/@onalojoseph96/list-manipulation-in-dart-programming-language-bcd329a567b2?source=rss-a8e4cc5e0c43------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcd329a567b2</guid>
            <dc:creator><![CDATA[Joseph Onalo]]></dc:creator>
            <pubDate>Fri, 08 Dec 2023 14:17:48 GMT</pubDate>
            <atom:updated>2023-12-08T14:17:48.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gw055gAYFaAbce_xizQQtA.png" /></figure><p>Lists are fundamental data structures in programming, serving as organized collections of elements. Dart, a versatile programming language, provides a robust set of methods for manipulating lists, enabling efficient data management and manipulation. This article delves into the intricacies of list manipulation in Dart, equipping you with the knowledge and skills to handle lists with ease.</p><h4>Creating and Initializing Lists</h4><p>Dart offers various ways to initialize lists. The most straightforward approach is to use square brackets [] and specify the elements within:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KRdMa5-exBJ9YIcoSmFv7A.png" /></figure><p>Alternatively, you can utilize the List.filled() constructor to create a fixed-length list with a specific fill value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cvryvK53NHTrUWgGORdBFg.png" /></figure><h4>Accessing List Elements</h4><p>To access individual elements within a list, use the square brackets [] notation and the element&#39;s index:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*f6w08m_hwHdNUHPyhZ9tsQ.png" /></figure><p>The elementAt() method provides an alternative way to access elements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*RZ3GrDqxb4g7fgwBVhfjJg.png" /></figure><h4>Adding elements to a list:</h4><p>Using the add() method: This method adds a single element at the end of the list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tz5e4N54CzxoGI6KRMJegA.png" /></figure><p>Using the addAll() method: This method adds multiple elements at the end of the list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*8ZkG_xIovaIIYJkhqspYrA.png" /></figure><h4><strong>Removing elements from a list:</strong></h4><ul><li>Using the remove() method: This method removes the first occurrence of a specified value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*SWg8adfeWuRxYpjHpaTJhA.png" /></figure><ul><li>Using the removeAt() method: This method removes an element at a specific index.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*3QViPESvRRW3hkN8J2shmg.png" /></figure><ul><li>Using the removeLast() method: This method removes the last element from the list.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*MXAiRIxe6DfbZc-1T043xw.png" /></figure><ul><li>Using the removeWhere() method: This method removes an item based on a condition .</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*QDoSdaPfRTyAeuvD-wgc9g.png" /></figure><h4><strong>Updating elements in a list:</strong></h4><ul><li>Using the index operator ([]): This allows us to access and update elements using their index.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*bEpiRuy-1f1Okk5mj8kERQ.png" /></figure><ul><li>Using the replaceRange() method: This method replaces a range of elements with another list.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*OmvGVRWjkiYQ82ERyYLMFA.png" /></figure><h4>Filtering a list</h4><ul><li>Using the where() method: This method filters elements based on a specific condition.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W15mLeA-mmAb5tZyHscaAQ.png" /></figure><ul><li>Using the removeWhere() method: This method removes elements based on a specific condition.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*A4GcCpXearkR0QZxhS-fBw.png" /></figure><h4>Sorting a list</h4><ul><li>Using the sort() method: This method sorts elements in ascending order.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*FOVGAzp66fcIeK8W8w3fFw.png" /></figure><ul><li>Using the sort() method with a custom comparator: This allows us to sort elements based on a custom criteria.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*I7AGwP_BnsVvwbBKAhKn2A.png" /></figure><h4><strong>Reversing a List</strong></h4><p>To reverse the order of elements in a list, you can use the reversed property or the reversed.toList() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*2hoLpHTZZGhBtQTXprb52A.png" /></figure><h4>Iterating over Lists (Looping)</h4><p>Iterating through a list to process its elements is a common task in programming. Dart provides various iteration methods, including for loops, forEach loops, and the where() method for conditional iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*SD5b1WDSZxu6-aa8S50GkQ.png" /></figure><h4><strong>Searching Lists</strong></h4><p>Lists can be searched using the indexOf</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*yL9IHmxjFCnBldib2LgdnA.png" /></figure><h4>List comprehension</h4><p>List comprehension is a shorthand syntax in Dart for creating a new list by iterating over an existing list and applying an expression to each element. The resulting list is constructed by including elements that evaluate to true in the expression.</p><p>Here’s an example that uses list comprehension to filter out even numbers from an existing list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rCzpbCT2V_KTfLenAWWEJA.png" /></figure><p>In this example, the expression x for (var x in numbers) if (x % 2 == 0) creates a new list by iterating over each element x in the numbers list and only including the elements that are divisible by 2.</p><p>You can also use list comprehension to apply transformations or calculations to elements in the original list. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4E-XvoT2EJl94AVrhFxvNQ.png" /></figure><p>In this example, the expression x * x for (var x in numbers) creates a new list by squaring each element in the numbers list.</p><h3>Conclusion</h3><blockquote>In conclusion, manipulation of lists is a crucial aspect of programming in Dart. Mastering the various methods and techniques for manipulating lists can greatly improve the efficiency, readability, and functionality of your Dart code. By understanding how to add, remove, access, and modify elements in a list, developers can optimize their programs and solve complex problems more effectively. Whether it is merging lists, sorting elements, or filtering based on specific conditions, the list manipulation capabilities in Dart provide a wide range of powerful tools. With practice and experience, programmers can harness the full potential of list manipulation in Dart to create robust and dynamic applications.</blockquote><p>References:</p><ul><li><a href="https://dart.dev/language/collections">Collections</a></li><li><a href="https://api.flutter.dev/flutter/dart-core/List-class.html">List class - dart:core library - Dart API</a></li><li><a href="https://www.darttutorial.org/dart-tutorial/dart-list/">Dart List</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcd329a567b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Untapped Tech Sectors in Nigeria: Unlocking Opportunities for Growth.]]></title>
            <link>https://medium.com/@onalojoseph96/the-untapped-tech-sectors-in-nigeria-unlocking-opportunities-for-growth-2a492243f1b4?source=rss-a8e4cc5e0c43------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a492243f1b4</guid>
            <dc:creator><![CDATA[Joseph Onalo]]></dc:creator>
            <pubDate>Sun, 03 Dec 2023 13:25:44 GMT</pubDate>
            <atom:updated>2023-12-03T13:25:44.494Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tiy73InqbO9sXLqPuhf48w.jpeg" /><figcaption>image-credit: Premiumtimesng.com</figcaption></figure><h3><strong>Introduction</strong></h3><p><em>Nigeria, known for its vibrant economy and growing tech scene, offers a plethora of opportunities for investment and growth in various tech sectors. While some areas have already gained significant attention and a lot of success stories, there are still untapped sectors that hold great potential for innovation and development. In this article, we will explore some of these untapped tech sectors in Nigeria.</em></p><p><strong><em>EDTECH</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QpY0xzX55yQhGSRea8-MRg.png" /></figure><p>With a population of over 200 million, Nigeria has a massive youth demographic, making it an excellent market for EdTech companies. However, despite the increasing demand for quality education and the proliferation of mobile devices, the adoption of technology in education remains relatively low. The potential for personalized learning platforms, online tutoring, and virtual classrooms is vast in Nigeria, creating opportunities for innovative startups to bridge the education gap.</p><p><strong><em>AGRITECH</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*w0Ev9rZAh2HgnSOrCFfuBA.jpeg" /></figure><p>Agriculture is a significant sector in Nigeria, contributing to the country’s GDP and providing employment for millions of people. However, there is a need for technological innovation to address challenges in the sector, such as outdated farming practices, limited access to market information, and post-harvest losses. Investments in agritech startups that leverage technologies like precision farming, remote sensing, and supply chain optimization could boost agricultural productivity and improve the livelihoods of farmers.</p><p><strong><em>HEALTHTECH</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OX4dZ8mAYWdWkVdtwgt_qw.png" /></figure><p>Nigeria’s healthcare system faces numerous challenges, including inadequate access to quality healthcare services, poor infrastructure, and limited adoption of digital health solutions. Healthtech holds immense potential in improving healthcare delivery, patient outcomes, and data management. Developing <em>telemedicine</em> platforms, health monitoring devices, and electronic health records systems could revolutionize the healthcare sector in Nigeria.</p><p><strong><em>TRANSPORTATION &amp; LOGISTICS</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BKNB2nkN2NCTZpJPSciWRA.jpeg" /></figure><p>Transportation and logistics is another tech sector in Nigeria that remains untapped. With a rapidly growing population and congested road networks in major cities, there is a need for innovative solutions to improve transportation and logistics efficiency. Startups focusing on ride-sharing platforms, last-mile delivery services, and supply chain management have the potential to revolutionize the industry in Nigeria and address the challenges of traffic congestion, unreliable logistics, and high transportation costs.</p><p><strong><em>CLEANTECH (Green or Renewable energy)</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*nhMZ1iOQG_yjs83ADdWI0A.jpeg" /></figure><p>With a growing awareness of climate change and environmental sustainability, the CleanTech sector provides significant opportunities for Nigeria’s tech ecosystem. Nigeria faces issues of energy access, waste management, and pollution, which can be mitigated through technology-driven solutions. CleanTech encompasses renewable energy solutions, waste-to-energy technologies, smart grid management, and sustainable transportation systems. Nigeria has abundant renewable energy resources, including solar, wind, and hydroelectric power. However, the country still heavily relies on fossil fuels for its energy needs. By leveraging CleanTech, Nigeria can reduce its carbon footprint, drive economic growth, and enhance the standard of living while safeguarding the environment.</p><p><strong><em>FINTECH (Decentralized)</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oYK5A9mMYg-ekTxbdTQtTA.jpeg" /></figure><p>You may be wondering Why FINTECH is on this list right? Well, while Nigeria has experienced remarkable success in the FinTech space, with companies like <em>Interswitch</em>, <em>Flutterwave</em>, and <em>Paystack</em> leading the way. These companies have revolutionized payment systems, allowing individuals and businesses to transact seamlessly and securely, the growth is massive especially with the rise of mobile banking and payment solutions but, there are still untapped opportunities within this sector. For instance, the adoption of blockchain technology could revolutionize financial services by providing secure and transparent transactions, enabling micropayments, and enhancing financial inclusion for the <em>unbanked</em> population.</p><blockquote><strong>Conclusion</strong></blockquote><blockquote>In conclusion, while Nigeria’s tech ecosystem is witnessing remarkable growth, there are still untapped sectors that hold significant potential for further development. Education Technology, HealthTech, and Transportation &amp; Logistics are examples of sectors that can benefit greatly from technological innovation in Nigeria. On the other hand, Fintech and E-commerce have already made significant strides in the country, positioning Nigeria as a leader in financial technology and online retail in Africa. As investment and support continue to flow into the tech industry, it is expected that the untapped sectors will gradually emerge, contributing to Nigeria’s economic diversification and technological advancement.</blockquote><p>References:</p><p><a href="https://www.thecable.ng/unlocking-nigerias-potential-the-commercial-and-industrial-pathway">https://www.thecable.ng/unlocking-nigerias-potential-the-commercial-and-industrial-pathway</a></p><ul><li><a href="https://professions.ng/it-sector-challenges-and-opportunities/">Challenges and Opportunities in Nigeria&#39;s IT Sector</a></li><li><a href="https://businessday.ng/technology/article/ict-industry-experts-identify-untapped-opportunities-in-sector/">ICT industry experts identify untapped opportunities in sector</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a492243f1b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create Dynamic Form Fields in Runtime Using Jetpack Compose.]]></title>
            <link>https://medium.com/@onalojoseph96/how-to-create-dynamic-formfields-in-runtime-using-jetpack-compose-using-kotlin-4ae4c47c7bca?source=rss-a8e4cc5e0c43------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ae4c47c7bca</guid>
            <dc:creator><![CDATA[Joseph Onalo]]></dc:creator>
            <pubDate>Mon, 27 Nov 2023 08:17:42 GMT</pubDate>
            <atom:updated>2023-11-27T13:49:00.311Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XYAEd2Ig_1CtMtBllRlY5Q.gif" /></figure><p>Jetpack Compose is a modern toolkit for building user interfaces in Android using Kotlin that allows you to create dynamic forms at runtime with ease. In this article, we will explore how to leverage the power of Jetpack Compose to create dynamic forms that can adapt and change based on user interaction.</p><p>Creating a dynamic form involves generating UI elements dynamically based on a pre-defined data model or user input. This can be useful in scenarios where the form structure is not known at compile-time or needs to be customized based on user preferences.</p><p>To get started, make sure you have the latest version of Android Studio installed and that you have a basic understanding of Kotlin and Jetpack Compose.</p><h3>Dependencies</h3><p>Add Jetpack Compose dependencies Open your build.gradle(app level) file and add the following dependencies under the dependencies block:</p><pre>implementation &#39;androidx.core:core-ktx:1.7.0&#39;<br>implementation &#39;androidx.appcompat:appcompat:1.4.1&#39;<br>implementation &#39;androidx.activity:activity-compose:1.4.1&#39;<br>implementation &#39;androidx.lifecycle:lifecycle-runtime-ktx:2.4.1&#39;<br>implementation &#39;androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha07&#39;<br>implementation &#39;androidx.compose.ui:ui:1.0.0&#39;<br>implementation &#39;androidx.compose.material:material:1.0.0&#39;<br>implementation &#39;androidx.compose.material:material-icons-extended:1.0.0&#39;<br>implementation &#39;androidx.compose.runtime:runtime:1.0.4&#39;<br>implementation &#39;androidx.compose.runtime:runtime-livedata:1.0.4&#39;</pre><p>Sync your project to resolve the dependencies.</p><p>Create a data model In order to dynamically generate the form, we need a data model that represents the form structure. Create a new Kotlin file called FormField.kt and add the following code:</p><pre>enum class FieldType {<br>    TEXT,<br>    NUMBER<br>}</pre><pre>data class FormField(<br>    val label: String,<br>    val fieldType: FieldType<br>)</pre><p>In this example, we define a FormField class that has a label and a FieldType. The FieldType enum defines three possible field types: TEXT or NUMBER.</p><p>Create the dynamic form Create a new Kotlin file called DynamicFormScreen.kt and add the following code:</p><pre>import androidx.compose.foundation.Image<br>import androidx.compose.foundation.layout.Column<br>import androidx.compose.foundation.layout.PaddingValues<br>import androidx.compose.foundation.layout.fillMaxSize<br>import androidx.compose.material.Button<br>import androidx.compose.material.ButtonDefaults<br>import androidx.compose.material.MaterialTheme<br>import androidx.compose.material.Text<br>import androidx.compose.material.TextField<br>import androidx.compose.runtime.Composable<br>import androidx.compose.runtime.MutableState<br>import androidx.compose.runtime.mutableStateListOf<br>import androidx.compose.runtime.mutableStateOf<br>import androidx.compose.runtime.savedinstancestate.savedInstanceState<br>import androidx.compose.runtime.livedata.observeAsState<br>import androidx.compose.ui.Alignment<br>import androidx.compose.ui.Modifier<br>import androidx.compose.ui.graphics.ImageBitmap<br>import androidx.compose.ui.graphics.asImageBitmap<br>import androidx.compose.ui.platform.LocalContext<br>import androidx.compose.ui.res.painterResource<br>import androidx.compose.ui.tooling.preview.Preview<br>import androidx.compose.ui.unit.dp<br>import androidx.lifecycle.LiveData<br>import androidx.lifecycle.MutableLiveData<br>import androidx.lifecycle.ViewModel<br>import androidx.lifecycle.ViewModelProvider<br><br>val formFieldsLiveData: MutableLiveData&lt;List&lt;FormField&gt;&gt; = MutableLiveData()<br>val formFields: LiveData&lt;List&lt;FormField&gt;&gt; = formFieldsLiveData<br><br>class DynamicFormViewModel : ViewModel() {<br>    private val _formFields = mutableStateListOf&lt;FormField&gt;()<br>    val formFields: List&lt;FormField&gt; = _formFields<br><br>// Add new field to form<br>fun addFormField(field: FormField) {<br>        _formFields.add(field)<br>    }<br><br>// Remove field from form<br>fun removeFormField(field: FormField) {<br>        _formFields.remove(field)<br>    }<br>}<br><br><br>class DynamicFormViewModelFactory(private val formFields: List&lt;FormField&gt;) :<br>    ViewModelProvider.Factory {<br>    override fun &lt;T : ViewModel?&gt; create(modelClass: Class&lt;T&gt;): T {<br>        if (modelClass.isAssignableFrom(DynamicFormViewModel::class.java)) {<br>            return DynamicFormViewModel() as T<br>        }<br>        throw IllegalArgumentException(&quot;Unknown ViewModel class&quot;)<br>    }<br>}<br><br><br><br>@Composable<br>fun DynamicFormScreen(<br>dynamicFormViewModel: DynamicFormViewModel<br>) {<br>    val context = LocalContext.current<br>    val formFieldsState = formFields.observeAsState()<br><br>LazyColumn(<br>        modifier = Modifier.fillMaxSize(),<br>        horizontalAlignment = Alignment.CenterHorizontally<br>    ) {<br>        formFieldsState.value?.forEach { field -&gt;<br>      <br>            when (field.fieldType) {<br>                FieldType.TEXT -&gt; {<br>                    TextField(<br>                        value = field.fieldValue as? String ?: &quot;&quot;,<br>                        onValueChange = {<br>                            field.fieldValue = it<br>                        }<br>                    )<br>                }<br><br>                FieldType.NUMBER -&gt; {<br>                    TextField(<br>                        value = field.fieldValue?.toString() ?: &quot;&quot;,<br>                        keyboardType = KeyboardType.Number,<br>                        onValueChange = {<br>                            field.fieldValue = it.toIntOrNull()<br>                        }<br>                    )<br>                }<br>           <br>            }<br>        }<br><br> Button(onClick = { <br>            dynamicFormViewModel.addFormField(<br>FormField(<br>    label= &quot;Age&quot;,<br>    fieldType= FieldType.NUMBER<br>))<br>        }) {<br>            Text(&quot;Add Field&quot;)<br>           <br>        }<br>    }</pre><p>Jetpack Compose provides a powerful and intuitive way to create dynamic forms in Android applications. By taking advantage of Kotlin’s concise syntax and Compose’s declarative nature, you can quickly build complex UIs that adapt to user input.</p><p>In this article, we learned how to define the form field model, create the UI, and handle user input. Feel free to extend this example by adding custom form field types or additional validation logic. Happy coding!</p><p>References</p><p><a href="https://developer.android.com/jetpack/compose/text/user-input">Handle user input | Jetpack Compose | Android Developers</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ae4c47c7bca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>