<?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 Sk Ahron on Medium]]></title>
        <description><![CDATA[Stories by Sk Ahron on Medium]]></description>
        <link>https://medium.com/@arunshaik432?source=rss-1e41946a95c7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tlUM4Qs0J6BbbVdf6h9y8A.jpeg</url>
            <title>Stories by Sk Ahron on Medium</title>
            <link>https://medium.com/@arunshaik432?source=rss-1e41946a95c7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:32:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arunshaik432/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[Building a Real-Time In-App Notification System with Nextjs and WebSockets]]></title>
            <link>https://javascript.plainenglish.io/building-a-real-time-in-app-notification-system-with-nextjs-and-websockets-9bfc1d9c4745?source=rss-1e41946a95c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bfc1d9c4745</guid>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Sk Ahron]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 11:49:56 GMT</pubDate>
            <atom:updated>2024-12-19T11:49:56.204Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jlG9ajRabBQ5Bxkg1XmTPw.png" /><figcaption><strong>inapp-notification app</strong></figcaption></figure><p>In this article, we will be working on <strong>in-app notification inbox</strong> using <strong>websockets</strong> for real time updates.</p><blockquote><strong>Note:</strong> I will not be explaining much about the UI stuff this article is more focused on real time notification updates</blockquote><h4>Lets get started:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zuak1nucJ0V8E3VgQKReuA.png" /><figcaption>HLD</figcaption></figure><p><a href="https://github.com/Arunshaik2001/in-app-notification-playground"><strong>Github Repo Link</strong></a></p><p><a href="https://inapp-notifications.dev-boi.com/"><strong>InApp Notification Playground</strong></a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F29zXak8qPMs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D29zXak8qPMs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F29zXak8qPMs%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/885c2a8ab315e9348cbbc3db0654ae53/href">https://medium.com/media/885c2a8ab315e9348cbbc3db0654ae53/href</a></iframe><p><strong>Step 1:</strong> I am using <strong>turborepo</strong> for managing my monorepo project.</p><pre>npx create-turbo@latest</pre><p>this is the file structure of the app.</p><pre>apps<br>   appServer<br>   inappWs<br>   web<br><br>packages<br>   types<br>   utils</pre><p><strong>Step 2</strong>: We will start with developing the <strong>appServer</strong> which is an <strong>express</strong> server.</p><p>I’ve simply created a http server.</p><pre>const app = express();<br><br>const port = process.env.APP_SERVER_PORT || 3000;<br><br>app.use(cors({<br>  origin: &#39;*&#39;<br>}));<br>app.use(express.json());<br><br>app.use(&quot;/v1/send&quot;, sendRouter);<br>app.use(&quot;/v1/getToken&quot;, authRouter);<br><br>app.get(&#39;/&#39;, (req: Request, res: Response) =&gt; {<br>  res.send(&#39;Hello World!&#39;);<br>});<br><br>app.listen(port, () =&gt; {<br>  console.log(`Server started on port ${port}`);<br>});</pre><p>I have 2 routes <strong>/send</strong> and <strong>/getToken</strong></p><p><strong>/send:</strong> This api endpoint is for sending notification to a particular <strong>subscriber id</strong> with the notification payload like below request.</p><pre>{<br>    &quot;title&quot;: &quot;hi arun&quot;,<br>    &quot;body&quot;: &quot;notification&quot;,<br>    &quot;subId&quot;: &quot;1197794&quot;,<br>    &quot;channel&quot;: &quot;feed&quot;,<br>    &quot;notificationType&quot;: &quot;feed&quot;,<br>    &quot;imageUrl&quot;: &quot;https://img.freepik.com/free-photo/colorful-design-with-spiral-design_188544-9588.jpg?ga=GA1.1.1653532884.1733632484&amp;semt=ais_hybrid&quot;<br>}</pre><pre>router.post(&#39;/&#39;, async (req: Request, res: Response, next: NextFunction) =&gt; {<br>    try {<br>        const { body }: {body: SendNotificationRequest} = req;<br>        console.log(body);<br><br>        await redisClient.connect();<br>        await redisClient.publish(body.channel, JSON.stringify(body));<br>        res.send({<br>            data: {<br>                message: `Notification has been queued.&quot;`<br>            }<br>        });<br>    } catch (err) {<br>        console.error(&#39;Error during publishing:&#39;, err);<br>    } finally {<br>        await redisClient.quit();<br>    }<br>});</pre><p>I am simply getting the request passing in <strong>redis</strong> publisher on specified channels(<strong>feed or in_app</strong>).</p><p><strong>/getToken</strong>: This is for creating a <strong>jwt</strong> token which we will be using in our websocket server for authentication without <strong>token</strong> param <strong>websocket</strong> server will not entertain any request.</p><pre>authRouter.post(&#39;/&#39;, async (req: Request, res: Response, next: NextFunction) =&gt; {<br>    const { subId } = req.body;<br><br>    if (!subId) {<br>        return res.status(400).send({ error: &quot;Subscriber Id is required&quot; });<br>    }<br><br>    if (!validateUser(subId)) {<br>        return res.status(401).send({ error: &quot;Invalid credentials&quot; });<br>    }<br><br>    const token = jwt.sign({ subId }, process.env.JWT_SECRET_KEY!, { expiresIn: process.env.TOKEN_EXPIRATION || &quot;1h&quot; });<br><br>    console.log(&#39;Authentication Token:&#39;, token);<br>    res.status(200).send({ token });<br>});</pre><p>this will simply get the<strong> subscriber id </strong>and generate a token which will be valid of<strong> 1 hour.</strong></p><p><strong>Step 3</strong>: Now, we will work on the websocket server.</p><pre>const server = createHttpServer();<br><br>setupWebSocketServer(server);<br><br>setupRedisSubscription().then(() =&gt; {<br>  console.log(&quot;Redis subscription successful.&quot;);<br>});<br><br>const PORT: number = Number(process.env.IN_APP_WEBSOCKET_PORT || 3001);<br>server.listen(PORT, () =&gt; {<br>  console.log(`Server started on port ${PORT}`);<br>});</pre><p>in <strong>index.ts</strong> file I am creating an http server and creating a websocket server and also subscribing to the redis channels <strong>feed</strong> and <strong>in_app.</strong></p><pre>export const setupRedisSubscription = async (): Promise&lt;void&gt; =&gt; {<br>    try {<br>        await redisSubscriber.connect();<br><br>        await redisSubscriber.subscribe(&#39;feed&#39;, (message, channel) =&gt; {<br>            handleRedisMessage(message, channel);<br>        });<br><br>        await redisSubscriber.subscribe(&#39;in_app&#39;, (message, channel) =&gt; {<br>            handleRedisMessage(message, channel);<br>        });<br><br>        console.log(&#39;Subscribed to Redis channels: feed and in_app&#39;);<br>    } catch (err) {<br>        console.error(&#39;Error subscribing to Redis channels:&#39;, err);<br>    }<br>};</pre><p>if you see we are subscribing on the <strong>feed</strong> and <strong>in_app</strong> channels where publisher push the events.</p><p>on receiving the events we will be passing it to the websocket of the connected clients.</p><pre>const handleRedisMessage: RedisMessageHandler = async (message, channel) =&gt; {<br>    console.log(`Message received on channel &quot;${channel}&quot;: ${message}`);<br><br>    try {<br>        const notification = JSON.parse(message);<br><br>        if (notification.subId &amp;&amp; clients.get(notification.subId)) {<br>            const payload: WebsocketTransactionPayload = {<br>                type: &quot;message&quot;,<br>                content: {<br>                    data: {<br>                        notifications: [<br>                            {<br>                                ...notification,<br>                                receivedAt: Date.now(),<br>                                id: generateRandom7DigitNumber(),<br>                                unRead: true,<br>                            }<br>                        ]<br>                    },<br>                },<br>            };<br>            sendNotificationsToClient(notification.subId, payload);<br><br>            // Retrieve existing notifications from Redis<br>            const existingNotifications = await redisCacheHandler.getNotificationsFromCache(notification.subId);<br><br>            // Add the new notification to the cached list<br>            const updatedNotifications = [<br>                ...payload.content.data.notifications ?? [],<br>                ...existingNotifications,<br>            ];<br><br>            // Update the cached notifications in Redis<br>            await redisCacheHandler.setNotificationsInCache(notification.subId, updatedNotifications);<br>        }<br>    } catch (err) {<br>        console.error(&#39;Failed to handle Redis message:&#39;, err);<br>    }<br>};</pre><p><strong>here we are simply checking for the connected websocket clients of that particular subscriber id and passing the payload.</strong> Also if you see we are adding the notification in an redis.</p><p>Now we will start on initializing the websocket server. <strong>if you see as soon as a client tries to make connection we are checking the token and if token is not verified we will close the connection.</strong></p><pre>export const setupWebSocketServer = (server: http.Server): WebSocketServer =&gt; {<br>    const wss = new WebSocketServer({ server });<br><br>    wss.on(&quot;connection&quot;, (ws, req) =&gt; {<br>        const token = new URL(req.url!, `https://${req.headers.host}`).searchParams.get(&#39;token&#39;);<br><br>        if(!token) {<br>            ws.close(4001, &#39;Unauthorized&#39;);<br>            return;<br>        }<br><br>        try {<br>            const decoded = jwt.verify(token, process.env.JWT_SECRET_KEY!); // Validate the token<br>            console.log(&#39;Authenticated user:&#39;, decoded);<br>        } catch (err) {<br>            console.error(&#39;Invalid token, closing connection.&#39;);<br>            ws.close(4001, &#39;Unauthorized&#39;);<br>            return;<br>        }<br><br>        let clientId: string;<br><br>        ws.on(&quot;error&quot;, console.error);<br><br>        ws.on(&quot;message&quot;, async (dataJson) =&gt; {<br>            const data: WebsocketTransactionPayload = rawDataToJson(dataJson);<br>            if (data.type === &#39;identifier&#39;) {<br>                clientId = String(data.content.data.subId);<br>                const clientSockets = clients.get(clientId) ?? [];<br>                clientSockets.unshift(ws);<br>                clients.set(clientId, clientSockets);<br>                console.log(`Total unique connections live: ${clients.size}`);<br><br>                // Fetch notifications from Redis cache<br>                const cachedNotifications = inMemoryCacheHandler.getNotificationsFromCache(clientId);<br>                const unreadCount = inMemoryCacheHandler.getUnreadCount(clientId);<br><br>                if (cachedNotifications.length &gt; 0) {<br>                    const payLoad: WebsocketTransactionPayload = {<br>                        type: &quot;message&quot;,<br>                        content: {<br>                            data: {<br>                                notifications: cachedNotifications,<br>                                notificationsUnreadCount: unreadCount,<br>                            },<br>                        },<br>                    };<br>                    sendNotificationToClient(ws, payLoad);<br>                }<br>            }<br>            else if (data.type === &#39;ping&#39;) {<br>                ws.send(JSON.stringify({<br>                    type: &quot;ping&quot;,<br>                    content: {<br>                        data: {<br>                            status: &quot;OK&quot;<br>                        }<br>                    }<br>                }));<br>            }<br>            else if (data.type === &#39;notificationStatus&#39;) {<br>                const notificationId = data.content.data.notificationId;<br>                const status = data.content.data.status;<br><br>                if (notificationId) {<br>                    await updateNotificationStatusInCache(clientId, notificationId, status === &#39;read&#39;);<br>                    sendUnReadCountMessageToClients(clientId);<br>                }<br>            }<br>        });<br><br>        ws.on(&quot;close&quot;, (code) =&gt; {<br>            console.log(`WebSocket connection closed: ${code}`);<br>            if (clientId) {<br>                if((clients.get(clientId) ?? [])!.includes(ws)){<br>                    clients.set(clientId, (clients.get(clientId) ?? [])!.filter(socket =&gt; socket !== ws));<br>                    if((clients.get(clientId) ?? []).length == 0){<br>                        clients.delete(clientId);<br>                    }<br>                }<br>            }<br>        });<br>    });<br><br>    return wss;<br>};</pre><p>this is the main implementation of the websocket which handles multiple subscribers and sending them notifications through the communication channel.</p><p>I will explain each message type:</p><pre>if (data.type === &#39;identifier&#39;) {<br>                clientId = String(data.content.data.subId);<br>                const clientSockets = clients.get(clientId) ?? [];<br>                clientSockets.unshift(ws);<br>                clients.set(clientId, clientSockets);<br>                console.log(`Total unique connections live: ${clients.size}`);<br><br>                // Fetch notifications from Redis cache<br>                const cachedNotifications = inMemoryCacheHandler.getNotificationsFromCache(clientId);<br>                const unreadCount = inMemoryCacheHandler.getUnreadCount(clientId);<br><br>                if (cachedNotifications.length &gt; 0) {<br>                    const payLoad: WebsocketTransactionPayload = {<br>                        type: &quot;message&quot;,<br>                        content: {<br>                            data: {<br>                                notifications: cachedNotifications,<br>                                notificationsUnreadCount: unreadCount,<br>                            },<br>                        },<br>                    };<br>                    sendNotificationToClient(ws, payLoad);<br>                }                <br>}</pre><p><strong>type === ‘identifier’</strong>: as soon as a client connects it sends this type and it contains the subscriber id in payload and when it connects we will send the notification list which we stored in<strong> app memory </strong>earlier or notification sent by another instance of same subscriber.</p><blockquote><strong>Note:</strong> We are caching the data in memory not caching in <strong>redis server </strong>and I’ve not used <strong>database</strong> for permanent storage. I will be updating the article once i’ve updated the code.</blockquote><p><strong>type === ‘ping’</strong>: this type is sent by client every 30 seconds for avoiding connection timeout issues.</p><pre>else if (data.type === &#39;ping&#39;) {<br>                ws.send(JSON.stringify({<br>                    type: &quot;ping&quot;,<br>                    content: {<br>                        data: {<br>                            status: &quot;OK&quot;<br>                        }<br>                    }<br>                }));<br>}</pre><p><strong>type === ‘notificationStatus’: </strong>this<strong> </strong>type is sent by the client as soon as notification seen status is updated mostly sent on notification read status so that server can identify which notifications have been read by multiple same subscriber ids on mutliple devices to maintain sync and also for sending the <strong>unreadNotifications</strong> count.</p><pre>else if (data.type === &#39;notificationStatus&#39;) {<br>                const notificationId = data.content.data.notificationId;<br>                const status = data.content.data.status;<br><br>                if (notificationId) {<br>                    await updateNotificationStatusInCache(clientId, notificationId, status === &#39;read&#39;);<br>                    sendUnReadCountMessageToClients(clientId);<br>                }<br>}</pre><p><strong>Step 4</strong>: We will now work on the Web App. I am using <strong>Nextjs</strong> for developing the UI. This is a single page web app.</p><p><strong>You can check out the </strong><a href="https://github.com/Arunshaik2001/in-app-notification-playground"><strong>repo</strong></a><strong> for all UI components I will explain only the main components.</strong></p><p><strong>NotificationForm</strong>: this component takes the input from user and calls the send api and doing basic validation.</p><pre>export default function NotificationForm() {<br>    const [message, setMessage] = useState(&quot;&quot;);<br>    const [title, setTitle] = useState(&quot;&quot;);<br>    const [templateType, setTemplateType] = useState(&quot;standard&quot;);<br>    const [actionUrl1, setActionUrl1] = useState(&quot;&quot;);<br>    const [actionLabel1, setActionLabel1] = useState(&quot;&quot;);<br>    const [actionUrl2, setActionUrl2] = useState(&quot;&quot;);<br>    const [actionLabel2, setActionLabel2] = useState(&quot;&quot;);<br>    const [loading, setLoading] = useState(false);<br>    const [imageUrl, setImageUrl] = useState(&quot;&quot;);<br>    const { subId } = useIdentifier();<br><br>    const sendNotification = async () =&gt; {<br>        if (!message || !title) return alert(&quot;Title and Message are required!&quot;);<br>        if (templateType === &quot;single_action&quot; &amp;&amp; (!actionUrl1 || !actionLabel1)) {<br>            return alert(&quot;Action URL and Label are required for Single Action!&quot;);<br>        }<br>        if (templateType === &quot;multi_action&quot; &amp;&amp; (!actionUrl1 || !actionLabel1 || !actionUrl2 || !actionLabel2)) {<br>            return alert(&quot;Both Action URLs and Labels are required for Multi Action!&quot;);<br>        }<br><br>        setLoading(true);<br>        try {<br>            await fetch(`${process.env.NEXT_PUBLIC_APP_SERVER_URL}/send`, {<br>                method: &quot;POST&quot;,<br>                headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>                body: JSON.stringify({<br>                    title,<br>                    body: message,<br>                    subId,<br>                    channel: &quot;feed&quot;,<br>                    notificationType: &quot;feed&quot;,<br>                    imageUrl,<br>                    actions:<br>                        templateType === &quot;standard&quot;<br>                            ? []<br>                            : [<br>                                { label: actionLabel1, actionUrl: actionUrl1 },<br>                                ...(templateType === &quot;multi_action&quot;<br>                                    ? [{ label: actionLabel2, actionUrl: actionUrl2 }]<br>                                    : []),<br>                            ],<br>                }),<br>            });<br>            setMessage(&quot;&quot;);<br>            setTitle(&quot;&quot;);<br>            setActionUrl1(&quot;&quot;);<br>            setActionLabel1(&quot;&quot;);<br>            setActionUrl2(&quot;&quot;);<br>            setActionLabel2(&quot;&quot;);<br>            setImageUrl(&quot;&quot;);<br>            setTemplateType(&quot;standard&quot;);<br>        } catch (error) {<br>            console.error(&quot;Error sending notification:&quot;, error);<br>            alert(&quot;Failed to send notification.&quot;);<br>        } finally {<br>            setLoading(false);<br>        }<br>    };<br><br>    return (<br>        &lt;div className=&quot;bg-white p-6 rounded-lg shadow-lg max-w-xl mx-auto mt-8&quot;&gt;<br>            &lt;h2 className=&quot;text-2xl font-bold text-gray-800 mb-4&quot;&gt;Create a Notification&lt;/h2&gt;<br><br>            &lt;div className=&quot;space-y-4&quot;&gt;<br>                &lt;InputField<br>                    value={title}<br>                    onChange={setTitle}<br>                    placeholder=&quot;Notification Title&quot;<br>                /&gt;<br>                &lt;TextAreaField<br>                    value={message}<br>                    onChange={setMessage}<br>                    placeholder=&quot;Message to be shown in the notification&quot;<br>                /&gt;<br>                &lt;ImagePreview imageUrl={imageUrl} setImageUrl={setImageUrl} /&gt;<br>                &lt;TemplateSelector<br>                    templateType={templateType}<br>                    setTemplateType={setTemplateType}<br>                /&gt;<br>                {[&quot;single_action&quot;, &quot;multi_action&quot;].includes(templateType) &amp;&amp; (<br>                    &lt;ActionFields<br>                        templateType={templateType}<br>                        actionLabel1={actionLabel1}<br>                        setActionLabel1={setActionLabel1}<br>                        actionUrl1={actionUrl1}<br>                        setActionUrl1={setActionUrl1}<br>                        actionLabel2={actionLabel2}<br>                        setActionLabel2={setActionLabel2}<br>                        actionUrl2={actionUrl2}<br>                        setActionUrl2={setActionUrl2}<br>                    /&gt;<br>                )}<br>                &lt;button<br>                    onClick={sendNotification}<br>                    className=&quot;w-full bg-blue-500 text-white py-3 rounded-lg hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-all duration-300&quot;<br>                    disabled={loading}<br>                &gt;<br>                    {loading ? &quot;Sending...&quot; : &quot;Send Notification&quot;}<br>                &lt;/button&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    );<br>}</pre><p><strong>NotificationInbox</strong>: this is where we display the notifications and also the UI <strong>New Message!</strong> on click of which it scroll to top to view the notification.</p><pre>const NotificationInbox: React.FC&lt;NotificationInboxProps&gt; = ({ notifications }: {notifications: Notification[]}) =&gt; {<br>    const [showScrollToTop, setShowScrollToTop] = useState(false);<br>    const notificationsContainerRef = useRef&lt;HTMLDivElement&gt;(null);<br>    const lastNotificationCount = useRef&lt;number&gt;(0);<br>    const [hasScrolled, setHasScrolled] = useState(false);<br><br>    useEffect(() =&gt; {<br>        const container = notificationsContainerRef.current;<br><br>        const handleScroll = () =&gt; {<br>            if (container) {<br>                const { scrollTop } = container;<br><br>                if (scrollTop &lt; 20) {<br>                    setHasScrolled(false);<br>                    setShowScrollToTop(false);<br>                } else {<br>                    setHasScrolled(true);<br>                }<br>            }<br>        };<br><br>        container?.addEventListener(&quot;scroll&quot;, handleScroll);<br>        return () =&gt; container?.removeEventListener(&quot;scroll&quot;, handleScroll);<br>    }, []);<br><br>    useEffect(() =&gt; {<br>        if (notifications.length &gt; lastNotificationCount.current) {<br>            const container = notificationsContainerRef.current;<br>            if (container) {<br>                if (hasScrolled) {<br>                    setShowScrollToTop(true);<br>                }<br>            }<br>        }<br>        lastNotificationCount.current = notifications.length;<br>    }, [notifications, hasScrolled]);<br><br>    const handleScrollToTop = () =&gt; {<br>        notificationsContainerRef.current?.scrollTo({<br>            top: 0,<br>            behavior: &quot;smooth&quot;,<br>        });<br>        setShowScrollToTop(false);<br>    };<br><br>    return (<br>        &lt;div className=&quot;relative&quot;&gt;<br>            {showScrollToTop &amp;&amp; (<br>                &lt;ScrollToTopButton onClick={handleScrollToTop}/&gt;<br>            )}<br><br>            &lt;div<br>                className=&quot;p-4 bg-gray-50 dark:bg-gray-800 rounded-lg shadow-md h-96 overflow-y-auto&quot;<br>                ref={notificationsContainerRef}<br>            &gt;<br>                &lt;NotificationList notifications={notifications}/&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    );<br>};</pre><p>I am simply having reference to this notification list component so that it can listen to scroll position of the list and based on that show New Message UI. If user has not scrolled that will not be shown.</p><p><strong>NotificationList</strong>: this component keep tracks of the notification in list and based on whether notification is visible or not we update the read status and send the data to our websocket server. I’ve used <strong>IntersectionObserver</strong> for listening notification visibility.</p><pre>const NotificationList: React.FC&lt;NotificationListProps&gt; = ({ notifications }: NotificationListProps) =&gt; {<br>    const { updateNotificationStatus, readNotificationSet } = useWebSocket();<br><br>    useEffect(() =&gt; {<br>        notifications.forEach(notification =&gt; {<br>            if (!notification.unRead) {<br>                readNotificationSet.add(notification.id);<br>            }<br>        });<br><br>        const observer = new IntersectionObserver(<br>            (entries) =&gt; {<br>                entries.forEach(entry =&gt; {<br>                    if (entry.isIntersecting) {<br>                        const notificationId = parseInt(entry.target.getAttribute(&#39;data-id&#39;)!);<br>                        if (notificationId) {<br>                            if (!readNotificationSet.has(notificationId)) {<br>                                updateNotificationStatus(notificationId, &#39;read&#39;);<br>                                readNotificationSet.add(notificationId);<br>                            }<br>                        }<br>                    }<br>                });<br>            },<br>            {<br>                root: null,<br>                threshold: 0.8,<br>            }<br>        );<br><br>        const notificationElements = document.querySelectorAll(&#39;.notification-item&#39;);<br>        notificationElements.forEach((item) =&gt; observer.observe(item));<br><br>        return () =&gt; {<br>            notificationElements.forEach((item) =&gt; observer.unobserve(item));<br>        };<br>    }, [notifications, updateNotificationStatus]);<br><br><br>    if (notifications.length === 0) {<br>        return (<br>            &lt;div className=&quot;flex items-center justify-center h-full&quot;&gt;<br>                &lt;p className=&quot;text-gray-500 dark:text-gray-400 text-center&quot;&gt;<br>                    No notifications yet.<br>                &lt;/p&gt;<br>            &lt;/div&gt;<br>        );<br>    }<br><br>    return (<br>        &lt;ul className=&quot;space-y-4&quot;&gt;<br>            {notifications.map((notification, index) =&gt; (<br>                &lt;NotificationItem key={index} notification={notification} /&gt;<br>            ))}<br>        &lt;/ul&gt;<br>    );<br>};</pre><p><strong>WebsocketProvider</strong>: this provider we are using to expose the methods and notifications data we want for all child components. This connects to websocket server and helps to pass various message types from client to server. As soon as we close the window we are closing the websocket and also added reconnection as well and continuous pings to server every 30 seconds to avoid connection timeout.</p><pre>const WebSocketContext = createContext&lt;WebSocketContextType | undefined&gt;(undefined);<br><br>export const useWebSocket = () =&gt; {<br>    const context = useContext(WebSocketContext);<br>    if (!context) {<br>        throw new Error(&#39;useWebSocket must be used within a WebSocketProvider&#39;);<br>    }<br>    return context;<br>};<br><br>interface WebSocketProviderProps {<br>    children: React.ReactNode;<br>    initialPayload: WebsocketTransactionPayload;<br>    reconnectDelay: number;<br>    url: string;<br>}<br><br>export const WebSocketProvider: React.FC&lt;WebSocketProviderProps&gt; = ({ children,url, initialPayload, reconnectDelay = 5000 }) =&gt; {<br>    const [isConnected, setIsConnected] = useState(false);<br>    const [notifications, setNotifications] = useState&lt;Notification[]&gt;([]);<br>    const [unReadCount, setUnReadCount] = useState&lt;number&gt;(0);<br>    const socket = useRef&lt;WebSocket | null&gt;(null);<br>    const reconnectAttempts = useRef(0);<br>    const [readNotificationsSet, setReadNotificationsSet] = useState&lt;Set&lt;number&gt;&gt;(new Set());<br><br><br>    const connectWebSocket = async () =&gt; {<br>        console.log(&quot;Attempting to connect to WebSocket...&quot;);<br><br>        const res = await fetch(`${process.env.NEXT_PUBLIC_APP_SERVER_URL}/getToken`, {<br>            method: &quot;POST&quot;,<br>            headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>            body: JSON.stringify({<br>                subId: initialPayload.content.data.subId,<br>            }),<br>        });<br><br>        if (!res.ok) {<br>            throw new Error(`Error fetching token: ${res.statusText}`);<br>        }<br><br>        const data = await res.json();<br>        const token = data.token;<br><br>        if (!token) {<br>            throw new Error(&quot;Token not found in response&quot;);<br>        }<br><br>        const ws = new WebSocket(`${url}?token=${token}`);<br>        socket.current = ws;<br><br>        ws.onopen = () =&gt; {<br>            console.log(&quot;WebSocket connected&quot;);<br>            setIsConnected(true);<br>            reconnectAttempts.current = 0; // Reset reconnect attempts<br><br>            // Send the initial payload upon connection<br>            if (initialPayload) {<br>                ws.send(JSON.stringify(initialPayload));<br>            }<br>        };<br><br>        ws.onmessage = (event) =&gt; {<br>            const notificationPayload: WebsocketTransactionPayload = JSON.parse(event.data);<br>            if(notificationPayload.type !== &quot;message&quot;){<br>                if(notificationPayload.type === &#39;unreadCount&#39;){<br>                    setUnReadCount(notificationPayload.content.data.notificationsUnreadCount || 0);<br>                }<br>                return;<br>            }<br><br>            const notifications = notificationPayload.content.data.notifications ?? [];<br>            // Add the new notification to the list<br>            setNotifications((prevNotifications) =&gt; [...notifications, ...prevNotifications]);<br>            setUnReadCount(notificationPayload.content.data.notificationsUnreadCount || 0);<br>        };<br><br>        ws.onerror = (error) =&gt; {<br>            console.error(&quot;WebSocket error:&quot;, error);<br>        };<br><br>        ws.onclose = (event) =&gt; {<br>            console.warn(&quot;WebSocket connection closed:&quot;, event.code);<br>            setIsConnected(false);<br><br>            // Attempt to reconnect<br>            if (reconnectAttempts.current &lt; 5) {<br>                reconnectAttempts.current += 1;<br>                setTimeout(connectWebSocket, reconnectDelay);<br>            } else {<br>                console.error(&quot;Max reconnection attempts reached&quot;);<br>            }<br>        };<br>    };<br><br>    const updateNotificationStatus = (notificationId: number, status: &#39;read&#39; | &#39;unread&#39;) =&gt; {<br>        // Send the updated status to the WebSocket server<br>        const payloadData: WebsocketTransactionPayload = {<br>            type: &#39;notificationStatus&#39;,<br>            content: {<br>                data: {<br>                    notificationId: notificationId,<br>                    subId: initialPayload.content.data.subId,<br>                    status: status<br>                }<br>            }<br>        };<br>        socket.current?.send(JSON.stringify(payloadData));<br>    };<br><br>    useEffect(() =&gt; {<br>        // Establish WebSocket connection<br>        connectWebSocket();<br><br>        return () =&gt; {<br>            if (socket.current &amp;&amp; socket.current.readyState === WebSocket.OPEN) {<br>                socket.current.close();<br>            }<br>        };<br>    }, [url]);<br><br>    // Heartbeat to keep the connection alive<br>    useEffect(() =&gt; {<br>        let pingInterval: NodeJS.Timeout;<br>        if (isConnected &amp;&amp; socket.current) {<br>            pingInterval = setInterval(() =&gt; {<br>                if (socket.current?.readyState === WebSocket.OPEN) {<br>                    socket.current.send(JSON.stringify({ type: &quot;ping&quot; }));<br>                }<br>            }, 30000); // Send a ping every 30 seconds<br>        }<br>        return () =&gt; clearInterval(pingInterval);<br>    }, [isConnected]);<br><br>    return (<br>        &lt;WebSocketContext.Provider<br>            value={{<br>                isConnected,<br>                notifications,<br>                unReadCount,<br>                sendMessage: (msg: object) =&gt; socket.current?.send(JSON.stringify(msg)),<br>                updateNotificationStatus,<br>                readNotificationSet: readNotificationsSet<br>            }}<br>        &gt;<br>            {children}<br>        &lt;/WebSocketContext.Provider&gt;<br>    );<br>};</pre><p><strong>That’s it. I have tried to explain the Real Time Notifications as short as possible.</strong></p><p>I hope you liked it.</p><h4>Thank You For Reading the article.</h4><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li><li>Have a story to share? <a href="https://formulatools.co/f/cJh1CStlo9jJmhIegBM9"><strong>Join our global community of writers today!</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bfc1d9c4745" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/building-a-real-time-in-app-notification-system-with-nextjs-and-websockets-9bfc1d9c4745">Building a Real-Time In-App Notification System with Nextjs and WebSockets</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Payment Transfer App with Nextjs, React, Nodejs, Websocket, Prisma, Turborepo and Docker.]]></title>
            <link>https://javascript.plainenglish.io/building-a-payment-transfer-app-with-nextjs-react-nodejs-websocket-prisma-turborepo-and-docker-912d9b74cf60?source=rss-1e41946a95c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/912d9b74cf60</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Sk Ahron]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 06:48:36 GMT</pubDate>
            <atom:updated>2024-11-19T07:22:47.717Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building a Payment Transfer App with Next.js, React.js, Node.js, Websockets, Prisma ORM, Turborepo and Docker</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VqSXkHmmvyOoEtmxCHMO8A.png" /><figcaption>fake payment app</figcaption></figure><blockquote><strong><em>Note:</em></strong><em> </em>You must be familiar with basics of Node.js, Typescript, Next.js, Prisma, Docker and React.js.</blockquote><p>In this article we are going to build a <strong>Payment App</strong> with fake money transfer and we will be creating the frontend using <strong>Nextjs</strong> and <strong>React</strong> and backend using <strong>Nodejs</strong>.</p><p>This project includes a <a href="https://github.com/Arunshaik2001/Paymnt-Transfer-karo/"><strong>Fake Payment App</strong></a> and <a href="https://github.com/Arunshaik2001/Netbanking"><strong>Fake Netbanking App</strong></a> for adding money from fake bank accounts to wallets both are <strong>Monorepos</strong> managed using <strong>Turborepo.</strong></p><blockquote>I have not explained each and every part of building the app as it will stretch the article so i’ve tried to explain the important pieces of the payment app system. It is not the best implementation of building a payment system. this will just get you started and give you an idea about how a payment system works.</blockquote><p><strong>Below is the HLD of the system</strong>. We will be building everything except Merchant App and its related features. It could be a good coding exercise for you after going through this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJyNghbqvQq7_vzhig0VXA.png" /><figcaption>HLD</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZt4LaA1wQiw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZt4LaA1wQiw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FZt4LaA1wQiw%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/68672f0f9c68f99c6f1f735a79332378/href">https://medium.com/media/68672f0f9c68f99c6f1f735a79332378/href</a></iframe><p>I will explain the interactions with various services.</p><ul><li>When users select “Add Money” on the <strong>Paymnt App</strong> (Frontend), it redirects to the <strong>Netbanking App</strong> (Frontend), where they input their netbanking credentials.</li><li>Upon submission, the credentials are sent to the Netbanking Server, which validates them for authenticity.</li><li>After successful validation, the Bank Server triggers the Paymnt App webhook, marking the transaction as initiated, and pushes the request to a <strong>Redis queue</strong>.</li><li>The <strong>OffRampHandler</strong> service processes the request from the queue, updates the transaction status, and notifies the Netbanking App (Frontend) via <strong>WebSockets</strong>.</li><li>It also invokes the Paymnt App <strong>webhook</strong> service with the updated status, which forwards the notification to the Paymnt App (Frontend) using <strong>WebSockets</strong> for UI updates.</li></ul><h4>Lets start building the Fake Netbanking App as this will support the Fake Paymnt App.</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F4UJfHcCeDq8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D4UJfHcCeDq8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F4UJfHcCeDq8%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae6da4deca6ba48854071ae751b27678/href">https://medium.com/media/ae6da4deca6ba48854071ae751b27678/href</a></iframe><p><strong>Features which we will be builiding are:</strong></p><ol><li>Create Netbanking Id provided you have bank account number you can use pre-added bank account numbers or you can add your own in db/prisma/seed.ts as this is a fake Netbanking App that only helps our Fake Paymnt App.</li><li>OffRamp fake money from netbanking app.</li><li>OnRamp fake money.</li></ol><p><strong>Step 1:</strong> Create a <strong>turborepo</strong> project using.</p><pre>npx create-turbo@latest</pre><p>you will have project structure like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*H9CPwsntLkhY5NjR1MVE6g.png" /></figure><p>you can delete both <strong>apps/web</strong> and <strong>app/docs as they </strong>are Nextjs apps we will build our <strong>Netbanking UI using React.</strong></p><p>you can add react project using in <strong>apps/</strong>.</p><pre>npm create vite@latest</pre><p>I will not focus on UI related stuff I will mostly be explaining the logical stuff you can find everything on github repo.</p><pre>{<br>    &quot;@fortawesome/free-solid-svg-icons&quot;: &quot;^6.5.2&quot;,<br>    &quot;@fortawesome/react-fontawesome&quot;: &quot;^0.2.0&quot;,<br>    &quot;@prisma/client&quot;: &quot;^5.13.0&quot;,<br>    &quot;@vercel/speed-insights&quot;: &quot;^1.0.11&quot;,<br>    &quot;jsonwebtoken&quot;: &quot;^9.0.2&quot;,<br>    &quot;prisma&quot;: &quot;^5.13.0&quot;,<br>    &quot;react&quot;: &quot;^18.2.0&quot;,<br>    &quot;react-dom&quot;: &quot;^18.2.0&quot;,<br>    &quot;react-router-dom&quot;: &quot;^6.23.1&quot;,<br>    &quot;react-toastify&quot;: &quot;^10.0.5&quot;,<br>    &quot;ws&quot;: &quot;^8.17.0&quot;<br>  }</pre><p>these are the dependencies which i am using.</p><p><strong>Step 2</strong>: Setup database for the Netbanking app I am using <strong>postresdb</strong> for this and I am using <strong>Prisma</strong> ORM for getting proper types for my tables.</p><p>I have put the schema below.</p><pre>model NetbankingAccount {<br>  userId                  Int           @id @unique<br>  password                String<br>  bankName                BankName<br>  transactions            Transaction[]<br>  bankAccount             BankAccount  @relation(fields: [bankAccountId], references: [accountNumber])<br>  bankAccountId           Int @unique<br>}<br><br>model BankAccount {<br>  accountNumber  Int               @id @unique<br>  balance        Int<br>  userName       String<br>  netbankAccount NetbankingAccount?<br>}<br><br>model Transaction {<br>  txId                    Int               @id @default(autoincrement())<br>  token                   String            @unique<br>  status                  PaymentStatus<br>  amount                  Int<br>  date                    DateTime<br>  netbankingAccount       NetbankingAccount @relation(fields: [netbankingUserId], references: [userId])<br>  netbankingUserId        Int<br>  paymentApp              PaymentApp?<br>  transactionType         TransactionType<br>}<br><br>model RegisteredApp {<br>  paymentApp PaymentApp<br>  secretKey  String<br>  bankSecretKey String<br>  bankName   BankName<br>  webhookUrl String<br>  offRampWebhookEndpoint String<br><br>  @@id([paymentApp, bankName])<br>}<br><br>enum TransactionType {<br>  OnRamp <br>  OffRamp<br>}<br><br>enum PaymentStatus {<br>  INITIATED<br>  PROCESSING<br>  SUCCESS<br>  FAILED<br>}<br><br>enum BankName {<br>  HDFC<br>  KOTAK<br>}<br><br>enum PaymentApp {<br>  PAYMNT <br>  PAYTM <br>  PHONEPE<br>  QUCKPAY<br>  MOBIQWIK<br>  ZEBPAY<br>  XYZPAY<br>}</pre><p>Here’s a breakdown of the schema:</p><h4>1. NetbankingAccount</h4><ul><li>Represents a user’s net banking account with details like:</li><li><strong>User ID (</strong><strong>userId)</strong>: Unique identifier for the user.</li><li><strong>Password (</strong><strong>password)</strong>: Authentication credential.</li><li><strong>Bank Name (</strong><strong>bankName)</strong>: Specifies the bank (e.g., HDFC, KOTAK).</li><li><strong>Transactions (</strong><strong>transactions)</strong>: Links the account to a list of transactions.</li><li><strong>Bank Account (</strong><strong>bankAccount)</strong>: Associates the net banking account with a specific bank account using a foreign key (bankAccountId).</li></ul><h4>2. BankAccount</h4><ul><li>Represents a traditional bank account with details:</li><li><strong>Account Number (</strong><strong>accountNumber)</strong>: Unique identifier for the bank account.</li><li><strong>Balance (</strong><strong>balance)</strong>: Tracks the current balance.</li><li><strong>User Name (</strong><strong>userName)</strong>: Name of the account holder.</li><li><strong>NetbankingAccount (</strong><strong>netbankAccount)</strong>: Optional one-to-one relationship with a NetbankingAccount.</li></ul><h4>3. Transaction</h4><ul><li>Tracks payment transactions with details:</li><li><strong>Transaction ID (</strong><strong>txId)</strong>: Unique identifier, auto-generated.</li><li><strong>Token (</strong><strong>token)</strong>: A unique string for transaction verification.</li><li><strong>Status (</strong><strong>status)</strong>: Indicates the current state of the transaction (e.g., SUCCESS, FAILED).</li><li><strong>Amount (</strong><strong>amount)</strong>: The monetary value involved.</li><li><strong>Date (</strong><strong>date)</strong>: Timestamp of the transaction.</li><li><strong>Netbanking Account (</strong><strong>netbankingAccount)</strong>: Links to the associated net banking account.</li><li><strong>Payment App (</strong><strong>paymentApp)</strong>: Optional field to specify which app was used (e.g., PAYTM, PHONEPE).</li><li><strong>Transaction Type (</strong><strong>transactionType)</strong>: Specifies if it&#39;s an &quot;OnRamp&quot; (money going into a netbanking app) or &quot;OffRamp&quot; (money going out).</li></ul><h4>4. RegisteredApp</h4><ul><li>Represents a payment app integrated with the banking system:</li><li><strong>Payment App (</strong><strong>paymentApp)</strong>: The name of the payment app (e.g., PAYMNT, PAYTM).</li><li><strong>Secret Key (</strong><strong>secretKey)</strong>: Unique key for app authentication.</li><li><strong>Bank Secret Key (</strong><strong>bankSecretKey)</strong>: Unique key for securing bank integration.</li><li><strong>Bank Name (</strong><strong>bankName)</strong>: The bank associated with the app.</li><li><strong>Webhook URL (</strong><strong>webhookUrl)</strong>: URL for event notifications from the app.</li><li><strong>Off-Ramp Webhook Endpoint (</strong><strong>offRampWebhookEndpoint)</strong>: URL for off-ramp transactions.</li><li>The model uses a composite key (@@id) combining paymentApp and bankName.</li></ul><p>and I have created a <strong>postgres</strong> database using <a href="https://aiven.io/"><strong>aiven</strong></a> and same for <strong>redis</strong>.</p><p>I am using a seed file to add default values to my database.</p><pre>async function main() {<br>  const netbankingUser = {<br>    userId: 1234567,<br>    bankName: BankName.HDFC,<br>    password: bcrypt.hashSync(&quot;1234567&quot;, 10),<br>  };<br><br>  await prisma.bankAccount.upsert({<br>    where: { accountNumber: 1234567 },<br>    update: {},<br>    create: {<br>      accountNumber: 1234567,<br>      balance: 1000000,<br>      userName: &quot;Arun Sk&quot;,<br>      netbankAccount: {<br>        create: netbankingUser,<br>      },<br>    },<br>  });<br><br><br>  await prisma.bankAccount.upsert({<br>    where: { accountNumber: 7894561 },<br>    update: {},<br>    create: {<br>      accountNumber: 7894561,<br>      balance: 2000000,<br>      userName: &quot;Varun&quot;,<br>    },<br>  });<br><br>  await prisma.bankAccount.upsert({<br>    where: { accountNumber: 7894562 },<br>    update: {},<br>    create: {<br>      accountNumber: 7894562,<br>      balance: 2000000,<br>      userName: &quot;Tarun&quot;,<br>    },<br>  });<br><br><br>  await prisma.bankAccount.upsert({<br>    where: { accountNumber: 4561234 },<br>    update: {},<br>    create: {<br>      accountNumber: 4561234,<br>      balance: 3000000,<br>      userName: &quot;Rohan&quot;,<br>    },<br>  });<br><br><br>  await prisma.bankAccount.upsert({<br>    where: { accountNumber: 1237894 },<br>    update: {},<br>    create: {<br>      accountNumber: 1237894,<br>      balance: 2000000,<br>      userName: &quot;Rakesh&quot;,<br>    },<br>  });<br><br><br>  await prisma.registeredApp.upsert({<br>    where: {<br>      paymentApp_bankName: {<br>        paymentApp: PaymentApp.PAYMNT,<br>        bankName: BankName.HDFC,<br>      },<br>    },<br>    update: {<br>      paymentApp: PaymentApp.PAYMNT,<br>      secretKey: &quot;PAYMNT_SECRET_HDFC&quot;,<br>      bankSecretKey: &quot;HDFC_SECRET&quot;,<br>      bankName: BankName.HDFC,<br>      webhookUrl: &quot;https://paymntwebhook.dev-boi.com/api/v1/transaction/hdfcWebhook&quot;,<br>      offRampWebhookEndpoint:<br>        &quot;https://paymntwebhook.dev-boi.com/api/v1/transaction/hdfcWebhook/offRamp&quot;,<br>    },<br>    create: {<br>      paymentApp: PaymentApp.PAYMNT,<br>      secretKey: &quot;PAYMNT_SECRET_HDFC&quot;,<br>      bankSecretKey: &quot;HDFC_SECRET&quot;,<br>      bankName: BankName.HDFC,<br>      webhookUrl: &quot;https://paymntwebhook.dev-boi.com/api/v1/transaction/hdfcWebhook&quot;,<br>      offRampWebhookEndpoint:<br>        &quot;https://paymntwebhook.dev-boi.com/api/v1/transaction/hdfcWebhook/offRamp&quot;,<br>    },<br>  });<br><br>  await prisma.registeredApp.upsert({<br>    where: {<br>      paymentApp_bankName: {<br>        paymentApp: PaymentApp.PAYMNT,<br>        bankName: BankName.KOTAK,<br>      },<br>    },<br>    update: {<br>      paymentApp: PaymentApp.PAYMNT,<br>      secretKey: &quot;PAYMNT_SECRET_KOTAK&quot;,<br>      bankName: BankName.KOTAK,<br>      bankSecretKey: &quot;KOTAK_SECRET&quot;,<br>      webhookUrl: &quot;https://paymntwebhook.dev-boi.com/api/v1/transaction/kotakWebhook&quot;,<br>      offRampWebhookEndpoint:<br>        &quot;https://paymntwebhook.dev-boi.com/api/v1/transaction/kotakWebhook/offRamp&quot;,<br>    },<br>    create: {<br>      paymentApp: PaymentApp.PAYMNT,<br>      secretKey: &quot;PAYMNT_SECRET_KOTAK&quot;,<br>      bankSecretKey: &quot;KOTAK_SECRET&quot;,<br>      bankName: BankName.KOTAK,<br>      webhookUrl: &quot;https://paymntwebhook.dev-boi.com/api/v1/transaction/kotakWebhook&quot;,<br>      offRampWebhookEndpoint:<br>        &quot;https://paymntwebhook.dev-boi.com/api/v1/transaction/kotakWebhook/offRamp&quot;,<br>    },<br>  });<br>}</pre><p>If you see the <strong>registeredApp</strong> table it has the details of different 3rd party apps where we will be redirecting the statues of payments using webhook url set by them where bank servers send the data. you can set your own webhook urls for your payment app here in seed file.</p><p><strong>Step 3</strong>: the main route in this app is <strong>/debit</strong> route which will be opened in window where user will add credentials while adding fake money in wallet.</p><p>below is the <strong>/debit</strong> route which handles the logic of verifing the credentials and send data to <strong>webhook</strong> service and push the request to redis and notifying own netbanking frontend.</p><pre>debitRouter.post(<br>  &quot;/&quot;,<br>  userAuthMiddleware,<br>  async function (req: Request, res: Response, next: NextFunction) {<br>    const { paymentAppToken, paymentApp, netbankApp }: userDebitType = req.body;<br>    console.log(&quot;DEBIT-------------&quot;);<br>    console.log(req.body);<br><br>    try {<br>      const bankNameValue: BankName = netbankApp as BankName;<br>      const paymentAppValue: PaymentApp = paymentApp as PaymentApp;<br><br>      const registeredApp = await client.registeredApp.findUnique({<br>        where: {<br>          paymentApp_bankName: {<br>            bankName: bankNameValue,<br>            paymentApp: paymentAppValue,<br>          },<br>        },<br>      });<br><br>      if (!registeredApp) {<br>        res.status(411).json({<br>          message: &quot;No registered financial app&quot;,<br>        });<br>        return;<br>      }<br><br>      const netBankingUser = await prisma.netbankingAccount.findUnique({<br>        where: { userId: Number(res.locals.userId) },<br>      });<br><br>      const registeredAppPayload = jwt.verify(<br>        paymentAppToken,<br>        registeredApp.secretKey<br>      ) as TransactionPaymentPayload;<br><br>      const bankAccount = await prisma.bankAccount.findUnique({<br>        where: { accountNumber: netBankingUser?.bankAccountId },<br>      });<br><br>      if (bankAccount!.balance &lt; registeredAppPayload.amount) {<br>        res.status(411).json({ message: &quot;User doesn&#39;t have enough money&quot; });<br>        return;<br>      }<br><br>      await client.transaction.create({<br>        data: {<br>          paymentApp: paymentAppValue,<br>          token: paymentAppToken,<br>          status: PaymentStatus.INITIATED,<br>          amount: registeredAppPayload.amount,<br>          date: new Date(),<br>          netbankingUserId: Number(res.locals.userId),<br>          transactionType: TransactionType.OffRamp,<br>        },<br>      });<br><br>      const bankSignedToken = jwt.sign(<br>        {<br>          amount: registeredAppPayload.amount,<br>          paymntUserId: registeredAppPayload.paymntUserId,<br>        },<br>        registeredApp!.bankSecretKey<br>      );<br><br>      console.log(`BANKSIGNEDTOKEN ${bankSignedToken}`);<br><br>      const webhookRes = await axios.post(registeredApp!.webhookUrl, {<br>        paymntToken: bankSignedToken,<br>        status: PaymentStatus.INITIATED,<br>      });<br><br>      console.log(`Webhook ${webhookRes.status} responded`);<br><br>      if (webhookRes.status &lt;= 300) {<br>        console.log(`Webhook ${registeredApp!.webhookUrl} responded`);<br>        res.status(200).json({<br>          message:<br>            &quot;Request of payment transfer initiated. will transfer shortly and notify&quot;,<br>          registeredAppPayload,<br>        });<br><br>        const redisClient = createClient({<br>          url: process.env.REDIS_URL || &quot;redis://localhost:6379&quot;,<br>        });<br><br>        await redisClient.connect();<br><br>        await redisClient.lPush(<br>          &quot;OFF_RAMP_TRANSACTIONS_QUEUE&quot;,<br>          JSON.stringify({<br>            paymntToken: paymentAppToken,<br>            paymentApp: paymentAppValue,<br>            netbankApp: bankNameValue,<br>            bankAppPaymentToken: bankSignedToken,<br>          })<br>        );<br><br>        await redisClient.quit();<br>      } else {<br>        res.status(411).json({<br>          message:<br>            &quot;Webhook not responding to transaction initiate. Please retry&quot;,<br>          registeredAppPayload,<br>        });<br>      }<br>    } catch (error) {<br>      console.log(error);<br><br>      res.status(411).json({<br>        message: error,<br>      });<br>    }<br>  }<br>);</pre><p><strong>Step 4</strong>: I have created a <strong>websocket</strong> connection on clicking debit button after getting credentials verified by netbanking server.</p><pre>async function listenToTransaction(clientId: string) {<br>    const ws = new WebSocket(import.meta.env.VITE_HDFC_MAIN_SOCKET_SERVER!);<br><br>    ws.onopen = (event) =&gt; {<br>      console.log(&quot;Connection Opened: &quot; + clientId);<br>      console.log(&quot;event: &quot; + event.type);<br><br>      ws.send(<br>        JSON.stringify({<br>          type: &quot;identifier&quot;,<br>          content: {<br>            data: {<br>              clientId: clientId,<br>            },<br>          },<br>        })<br>      );<br>    };<br><br>    ws.onmessage = (message) =&gt; {<br>      const txDetails = JSON.parse(message.data);<br>      console.log(&quot;Message received:&quot;, txDetails.paymntToken);<br>      if (queryParams.token == txDetails.paymntToken) {<br>        toast.dismiss();<br>        if (txDetails.status == &quot;SUCCESS&quot;) {<br>          toastId.current = toast.success(<br>            &quot;Successfylly Transferred Money. Closing Window.&quot;<br>          );<br>        } else {<br>          toastId.current = toast.error(&quot;Failed to Transfer Money.&quot;);<br>        }<br>        setLoading(false);<br>        ws.close();<br>        setTimeout(() =&gt; {<br>          window.close();<br>        }, 3000);<br>      }<br>    };<br><br>    ws.onclose = () =&gt; {<br>      console.log(&quot;closing connection&quot;);<br>      setLoading(false);<br>    };<br>  }</pre><p>I have fixed the structure of json being passed to and fro through the <strong>websocket</strong> channel.</p><pre>type MessageType = &quot;identifier&quot; | &quot;message&quot;;<br><br>export type WebsocketTransactionPayload = {<br>  type: MessageType;<br>  content: {<br>    data: {<br>      [key: string]: string | number;<br>    };<br>  };<br>};</pre><p>once the frontend receives the data we show notification using <strong>sonner</strong> package and we close the pop-up window when we process the data in frontend.</p><p><strong>Step 5:</strong> Whenever the money handler service or any other services sends data to websocket it has to be in certain json structure.</p><p>below is the <strong>websocket</strong> code.</p><pre>export default function startWebsocketServer(httpServer: any) {<br>  const clients: { [key: string]: WebSocket } = {};<br><br>  const wss = new WebSocketServer({ server: httpServer });<br><br>  wss.on(&quot;connection&quot;, function connection(ws) {<br>    let clientId: string;<br><br>    ws.on(&quot;error&quot;, console.error);<br><br>    ws.on(&quot;message&quot;, function message(dataJson, isBinary) {<br>      const data: WebsocketTransactionPayload = rawDataToJson(dataJson);<br><br>      console.log(&quot;--------------------&quot;);<br>      console.log(data);<br><br>      if (data.type === &quot;identifier&quot;) {<br>        clientId = String(data.content.data.clientId);<br>        clients[clientId] = ws;<br>      } else if (data.type === &quot;message&quot;) {<br>        const clientIdToSend = String(data.content.data.clientIdToSend);<br>        if (<br>          clients[clientIdToSend] &amp;&amp;<br>          clients[clientIdToSend]!.readyState == WebSocket.OPEN<br>        ) {<br>          clients[clientIdToSend]!.send(<br>            JSON.stringify({<br>              paymntToken: data.content.data.paymntToken,<br>              status: data.content.data.status,<br>            }),<br>            { binary: false }<br>          );<br>        }<br>      }<br>    });<br><br>    ws.on(&quot;close&quot;, () =&gt; {<br>      if (clientId) {<br>        delete clients[clientId];<br>        console.log(`Client disconnected with ID: ${clientId}`);<br>      }<br>    });<br>  });<br>}</pre><p>This code sets up a WebSocket server for real-time client communication, where each client is identified by a unique clientId. Clients can register their IDs via an &quot;identifier&quot; message, enabling targeted communication through the server. Messages of type &quot;message&quot; are forwarded to other clients identified by clientIdToSend, provided their WebSocket connection is open. The server maintains an in-memory registry of active connections and cleans up disconnected clients. It includes basic error handling and is ideal for real-time applications like messaging, notifications, or transactional updates.</p><h3>Now we will start on Paymnt App.</h3><p><a href="https://youtu.be/4UJfHcCeDq8">https://youtu.be/4UJfHcCeDq8</a></p><h4>Features it supports:</h4><ol><li>SignUp/SignIn.</li><li>Session based login using <strong>NextAuth</strong>.</li><li>OnRamp/OffRamp fake money from fake/to netbanking frontend and server.</li><li>Peer-2-Peer Transfer in app.</li><li>See OnRamp and OffRamp Transactions.</li><li>Transaction Status updates using Websocket server.</li></ol><p><strong>Step 1</strong>: Create a turborepo project.</p><pre>npx create-turbo@latest</pre><p><strong>Step 2:</strong> Setup database for your fake Payment App. I am using postgresDb and primsa ORM for type safety.</p><p>Here is the schema of the database.</p><pre>model Account {<br>  id Int @id @default(autoincrement())<br>  email String @unique<br>  name String?<br>  password String<br>  upiId Int? @unique<br>  bankAccountNumber Int? @unique<br>  userVerified Boolean<br>  authType AuthType<br>  onRampTransactions RampTransaction[] @relation(&quot;onRampTransactions&quot;)<br>  offRampTransactions RampTransaction[] @relation(&quot;offRampTransactions&quot;)<br>  balance Int?<br>  accountType AccountType<br>  sentTransactions P2PTransaction[] @relation(&quot;debitedAccount&quot;)<br>  receivedTransactions P2PTransaction[] @relation(&quot;creditedAccount&quot;)<br>}<br><br>model RampTransaction {<br>  txId Int @id @default(autoincrement())<br>  onRampAccountId Int? <br>  offRampAccountId Int?<br>  date DateTime<br>  txStatus Status<br>  bankToken String @unique<br>  providerBank BankName<br>  amount Int<br>  accountOnRamp  Account? @relation(&quot;onRampTransactions&quot;, fields: [onRampAccountId], references: [id])<br>  accountOffRamp Account? @relation(&quot;offRampTransactions&quot;, fields: [offRampAccountId], references: [id])<br>  transactionType RampTransactionType<br>}<br><br>model P2PTransaction {<br>  txId Int @id @default(autoincrement())<br>  fromUpiId Int<br>  toUpiId Int<br>  amount Int<br>  date DateTime<br>  status Status<br>  fromAccount Account @relation(&quot;debitedAccount&quot;, fields: [fromUpiId], references: [upiId])<br>  toAccount Account @relation(&quot;creditedAccount&quot;, fields: [toUpiId], references: [upiId])<br>}<br><br>enum AuthType {<br>  GOOGLE<br>  EMAIL<br>}<br><br>enum Status {<br>  INITIATED<br>  PROCESSING<br>  SUCCESS<br>  FAILED<br>}<br><br>enum AccountType {<br>  NORMAL_USER<br>  MERCHANT<br>}<br><br>enum BankName {<br>  HDFC<br>  KOTAK<br>}<br><br>enum RampTransactionType {<br>  OnRamp <br>  OffRamp<br>}</pre><p>The <strong>Account</strong> model represents user accounts with attributes like email, password, optional UPI ID, bank account number, and account type (e.g., personal or business). Users can send and receive funds through two types of transactions: <strong>RampTransactions</strong> and <strong>P2PTransactions</strong>. <strong>RampTransaction</strong> handles on-ramp (loading funds into the system) and off-ramp (withdrawing funds from the system) operations, linking accounts via optional onRampAccountId and offRampAccountId, with details like transaction status, provider bank, and amount. <strong>P2PTransaction</strong> facilitates direct transfers between users via UPI IDs, tracking transaction amount, status, and related accounts. Relationships between these models ensure efficient tracking of sent, received, and account-specific transactions.</p><p><strong>Step 3:</strong> We will create a <strong>webhook server</strong> where we receive data about the payments from fake Netbanking app server.</p><p>I have created 2 API routes for <strong>onRamp</strong> and <strong>offRamp</strong> both the logic are same just we are doing + and — in DB as it is fake money.</p><p>Below is the code for <strong>onRamp</strong> route same is the code for <strong>offRamp</strong> where amount is decremented.</p><pre>const onRampRouter = Router();<br><br>onRampRouter.post(<br>  &quot;/&quot;,<br>  async (req: Request, res: Response, next: NextFunction) =&gt; {<br>    try {<br>      const { paymntToken, status }: ServerWebhookResponseType = req.body;<br><br>      console.log(req.body);<br><br>      const bankPayload = jwt.verify(<br>        paymntToken,<br>        process.env.HDFC_PAYMNT_BANK_SERVER_KEY!<br>      ) as BankPayload;<br><br>      await prisma.rampTransaction.upsert({<br>        where: {<br>          bankToken: paymntToken,<br>        },<br>        update: {<br>          txStatus: status,<br>          date: new Date(),<br>        },<br>        create: {<br>          onRampAccountId: Number(bankPayload.paymntUserId),<br>          amount: bankPayload.amount,<br>          providerBank: BankName.HDFC,<br>          txStatus: status,<br>          bankToken: paymntToken,<br>          date: new Date(),<br>          transactionType: RampTransactionType.OnRamp,<br>        },<br>      });<br><br>      if (status == Status.SUCCESS) {<br>        await prisma.account.update({<br>          where: {<br>            id: Number(bankPayload.paymntUserId),<br>          },<br>          data: {<br>            balance: {<br>              increment: bankPayload.amount,<br>            },<br>          },<br>        });<br>        console.log(&quot;Transaction Success&quot;);<br>        res.status(202).json({<br>          message: &quot;Transaction Success&quot;,<br>        });<br>      } else if (status == Status.FAILED) {<br>        console.log(&quot;Transaction Failed&quot;);<br>        res.status(500).json({<br>          message: &quot;Transaction Failed&quot;,<br>        });<br>      } else if (status == Status.INITIATED) {<br>        console.log(&quot;Transaction Initiated&quot;);<br>        res.status(200).json({<br>          message: &quot;Transaction Initiated&quot;,<br>        });<br>      } else if (status == Status.PROCESSING) {<br>        console.log(&quot;Transaction PROCESSING&quot;);<br>        res.status(200).json({<br>          message: &quot;Transaction PROCESSING&quot;,<br>        });<br>      }<br><br>      const newSocket = new WebSocket(&quot;ws://localhost:3006&quot;);<br><br>      newSocket.onopen = () =&gt; {<br>        console.log(&quot;Connection established&quot;);<br>        newSocket.send(<br>          JSON.stringify({<br>            type: &quot;identifier&quot;,<br>            content: {<br>              data: {<br>                clientId: generateRandom7DigitNumber(),<br>              },<br>            },<br>          }),<br>          {<br>            binary: false,<br>          }<br>        );<br><br>        newSocket.send(<br>          JSON.stringify({<br>            type: &quot;message&quot;,<br>            content: {<br>              data: {<br>                paymntToken: paymntToken,<br>                status: status,<br>                clientIdToSend: bankPayload!.paymntUserId,<br>                rampType: RampTransactionType.OnRamp,<br>              },<br>            },<br>          }),<br>          {<br>            binary: false,<br>          }<br>        );<br>      };<br>      newSocket.onmessage = (message) =&gt; {<br>        console.log(&quot;Message received:&quot;, message.data);<br>      };<br>    } catch (error) {<br>      console.log(error);<br>      res.status(411).json({});<br>    }<br>  }<br>);</pre><p>This code defines an Express.js POST route to handle on-ramp transactions, where funds are added to user accounts from a bank. It validates the provided payment token (paymntToken) using a <strong>JWT</strong> and a bank-specific secret key to extract transaction details such as the user ID and amount. Using Prisma&#39;s upsert method, the transaction is either updated if it already exists or created as a new record in the rampTransaction database table, with details like status, date, amount, and transaction type. If the transaction is successful, the user&#39;s account balance is incremented by the transaction amount; appropriate HTTP responses and logs are provided for other statuses like FAILED, INITIATED, or PROCESSING. The code also establishes a WebSocket connection to notify clients in real-time about the transaction status, sending structured messages to the relevant user based on their unique ID. Errors are caught and logged, ensuring resilience in case of failures.</p><p><strong>Step 4</strong>: We will now create the <strong>websocket</strong> server the code is similar to the code in Netbanking server.</p><pre>const wss = new WebSocketServer({ server: server });<br><br>const clients: { [key: string]: WebSocket } = {};<br><br>wss.on(&quot;connection&quot;, (ws) =&gt; {<br><br>  console.log(&#39;WEBSOCKET SERVER CONNECTED&#39;);<br>  let clientId: string;<br><br>  ws.on(&quot;error&quot;, console.error);<br><br>  ws.on(&quot;message&quot;, (dataJson, isBinary) =&gt; {<br>    const data: WebsocketTransactionPayload = rawDataToJson(dataJson);<br><br>    console.log(&quot;--------------------&quot;);<br>    console.log(data);<br><br>    if (data.type === &quot;identifier&quot;) {<br>      clientId = String(data.content.data.clientId);<br>      clients[clientId] = ws;<br>    } else if (data.type === &quot;message&quot;) {<br>      const clientIdToSend = String(data.content.data.clientIdToSend);<br>      if (<br>        clients[clientIdToSend] &amp;&amp;<br>        clients[clientIdToSend]!.readyState == WebSocket.OPEN<br>      ) {<br>        clients[clientIdToSend]!.send(<br>          JSON.stringify({<br>            paymntToken: data.content.data.paymntToken,<br>            status: data.content.data.status,<br>          }),<br>          { binary: false }<br>        );<br>      }<br>    }<br>  });<br><br>  ws.on(&quot;close&quot;, (code, isBinary) =&gt; {<br>    if (clientId) {<br>      delete clients[clientId];<br>      console.log(`Client disconnected with ID: ${clientId}`);<br>    }<br>  });<br>});</pre><p>this will notify the client with the payment status in notification.</p><p><strong>Step 5</strong>: We will create payment Nextjs app</p><pre>npx create-next-app@latest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NW-KnM3ngumDd5xRDMA7xg.png" /></figure><p>I have chosen these options you can choose your own.</p><p>I will not be discussing about the UI you can find everything in the Github Repo.</p><p><strong>Step 6:</strong> I am using <strong>NextAuth</strong> for authentication. I will define the <strong>AuthOptions</strong>.</p><pre>export const authOptions: AuthOptions = {<br>  providers: [<br>    CredentialsProvider({<br>      name: &quot;Credentials Provider&quot;,<br>      credentials: {<br>        email: {<br>          label: &quot;Email&quot;,<br>          placeholder: &quot;Enter your email id&quot;,<br>          type: &quot;text&quot;,<br>        },<br>        password: {<br>          label: &quot;Password&quot;,<br>          placeholder: &quot;Enter your password&quot;,<br>          type: &quot;password&quot;,<br>        },<br>        <br>      },<br>      async authorize(credentials, req) {<br>        try {<br>          const userRes = await getUser(<br>            credentials!.email,<br>            credentials!.password<br>          );<br><br>          if (userRes) {<br>            return userRes;<br>          }<br>        } catch (error) {<br>          console.log(error);<br>        }<br><br>        return null;<br>      },<br>    }),<br>  ],<br>  secret: process.env.NEXTAUTH_SECRET || &quot;secret&quot;,<br>  pages: {<br>    signIn: &quot;/login&quot;,<br>  },<br>  callbacks: {<br>    async jwt({ token, user, account, profile, trigger, session }) {<br>      //<br><br>      if (trigger == &quot;update&quot;) {<br>        const sessionData = session as Session;<br>        const user = await getUserById(sessionData.user!.userId!);<br><br>        return { ...token, ...user } as JWT;<br>      }<br><br>      if (user) {<br>        return {<br>          ...token,<br>          ...user,<br>        } as JWT;<br>      }<br><br>      if (token!.id) {<br>        const userData = await getUserById(Number(token!.id));<br><br>        console.log({<br>          ...token,<br>          ...userData,<br>        });<br><br>        return {<br>          ...token,<br>          ...userData,<br>        } as JWT;<br>      }<br><br>      return token as JWT;<br>    },<br>    async session({ session, token, user }) {<br>      // console.log(&quot;AUTHORIZE1 &quot;);<br>      // console.log(token);<br>      if (session.user) {<br>        session.user!.accountType = token.accountType;<br>        session.user!.balance = token!.balance;<br>        session.user!.bankAccountNumber = token!.bankAccountNumber;<br>        session.user!.upiId = token!.upiId;<br>        session.user!.userId = token!.id;<br><br>        return session;<br>      }<br>      return session;<br>    },<br>  },<br>};</pre><p>This code defines the authOptions configuration for <strong>NextAuth.js</strong>, enabling authentication using custom credentials. It includes a <strong>Credentials Provider</strong>, where users authenticate with an email and password. Upon submission, the authorize function verifies the credentials by fetching the user data via the getUser server action. If valid, the user object is returned; otherwise, authentication fails.</p><pre>export default async function getUser(email: string, password: string) {<br>  try {<br>    console.log(`${email} : ${password}`);<br>    const user = await prisma.account.findUnique({<br>      where: {<br>        email: email,<br>      },<br>    });<br><br>    if (user) {<br>      const isMatching = await bcrypt.compare(password!, user.password);<br>      if (isMatching) {<br>        return user;<br>      }<br>    }<br>  } catch (error) {<br>    console.log(error);<br>  }<br>  return null;<br>}</pre><p>In the<strong> /login</strong> and <strong>/signup</strong> we have defined the component for authentication.</p><p>The server route for next auth to be set in <strong>/api/auth/[...nextauth]</strong> folder from where you expose GET and POST handler. There are server apis defined in this.</p><p>you can define the server actions in<strong> /actions</strong> folder.</p><p>I have created these server actions as i will be using them in <strong>server components.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*BQhsC6-ZYtTiK7x-wZTGTA.png" /></figure><p>The callbacks in authOptions section extends the authentication behavior. The jwt callback manages JSON Web Token (JWT) updates during login or session refresh. It merges token data with user details fetched dynamically based on triggers like session updates. The session callback customizes the session object by adding additional user-specific details such as account type, balance, bank account number, UPI ID, and user ID, which are derived from the token.</p><p>Additionally, the configuration specifies a secret for token signing, a custom sign-in page (/login), and supports dynamic session updates.</p><p><strong>Step 7:</strong> When you want to set custom properties in session object you have to override the default object present in nextauth lib by creating <strong>next-auth.d.ts</strong> file otherwise you will not be able get custom props.</p><p>create this <strong>/src/@types/next-auth.d.ts </strong>file</p><pre>declare module &quot;next-auth&quot; {<br>  interface Session {<br>    user: {<br>      userId: number;<br>      name: string | null;<br>      upiId: number | null;<br>      bankAccountNumber: number | null;<br>      userVerified: boolean;<br>      authType: AuthType;<br>      balance: number | null;<br>      accountType: AccountType;<br>    } &amp; DefaultSession[&quot;user&quot;];<br>  }<br><br>  interface User {<br>    id: number;<br>    email: string;<br>    name: string | null;<br>    upiId: number | null;<br>    bankAccountNumber: number | null;<br>    userVerified: boolean;<br>    authType: AuthType;<br>    balance: number | null;<br>    accountType: AccountType;<br>  }<br>}<br><br>declare module &quot;next-auth/jwt&quot; {<br>  interface JWT {<br>    id: number;<br>    upiId: number | null;<br>    bankAccountNumber: number | null;<br>    userVerified: boolean;<br>    authType: AuthType;<br>    balance: number | null;<br>    accountType: AccountType;<br>  }<br>}</pre><p><strong>Step 8</strong>: I am using <a href="https://www.npmjs.com/package/recoil"><strong>recoil</strong></a> for managing the state.</p><p>I have created a <strong>custom hook</strong> for session management and on user login to the app we will open up a websocket with server.</p><pre>const useSyncSessionWithRecoil = () =&gt; {<br>  const { data: session, update } = useSession({<br>    required: true,<br>    onUnauthenticated() {<br>      redirect(&quot;/login&quot;);<br>    },<br>  });<br>  const setSession = useSetRecoilState(sessionAtom);<br><br>  const pathname = usePathname();<br>  const setDashboardAtom = useSetRecoilState(dashboardAtom);<br><br>  useEffect(() =&gt; {<br>    setDashboardAtom(pathname);<br>  }, [pathname]);<br><br>  useEffect(() =&gt; {<br>    let ws: WebSocket;<br>    if (session?.user.userId) {<br>      const userSession = session.user;<br>      setSession(userSession);<br><br>      ws = new WebSocket(process.env.NEXT_PUBLIC_PAYMNT_WEBSOCKET_URL!);<br>      console.log(`ws ${process.env.NEXT_PUBLIC_PAYMNT_WEBSOCKET_URL!}`);<br><br>      ws.onerror = (ev) =&gt; {<br>        console.log(`ws.onerror ${process.env.NEXT_PUBLIC_PAYMNT_WEBSOCKET_URL!}`);<br>      }<br>      ws.onopen = (ev: Event) =&gt; {<br>        console.log(&#39;WebSocket connection established.&#39;);<br>        ws.send(<br>          JSON.stringify({<br>            type: &quot;identifier&quot;,<br>            content: {<br>              data: {<br>                clientId: userSession?.userId,<br>              },<br>            },<br>          })<br>        );<br>      };<br><br>      ws.onclose = (ev: CloseEvent) =&gt; {<br>        console.log(&#39;WebSocket connection closed.&#39;);<br>      };<br><br>      ws.onmessage = async (ev: MessageEvent) =&gt; {<br>        const txData = JSON.parse(ev.data);<br><br>        if (txData.status == Status.SUCCESS) {<br>          if (txData.rampType == RampTransactionType.OnRamp) {<br>            toast.success(&quot;Successfully added money.&quot;);<br>          } else {<br>            toast.success(&quot;Successfully withdrawn money.&quot;);<br>          }<br><br>          await update({<br>            ...session,<br>            user: {<br>              ...session.user,<br>              userId: session.user?.userId,<br>            },<br>          });<br>        } else if (txData.status == Status.INITIATED) {<br>          toast.success(&quot;Initiated transaction&quot;);<br>        } else if (txData.status == Status.FAILED) {<br>          toast.error(&quot;failed transaction&quot;);<br>        }<br>      };<br>    } else {<br>      setSession(null);<br>    }<br><br>    return () =&gt; {<br>      if (ws &amp;&amp; ws.OPEN) {<br>        ws.close();<br>      }<br><br>    };<br>  }, [session]);<br>};</pre><p>we are using this hook in <strong>SessionSyncProvider</strong></p><pre>export const Providers = ({ children }: { children: ReactNode }) =&gt; {<br>  return (<br>    &lt;RecoilRoot&gt;<br>      &lt;SessionProvider&gt;<br>        &lt;SessionSyncProvider&gt;{children}&lt;/SessionSyncProvider&gt;<br>      &lt;/SessionProvider&gt;<br>    &lt;/RecoilRoot&gt;<br>  );<br>};<br><br>const SessionSyncProvider: React.FC&lt;{ children: ReactNode }&gt; = ({<br>  children,<br>}) =&gt; {<br>  useSyncSessionWithRecoil();<br>  return &lt;&gt;{children}&lt;/&gt;;<br>};</pre><p>the <strong>Provider</strong> will be the top component in app hierarchy.</p><p>I have tried to explain the important parts of builing the system and rest of the things are pretty straight work.</p><h4>Now we will we be working on containerizing the apps using docker.</h4><p><strong>Step 1:</strong> Install docker on your machine.</p><p><strong>Step 2</strong>: add this in <strong>.env</strong> file inside root folder of payment app.</p><pre>DATABASE_URL=&quot;postgres://YOUR_DATABASE_URL/paymnt?sslmode=require&quot;<br>HDFC_PAYMNT_BANK_SERVER_KEY=&quot;HDFC_SECRET&quot;<br>PAYMNT_HDFC_BANK_SERVER_KEY=&quot;PAYMNT_SECRET_HDFC&quot;<br>KOTAK_PAYMNT_BANK_SERVER_KEY=&quot;KOTAK_SECRET&quot;<br>PAYMNT_KOTAK_BANK_SERVER_KEY=&quot;PAYMNT_SECRET_KOTAK&quot;<br>HDFC_BANK_SERVER=&quot;http://netbanking:4000&quot;<br>PAYMNT_WEBHOOK_PORT=3005<br>PAYMNT_WEBSOCKET_PORT=3006<br>NEXTAUTH_URL=&#39;http://localhost:3000/transfer&#39;<br>NEXTAUTH_SECRET=&quot;secret&quot;<br>NEXT_PUBLIC_PAYMNT_WEBSOCKET_URL=&quot;ws://localhost:3006&quot;<br>NEXT_PUBLIC_HDFC_DEBIT_URL=&quot;http://netbanking:5173/debit&quot;<br>NEXT_PUBLIC_PAYMNT_HDFC_SECRET=&quot;PAYMNT_SECRET_HDFC&quot;<br>NEXT_PUBLIC_HDFC_CREDIT_SERVER_URL=&quot;http://netbanking:4000/api/v1/credit&quot;<br>NEXT_PUBLIC_CLOUDFARE_TOKEN=&quot;XXXXXXXXXX&quot;<br>NEXT_PUBLIC_CAPTCHA=&quot;XXXXXXXXX&quot;<br>NEXT_CAPTCHA_KEY=&quot;XXXXXXXXX&quot;</pre><p><strong>Step 3</strong>: Create a Dockerfile in the root folder.</p><pre>FROM ubuntu:latest<br><br>RUN apt update <br>RUN apt-get install -y build-essential make automake gcc g++ cpp libkrb5-dev libc6-dev man-db autoconf pkg-config <br><br><br># Install NodeJS<br>RUN apt-get update &amp;&amp; apt-get install -y apt-utils &amp;&amp; apt-get install -y nodejs &amp;&amp; apt-get install -y npm &amp;&amp; apt-get install -y python3<br>RUN npm install -g node-gyp<br><br># add turborepo<br>RUN npm install -g turbo<br><br># add dotenv<br>RUN npm install -g dotenv-cli<br><br># Set working directory<br>WORKDIR /app<br><br>COPY  [&quot;package-lock.json&quot;, &quot;package.json&quot;, &quot;./&quot;] <br><br>COPY . .<br><br>RUN npm install<br><br>RUN npm rebuild bcrypt --build-from-source<br><br>EXPOSE 3001 3000 3005 3006<br><br>CMD [&quot;npm&quot;, &quot;run&quot;, &quot;dev:docker&quot;]</pre><p>also make sure these scripts are added in root package.json before creating the docker image.</p><pre>&quot;dev:docker&quot;: &quot;npm run dev:prisma &amp;&amp; npm run dev&quot;,<br>&quot;dev:prisma&quot;: &quot;cd packages/db &amp;&amp; npm run prisma:migrate &amp;&amp; npm run prisma:seed&quot;,<br>&quot;prisma-generate&quot;: &quot;cd packages/db &amp;&amp; npm run prisma:generate&quot;,<br>&quot;docker-compose&quot;: &quot;docker-compose --env-file ./.env up&quot;</pre><p><strong>Step 4</strong>: Build the docker file.</p><pre>docker build -t paymnt-app .</pre><p><strong>Step 5</strong>: create a docker-compose file.</p><pre>version: &quot;3.8&quot;<br><br>services:<br>  turbo:<br>    image: paymnt-app:latest<br>    container_name: paymnt-app<br>    ports:<br>      - &quot;3000:3000&quot;<br>      - &quot;3001:3001&quot;<br>      - &quot;3005:3005&quot;<br>      - &quot;3006:3006&quot;<br><br>    volumes:<br>      - ./:/app/<br>      - /app/node_modules/<br>    restart: on-failure<br>    networks:<br>      - common-network<br><br>networks:<br>  common-network:<br>    driver: bridge<br>    name: &quot;common&quot;</pre><p>This docker-compose.yml file sets up a service called turbo using Docker Compose version 3.8. The service runs a container based on the paymnt-app:latest image and names the container paymnt-app. It exposes several ports (3000, 3001, 3005, and 3006), making them accessible outside the container. For file management, it maps the current directory to /app in the container, allowing changes made locally to be reflected inside the container, while excluding the node_modules directory to prevent potential conflicts. The container is configured to restart automatically if it fails. Lastly, the service connects to a custom bridge network called common-network, which is explicitly named common, ensuring smooth communication with other containers on the same network. This setup is practical for local development and enables easy container management and networking.</p><p><strong>Step 6</strong>: Now run the compose file.</p><pre>npm run docker-compose</pre><p>If you run this cmd</p><pre>docker container ls </pre><p>you will see container paymnt-app is running.</p><p><strong>Step 7:</strong> Create <strong>.env</strong> in root folder of Netbanking project.</p><pre>DATABASE_URL=&quot;postgres://YOUR_DB_URL/netbanking?sslmode=require&quot;<br>REDIS_URL=&quot;YOUR_REDIS_URL&quot;<br>HDFC_JWT_LOGIN_SECRET=&quot;PAYMNT_SECRET_HDFC&quot;<br>VITE_HDFC_MAIN_SERVER=&quot;http://localhost:4000/&quot;<br>VITE_HDFC_DEBIT_SERVER_URL=&quot;http://localhost:4000/api/v1/auth/debit&quot;<br>VITE_HDFC_CREATE_SERVER_URL=&quot;http://localhost:4000/api/v1/create&quot;<br>VITE_HDFC_LOGIN_SERVER_URL=&quot;http://localhost:4000/api/v1/auth/login&quot;<br>VITE_HDFC_MAIN_SOCKET_SERVER=&quot;ws://localhost:4000/&quot;<br>VITE_CLOUDFARE_TOKEN=&quot;ws://localhost:4000/&quot;</pre><p><strong>Step 8:</strong> Create a docker file and docker-compose.netbanking file.</p><pre>FROM ubuntu:latest<br><br>RUN apt update <br>RUN apt-get install -y build-essential make automake gcc g++ cpp libkrb5-dev libc6-dev man-db autoconf pkg-config <br><br><br># Install NodeJS<br>RUN apt-get update &amp;&amp; apt-get install -y apt-utils &amp;&amp; apt-get install -y nodejs &amp;&amp; apt-get install -y npm &amp;&amp; apt-get install -y python3<br>RUN npm install -g node-gyp<br><br># add turborepo<br>RUN npm install -g turbo<br><br># add dotenv<br>RUN npm install -g dotenv-cli<br><br># Set working directory<br>WORKDIR /app<br><br>COPY  [&quot;package-lock.json&quot;, &quot;package.json&quot;, &quot;./&quot;] <br><br>COPY . .<br><br>RUN npm install<br><br>RUN npm rebuild bcrypt --build-from-source<br><br>EXPOSE 4000 5173<br><br>CMD [&quot;npm&quot;, &quot;run&quot;, &quot;dev:docker&quot;]</pre><pre>version: &quot;3.8&quot;<br><br>services:<br>  netbanking:<br>    image: netbanking:latest<br>    container_name: netbanking<br>    ports:<br>      - &quot;4000:4000&quot;<br>      - &quot;5173:5173&quot;<br>    volumes:<br>      - ./:/app/<br>      - /app/node_modules/<br>    restart: on-failure<br>    networks:<br>      - common<br><br>networks:<br>  common:<br>    external:<br>      name: common</pre><p>This docker-compose.yml file configures a service named netbanking using Docker Compose version 3.8. The service runs a container from the netbanking:latest image and names the container netbanking. It maps ports <strong>4000</strong> and <strong>5173</strong> on the host to the same ports inside the container, making these accessible for external communication. Two volumes are defined: the first maps the current directory to /app in the container to allow local code changes to be reflected inside the container, while the second excludes the node_modules directory to prevent syncing conflicts. The container is set to restart automatically on failure for added resilience. The netbanking service is connected to a shared external network named common, allowing seamless communication with other containers on the same network.</p><p>make sure you have these scripts in package.json</p><pre>&quot;dev:docker&quot;: &quot;npm run dev:prisma &amp;&amp; npm run dev&quot;,<br>&quot;dev:prisma&quot;: &quot;cd packages/db &amp;&amp; npm run prisma:migrate &amp;&amp; npm run prisma:seed&quot;,<br>&quot;prisma-generate&quot;: &quot;cd packages/db &amp;&amp; npx prisma generate&quot;,<br>&quot;docker-compose&quot;: &quot;docker-compose --env-file ./.env -f docker-compose.netbanking.yml up&quot;</pre><p><strong>Step 9</strong>: Build the docker file and run it.</p><pre>docker build -t netbanking .<br>npm run docker-compose</pre><p>Your end result should be similar to this.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZt4LaA1wQiw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZt4LaA1wQiw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FZt4LaA1wQiw%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/68672f0f9c68f99c6f1f735a79332378/href">https://medium.com/media/68672f0f9c68f99c6f1f735a79332378/href</a></iframe><p><strong>Thank You for reading the article.</strong></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=912d9b74cf60" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/building-a-payment-transfer-app-with-nextjs-react-nodejs-websocket-prisma-turborepo-and-docker-912d9b74cf60">Building a Payment Transfer App with Nextjs, React, Nodejs, Websocket, Prisma, Turborepo and Docker.</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server-Driven UI Backend Implementation from Scratch Using Serverpod: Part 6]]></title>
            <link>https://levelup.gitconnected.com/server-driven-ui-backend-implementation-from-scratch-using-serverpod-part-6-b540c5c6fb68?source=rss-1e41946a95c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b540c5c6fb68</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Sk Ahron]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 13:23:44 GMT</pubDate>
            <atom:updated>2024-08-01T13:23:44.925Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*g6-63_SpWyPG0r9YC_BUwA.jpeg" /></figure><p>In this article we will continue working on <strong>backend</strong> part of <a href="https://github.com/ServeDynamicUI/pokedyn-app"><strong>Pokedyn</strong></a> app in this we will primary focus on <strong>backend</strong> using <a href="https://serverpod.dev/"><strong>Serverpod</strong></a><strong>.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FrC6ibQc4KpA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrC6ibQc4KpA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FrC6ibQc4KpA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7d8e74585e4df4be40fa4af1ac6afe3/href">https://medium.com/media/c7d8e74585e4df4be40fa4af1ac6afe3/href</a></iframe><h4>Lets Start</h4><p><strong>Step 1.</strong> We will be creating models <strong>PageUriMapping</strong>, <strong>PageWidgetMapping</strong>, <strong>WidgetWidgetMapping</strong> and <strong>Widget</strong></p><p>In the <strong>models</strong> folder create yaml files</p><p>create these files in<strong> pokedyn_server/lib/src/models</strong></p><pre>class: PageUriMapping<br>table: page_uri_mapping<br>fields:<br>  pageUri: String<br>  pageId: int<br>  pageData: String</pre><pre>class: PageWidgetMapping<br>table: page_widget_mapping<br>fields:<br>  pageId: int<br>  widgetId: int</pre><pre>class: WidgetWidgetMapping<br>table: widget_widget_mapping<br>fields:<br>  parentWidget: int<br>  childWidgetId: int?</pre><pre>class: Widget<br>table: widget<br>fields:<br>  widgetId: int<br>  widgetType: String<br>  widgetData: String<br>  widgetName: String</pre><p>I will explain what each table will do in our case.</p><p><strong><em>page_uri_mapping:</em></strong> this table will have a mapping between the <strong>page_uri</strong> and <strong>pagedata</strong> stringfied. we will only be <strong>keeping scaffold level json string</strong> not children items.</p><p><strong><em>page_widget_mapping:</em></strong> this table will have mapping between page and its direct child widgets. a page may or may not be present if it doesn’t have child items</p><p><strong><em>widget_widget_mapping:</em></strong> this table will have mapping between parent_widget and child_widget. a widget may or may not have child widget.</p><p><strong><em>widget:</em></strong> this table will contain details about a widget and where this will be used.</p><pre>class: PokemonData<br>fields:<br>  name: String<br>  id: String<br>  images: List&lt;String&gt;<br>  types: List&lt;String&gt;<br>  weight: double<br>  height: double<br>  stats: Map&lt;String, Map&lt;String, String&gt;&gt;</pre><p>this <strong>PokemonData</strong> will be used for <strong>Pokemon Info</strong> when we fetch from <strong>Poke Api</strong>. This doesn’t require any table in database.</p><p>now, run in <strong>pokedyn_server</strong> folder</p><pre>serverpod generate</pre><p><strong>this will generate dart models</strong> which we can use. if you see in yaml file we have added <strong>table</strong> key</p><p>after generation you will find generated code in code in <strong>generated</strong> folder and <strong>pokedyn_client</strong></p><p><strong>Step 2.</strong> Now, we create a migration</p><pre>serverpod create-migration</pre><p>this while create migration files when you run the <strong>serverpod</strong> server using the below cmd. it will create tables in the database you provided</p><pre>dart bin/main.dart --apply-migrations</pre><p><strong>Serverpod</strong> comes with <strong>docker compose </strong>file which has<strong> postgres </strong>and<strong> redis </strong>containers so if you want to use that, run this before running server</p><pre>docker-compose up --build --detach</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WaFKq67Zc6bpfgOFWjZYfQ.png" /><figcaption>containers created and running</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*eWJHDbdLTrJV-tENJUdckA.png" /><figcaption>serverpod server running</figcaption></figure><p>Below is the database created and we can see our 4 tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*m7b810eNyl8WI9dYt90SEA.png" /><figcaption>pokedyn database</figcaption></figure><p>Now, we have to insert rows in each table which will be used to create the whole json page.</p><p>What we have to do is break down the page json.</p><ol><li>scaffold level should go in <strong>page_uri_mapping</strong> and</li><li>each <strong>widget</strong> info will be inserted in widget table.</li><li>and mapping between page and direct child widgets will be inserted in <strong>page_widget_mapping</strong> and</li><li>the widgets can also have children widgets so we keep a mapping between them in <strong>widget_widget_mapping</strong>.</li></ol><p>I will add the data below</p><blockquote><strong>Note: </strong>For simplicity purpose i have not added each and every child mapping. I have tried to put child widgets in parent widget which i thought look static and don’t need any programmatic update in server.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2Vp_SFFaWvwldBjwwW6Tg.png" /><figcaption><strong>page_uri_mapping</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*gWyzTosJfZ39J9BoCkyr2g.png" /><figcaption><strong>page_widget_mapping</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*RXTKqsCEI4wtTmttfsAagA.png" /><figcaption><strong>widget_widget_mapping</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lft1JqvzA0GdIMAv7mOROw.png" /><figcaption><strong>widget</strong></figcaption></figure><p><strong>you will find the sql files </strong><a href="https://github.com/ServeDynamicUI/pokedyn-app/tree/main/pokedyn_server/sql"><strong>here</strong></a></p><p><strong>Step 3:</strong> Now, we will create endpoints which we will call from app to get pages json.</p><p>create endpoints in this folder <strong>pokedyn_server/lib/src/endpoints</strong></p><h4>First, endpoint is <strong>authPage</strong></h4><p>create <strong>authpage_endpoint.dart</strong></p><pre>class AuthPageEndpoint extends Endpoint {<br><br><br>  @override<br>  bool get requireLogin {<br>    return false;<br>  }<br><br>  Future&lt;Map&lt;String, dynamic&gt;&gt; getPage(Session session) async {<br>    PageUriMapping? page = await PageUriMapping.db.findFirstRow(session, where: (table)=&gt;table.pageUri.equals((session as MethodCallSession).endpointName));<br>    Map&lt;String, dynamic&gt; pageMap = jsonDecode(jsonDecode(page!.pageData));<br>    return pageMap..assignKeyWithRandomValues();<br>  }<br>}</pre><p>in this we create a method <strong>getPage</strong> we have to pass session object in arguments as it is necessary for <strong>serverpod</strong> to detect authentication and other stuffs.</p><p>we will be creating a authpage endpoint, its url looks like this</p><pre>&#39;http://$localhost:8080/authPage/getPage?isPageCacheEnabled=true&#39;</pre><p>in the <strong>getPage()</strong> method we are just simply getting <strong>endpointName</strong> which is authPage which we will search in <strong>page_uri_mapping</strong> table and get stringified <strong>pageData</strong>. For simplicity purpose i have kept whole page json in pageData as auth json is mostly static and we don’t need to alter any value programmatically.</p><p>if you run<strong> serverpod generate</strong> and then <strong>dart bin/main.dart — apply-migrations</strong></p><p><strong>if you hit the above url from flutter app you will get the page json working.</strong></p><pre>ServeDynamicUI.fromNetwork(<br>  DynamicRequest(<br>    url:<br>    &#39;http://$localhost:8080/authPage/getPage?isPageCacheEnabled=true&#39;,<br>    requestType: RequestType.get,<br>    sendTimeout: const Duration(seconds: 5),<br>    receiveTimeout: const Duration(seconds: 5),<br>  ),<br>  templateJsonPath: &#39;assets/json/logout_loader.json&#39;,<br>)</pre><p>Next, is we have to create endpoint for homepage which also supports pagination.</p><p>create file <strong>pokdyn_homepage_endpoint.dart</strong></p><pre>class PokedynHomepageEndpoint extends Endpoint {<br>  int offset = 0;<br>  final int limit = 10;<br>  int? totalCount;<br>  late Session session;<br><br>  @override<br>  bool get requireLogin {<br>    return false;<br>  }<br><br>  Future&lt;String&gt; getPage(Session session) async {<br>    this.session = session;<br>    Map&lt;String, dynamic&gt; queryParams = (session as MethodCallSession).queryParameters;<br><br>    PageUriMapping? page = await PageUriMapping.db.findFirstRow(session, where: (table)=&gt;table.pageUri.equals((session).endpointName));<br>    Map&lt;String, dynamic&gt; pageJsonData = jsonDecode(jsonDecode(page!.pageData));<br><br>    PageWidgetMapping? pageWidgetMapping = await PageWidgetMapping.db.findFirstRow(session, where: (table)=&gt;table.pageId.equals(page.pageId));<br>    gen.Widget? widget = await gen.Widget.db.findFirstRow(session, where: (table)=&gt;table.widgetId.equals(pageWidgetMapping!.widgetId));<br><br>    if(queryParams.containsKey(&#39;offset&#39;)){<br>      offset = int.parse(queryParams[&#39;offset&#39;]);<br><br>      List&lt;Map&lt;String, dynamic&gt;&gt; children = await _getPokemonListAndUpdateOffset(widget!.widgetData, limit, offset);<br><br>      Map&lt;String, dynamic&gt; paginatedMap = {<br>        &quot;children&quot;: children,<br>        &quot;nextUrl&quot;: offset &lt; totalCount! ? &quot;http://localhost:8080/pokedynHomepage/getPage?offset=$offset&amp;limit=5&quot; : &quot;&quot;<br>      };<br>      paginatedMap.assignKeyWithRandomValues();<br>      return jsonEncode(paginatedMap);<br>    }<br>    else {<br>      offset = 0;<br>      List&lt;Map&lt;String, dynamic&gt;&gt; children = await _getPokemonListAndUpdateOffset(widget!.widgetData, limit, offset);<br>      pageJsonData[&#39;data&#39;][&#39;children&#39;] = children;<br>      pageJsonData[&#39;data&#39;][&#39;nextUrl&#39;] = offset &lt; totalCount! ? &quot;http://localhost:8080/pokedynHomepage/getPage?offset=$offset&amp;limit=5&quot; : &quot;&quot;;<br>      pageJsonData.assignKeyWithRandomValues();<br>      return jsonEncode(pageJsonData);<br>    }<br>  }<br><br>  Future&lt;List&lt;Map&lt;String, dynamic&gt;&gt;&gt; _getPokemonListAndUpdateOffset(String widgetJsonString,int limit, int offset) async {<br>    List&lt;Map&lt;String, dynamic&gt;&gt; children = await _getPaginatedPokemonJson(widgetJsonString, limit, offset);<br>    this.offset = offset + limit;<br>    return children;<br>  }<br><br>  Future&lt;List&lt;Map&lt;String, dynamic&gt;&gt;&gt; _getPaginatedPokemonJson(String widgetJsonString, int limit, int offset) async {<br>    ....<br>  }<br><br>  Map&lt;String, dynamic&gt; _getPokemonWidget(String jsonTemplate, PokemonData pokemonData) {<br>    return Util.getMapFromString(jsonTemplate<br>        .replaceAll(&#39;{BACKEND_POKEMON_DETAIL_URL}&#39;, _getPokemonDetailPageUrl(pokemonData.id))<br>        .replaceAll(&#39;{POKEMON_TYPE_BG_COLOR_AS_PER_TYPE}&#39;, Util.getColorForPokemonType(pokemonData.types[0]))<br>        .replaceAll(&#39;{POKEMON_IMAGE}&#39;, pokemonData.images[0])<br>        .replaceAll(&#39;{POKEMON_NAME}&#39;, pokemonData.name)<br>        .replaceAll(&#39;{POKEMON_MAIN_TYPE}&#39;, pokemonData.types[0]));<br>  }<br><br>  String _getPokemonId(Uri uri){<br>    List&lt;String&gt; segments = uri.pathSegments;<br>    return segments.elementAt(segments.length-2);<br>  }<br><br>  String _getPokemonDetailPageUrl(String id){<br>    return &quot;http://localhost:8080/pokemonDetailPage/getPage?pokemon=$id&quot;;<br>  }<br><br>  List&lt;String&gt; _getPokemonTypes(List&lt;dynamic&gt; pokemonTypes){<br>    List&lt;String&gt; types = pokemonTypes.map((value) =&gt; value[&#39;type&#39;][&#39;name&#39;] as String).toList();<br>    if(types.length == 1){<br>      types.add(types[0]);<br>    }<br>    return types;<br>  }<br><br>}</pre><p>if you see in <strong>getPage()</strong> we are fetching if <strong>offset</strong> and <strong>limit</strong> are added in query params if yes then we will return our json for paginated json otherwise we return normal json.</p><pre>    Map&lt;String, dynamic&gt; queryParams = (session as MethodCallSession).queryParameters;<br><br>    PageUriMapping? page = await PageUriMapping.db.findFirstRow(session, where: (table)=&gt;table.pageUri.equals((session).endpointName));<br>    Map&lt;String, dynamic&gt; pageJsonData = jsonDecode(jsonDecode(page!.pageData));<br><br>    PageWidgetMapping? pageWidgetMapping = await PageWidgetMapping.db.findFirstRow(session, where: (table)=&gt;table.pageId.equals(page.pageId));<br>    gen.Widget? widget = await gen.Widget.db.findFirstRow(session, where: (table)=&gt;table.widgetId.equals(pageWidgetMapping!.widgetId));</pre><p>here as you can see we are first getting the page details and the trying to find child widgets and getting the widget data.</p><pre>if(queryParams.containsKey(&#39;offset&#39;)){<br>      offset = int.parse(queryParams[&#39;offset&#39;]);<br><br>      List&lt;Map&lt;String, dynamic&gt;&gt; children = await _getPokemonListAndUpdateOffset(widget!.widgetData, limit, offset);<br><br>      Map&lt;String, dynamic&gt; paginatedMap = {<br>        &quot;children&quot;: children,<br>        &quot;nextUrl&quot;: offset &lt; totalCount! ? &quot;http://localhost:8080/pokedynHomepage/getPage?offset=$offset&amp;limit=5&quot; : &quot;&quot;<br>      };<br>      paginatedMap.assignKeyWithRandomValues();<br>      return jsonEncode(paginatedMap);<br>    }<br>    else {<br>      offset = 0;<br>      List&lt;Map&lt;String, dynamic&gt;&gt; children = await _getPokemonListAndUpdateOffset(widget!.widgetData, limit, offset);<br>      pageJsonData[&#39;data&#39;][&#39;children&#39;] = children;<br>      pageJsonData[&#39;data&#39;][&#39;nextUrl&#39;] = offset &lt; totalCount! ? &quot;http://localhost:8080/pokedynHomepage/getPage?offset=$offset&amp;limit=5&quot; : &quot;&quot;;<br>      pageJsonData.assignKeyWithRandomValues();<br>      return jsonEncode(pageJsonData);<br>    }</pre><p>then if query has offset then we will fetch children items and format in paginated way and return encoded json.</p><p><strong>if offset is not present we use offset as 0.</strong></p><blockquote>One more thing we are using open source api for pokemon details which is <a href="https://pokeapi.co/">Poke Api.</a></blockquote><p>I am just simply calling the poke api endpoint which gives list of pokemons with their urls and we will use these urls to fetch the details we require about the pokemon.</p><pre>Future&lt;List&lt;Map&lt;String, dynamic&gt;&gt;&gt; _getPaginatedPokemonJson(String widgetJsonString, int limit, int offset) async {<br>    print(Uri.parse(&#39;https://pokeapi.co/api/v2/pokemon?limit=$limit&amp;offset=$offset&#39;));<br>    final response = await http.get(Uri.parse(&#39;https://pokeapi.co/api/v2/pokemon?limit=$limit&amp;offset=$offset&#39;));<br>    final data = jsonDecode(response.body);<br>    final pokemonList = data[&#39;results&#39;];<br>    totalCount ??= data[&#39;count&#39;];<br>    List&lt;Map&lt;String, dynamic&gt;&gt; paginatedJsonList = [];<br><br>    for (var pokemon in pokemonList) {<br>      final Uri pokemonUri = Uri.parse(pokemon[&#39;url&#39;]);<br>      final pokemonDetailResponse = await http.get(pokemonUri);<br>      final pokemonDetail = jsonDecode(pokemonDetailResponse.body);<br><br>      Map&lt;String, dynamic&gt; pokemonData = {<br>        &#39;name&#39;: pokemonDetail[&#39;name&#39;],<br>        &#39;types&#39;: _getPokemonTypes(pokemonDetail[&#39;types&#39;] as List&lt;dynamic&gt;),<br>        &#39;images&#39;: &lt;String&gt;[<br>          (pokemonDetail[&#39;sprites&#39;][&#39;other&#39;][&#39;official-artwork&#39;][&#39;front_default&#39;]).toString(),<br>          (pokemonDetail[&#39;sprites&#39;][&#39;other&#39;][&#39;official-artwork&#39;][&#39;front_shiny&#39;]).toString(),<br>        ],<br>        &#39;id&#39;: _getPokemonId(pokemonUri),<br>        &quot;weight&quot;:(pokemonDetail[&#39;weight&#39;] as num).toDouble() / 10,<br>        &quot;height&quot;: (pokemonDetail[&#39;height&#39;] as num).toDouble() / 10,<br>        &quot;stats&quot;: Util.getStatValue(pokemonDetail[&#39;stats&#39;] as List&lt;dynamic&gt;)<br>      };<br>      PokemonData pokemonDataModel = PokemonData.fromJson(pokemonData);<br>      session.caches.local.put(&#39;pokemon${pokemonDataModel.id}&#39;, pokemonDataModel, lifetime: Duration(minutes: 5));<br><br>      paginatedJsonList.add(_getPokemonWidget(widgetJsonString, pokemonDataModel));<br>    }<br><br>    return paginatedJsonList;<br>  }</pre><p>If you see once we fetch a data about pokemon then will inflate the widget json for different pokemons. We are also caching the pokemon data in memory using serverpod cache mechanism.</p><pre>Map&lt;String, dynamic&gt; _getPokemonWidget(String jsonTemplate, Map&lt;String, dynamic&gt; pokemonData) {<br>  return Util.getMapFromString(jsonTemplate<br>      .replaceAll(&#39;{BACKEND_POKEMON_DETAIL_URL}&#39;, _getPokemonDetailPageUrl(pokemonData[&#39;id&#39;]))<br>      .replaceAll(&#39;{POKEMON_TYPE_BG_COLOR_AS_PER_TYPE}&#39;, Util.getColorForPokemonType(pokemonData[&#39;type&#39;]))<br>      .replaceAll(&#39;{POKEMON_IMAGE}&#39;, pokemonData[&#39;image&#39;])<br>      .replaceAll(&#39;{POKEMON_NAME}&#39;, pokemonData[&#39;name&#39;])<br>      .replaceAll(&#39;{POKEMON_MAIN_TYPE}&#39;, pokemonData[&#39;type&#39;]));<br>}</pre><p>Using this method we will inflate the json string for a pokemon this we will repeat for all <strong>Pokemons</strong> for that particular <strong>offset</strong> and <strong>limit</strong>.</p><p>and one more thing we will <strong>generate random keys</strong> for all dynamic widgets using the below map extension</p><pre>pageJsonData.assignKeyWithRandomValues();</pre><pre>extension MapUtil on Map&lt;String,dynamic&gt;{<br><br>  void assignKeyWithRandomValues(){<br>    forEach((key, value) {<br>      if (key == &#39;key&#39;) {<br>        this[key] = Util.generateRandomString(15);<br>      } else if (value is Map&lt;String, dynamic&gt;) {<br>        value.assignKeyWithRandomValues();<br>      } else if (value is List) {<br>        for (var item in value) {<br>          if (item is Map&lt;String, dynamic&gt;) {<br>            item.assignKeyWithRandomValues();<br>          }<br>        }<br>      }<br>    });<br>  }<br>}</pre><p><strong>if you generate and run the server and hit the below url it will work.</strong></p><pre>ServeDynamicUI.fromNetwork(<br>  DynamicRequest(<br>    url: &#39;http://$localhost:8080/pokedynHomepage/getPage?isPageCacheEnabled=true&#39;,<br>    requestType: RequestType.get,<br>    sendTimeout: const Duration(seconds: 15),<br>    receiveTimeout: const Duration(seconds: 15),<br>  ),<br>  templateJsonPath: &#39;assets/json/shimmers/pokedyn_home_page_shimmer.json&#39;,<br>)</pre><h4>Last endpoint is <strong>pokemon_detail_page_endpoint.dart</strong></h4><pre>class PokemonDetailPageEndpoint extends Endpoint {<br>  <br>  Map&lt;String, dynamic&gt;? pokemonDetail;<br>  <br>  Future&lt;String&gt; getPage(Session session) async {<br>    Map&lt;String, dynamic&gt; query = (session as MethodCallSession).queryParameters;<br>    if (!query.containsKey(&#39;pokemon&#39;)) {<br>      return &#39;&#39;;<br>    }<br><br>    String pokemonId = query[&#39;pokemon&#39;];<br>    pokemonDetail = await _fetchPokemonData(pokemonId);<br>    <br>    assert(pokemonDetail != null);<br><br>    PageUriMapping? page = await PageUriMapping.db.findFirstRow(session,<br>        where: (table) =&gt; table.pageUri.equals((session).endpointName));<br>    Map&lt;String, dynamic&gt; pageJsonData = jsonDecode(<br>      jsonDecode(page!.pageData<br>          .replaceAll(&quot;{POKEMON_ID}&quot;, _formatId(pokemonId))<br>          .replaceAll(&quot;{LINEAR_GRADIENT_AS_PER_POKEMON_MAIN_TYPE}&quot;, Util.getPokemonTypeGradient(pokemonDetail![&#39;types&#39;][0]))),<br>    );<br><br>    List&lt;PageWidgetMapping&gt;? pageWidgetMappingList = await PageWidgetMapping.db.find(session, where: (table) =&gt; table.pageId.equals(page.pageId));<br><br>    Set&lt;int&gt; parentWidgetIds = {};<br>    for (PageWidgetMapping pageWidgetMapping in pageWidgetMappingList) {<br>      parentWidgetIds.add(pageWidgetMapping.widgetId);<br>    }<br><br>    List&lt;WidgetWidgetMapping&gt;? widgetWidgetMappings = await WidgetWidgetMapping.db.find(session, where: (table) =&gt; table.parentWidget.inSet(parentWidgetIds));<br>    Set&lt;int&gt; widgetIds = {};<br>    for (WidgetWidgetMapping widgetWidgetMapping in widgetWidgetMappings) {<br>      widgetIds.add(widgetWidgetMapping.parentWidget);<br>      if(widgetWidgetMapping.childWidgetId != null){<br>        widgetIds.add(widgetWidgetMapping.childWidgetId!);<br>      }<br>    }<br>    <br>    List&lt;gen.Widget&gt;? widgets = await gen.Widget.db.find(session, where: (table) =&gt; table.widgetId.inSet(widgetIds));<br><br>    String carouselJsonString = &quot;&quot;;<br>    String pokemonCarouselCardJsonString = &quot;&quot;;<br>    String pokemonDetailPokemonNameJsonString = &quot;&quot;;<br>    String pokemonDetailPokemonTypeRowJsonString = &quot;&quot;;<br>    String pokemonDetailBaseStatsTextJsonString = &quot;&quot;;<br>    String pokemonDetailStatsColumnJsonString = &quot;&quot;;<br>    String pokemonDetailStatPercentIndicatorJsonString = &quot;&quot;;<br><br>    for(gen.Widget widget in widgets){<br>      if(widget.widgetName == &quot;pokemon_carousel&quot;){<br>        carouselJsonString = widget.widgetData;<br>      }<br>      else if(widget.widgetName == &quot;pokemon_carousel_card&quot;){<br>        pokemonCarouselCardJsonString = widget.widgetData;<br>      }<br>      else if(widget.widgetName == &quot;pokemon_detail_pokemon_name&quot;){<br>        pokemonDetailPokemonNameJsonString = widget.widgetData;<br>      }<br>      else if(widget.widgetName == &quot;pokemon_detail_pokemon_type_row&quot;){<br>        pokemonDetailPokemonTypeRowJsonString = widget.widgetData;<br>      }<br>      else if(widget.widgetName == &quot;pokemon_detail_base_stats_text&quot;){<br>        pokemonDetailBaseStatsTextJsonString = widget.widgetData;<br>      }<br>      else if(widget.widgetName == &quot;pokemon_detail_stats_column&quot;){<br>        pokemonDetailStatsColumnJsonString = widget.widgetData;<br>      }<br>      else if(widget.widgetName == &quot;pokemon_detail_stat_percent_indicator&quot;){<br>        pokemonDetailStatPercentIndicatorJsonString = widget.widgetData;<br>      }<br>    }<br>    <br>    Map&lt;String, dynamic&gt; carouselJson = Util.getMapFromString(carouselJsonString.replaceAll(&#39;{KEY_1}&#39;, Util.generateRandomString(10)));<br><br>    _addCarouselCards(carouselJson, pokemonCarouselCardJsonString);<br><br>    pageJsonData[&#39;data&#39;][&#39;children&#39;] = [];<br>    (pageJsonData[&#39;data&#39;][&#39;children&#39;] as List)<br>        ..add(carouselJson)<br>        ..add(_addPokemonNameCard(pokemonDetailPokemonNameJsonString))<br>        ..add(_addPokemonTypeRow(pokemonDetailPokemonTypeRowJsonString))<br>        ..add(_addPokemonBaseStatsText(pokemonDetailBaseStatsTextJsonString))<br>        ..add(_addPokemonStatsColumn(pokemonDetailStatsColumnJsonString, pokemonDetailStatPercentIndicatorJsonString));<br><br>    pageJsonData.assignKeyWithRandomValues();<br>    return jsonEncode(pageJsonData);<br>  }<br><br>  Map&lt;String, dynamic&gt; _addPokemonStatsColumn(String pokemonDetailStatsColumnJsonString, String pokemonDetailStatPercentIndicatorJsonString){<br>    ....<br>  }<br><br>  Map&lt;String, dynamic&gt; _addPokemonBaseStatsText(String pokemonDetailBaseStatsTextJsonString){<br>    Map&lt;String, dynamic&gt; pokemonDetailPokemonNameJson = Util.getMapFromString(pokemonDetailBaseStatsTextJsonString);<br>    return pokemonDetailPokemonNameJson;<br>  }<br><br>  Map&lt;String, dynamic&gt; _addPokemonNameCard(String pokemonDetailPokemonName){<br>    Map&lt;String, dynamic&gt; pokemonDetailPokemonNameJson = Util.getMapFromString(pokemonDetailPokemonName.replaceAll(&quot;{POKEMON_NAME}&quot;, pokemonDetail![&#39;name&#39;]));<br>    return pokemonDetailPokemonNameJson;<br>  }<br><br>  Map&lt;String, dynamic&gt; _addPokemonTypeRow(String pokemonTypeDetailString){<br>    ....<br>  }<br><br>  void _addCarouselCards(Map&lt;String, dynamic&gt; carouselJson, String pokemonCarouselCardJsonString){<br>    .....<br>  }<br><br>  String _formatId(String id) {<br>    return &#39;#${id.padLeft(4, &#39;0&#39;)}&#39;;<br>  }<br><br>  Future&lt;Map&lt;String, dynamic&gt;&gt; _fetchPokemonData(String pokemonId) async {<br>    ....<br>  }<br><br>  List&lt;String&gt; _getPokemonTypes(List&lt;dynamic&gt; pokemonTypes){<br>    List&lt;String&gt; types = pokemonTypes.map((value) =&gt; value[&#39;type&#39;][&#39;name&#39;] as String).toList();<br>    if(types.length == 1){<br>      types.add(types[0]);<br>    }<br>    return types;<br>  }<br><br>  Map&lt;String, Map&lt;String, dynamic&gt;&gt; _getStatValue(List&lt;dynamic&gt; statsList){<br>    .....<br>  }<br>}</pre><p>In the <strong>getPage()</strong> in this we need pokemon id for which we have to show the details we will get it from query params (<strong>pokemon</strong>).</p><p>Now once we get the pokemon id we will call <strong>poke api</strong> to fetch all info we need to show in this page.</p><pre>Future&lt;PokemonData&gt; _fetchPokemonData(String pokemonId) async {<br>    PokemonData? pokemonData = await session.caches.local.get&lt;PokemonData&gt;(&#39;pokemon$pokemonId&#39;);<br>    if(pokemonData != null) return pokemonData;<br><br>    final response = await http.get(Uri.parse(&#39;https://pokeapi.co/api/v2/pokemon/$pokemonId/&#39;));<br><br>    if (response.statusCode == 200) {<br>      Map&lt;String, dynamic&gt; pokemonDetail = jsonDecode(response.body);<br>      Map&lt;String, dynamic&gt; pokemonData = {<br>        &#39;name&#39;: pokemonDetail[&#39;name&#39;],<br>        &#39;types&#39;: _getPokemonTypes(pokemonDetail[&#39;types&#39;] as List&lt;dynamic&gt;),<br>        &#39;images&#39;: &lt;String&gt;[<br>          (pokemonDetail[&#39;sprites&#39;][&#39;other&#39;][&#39;official-artwork&#39;][&#39;front_default&#39;]).toString(),<br>          (pokemonDetail[&#39;sprites&#39;][&#39;other&#39;][&#39;official-artwork&#39;][&#39;front_shiny&#39;]).toString(),<br>        ],<br>        &#39;id&#39;: pokemonId,<br>        &quot;weight&quot;:(pokemonDetail[&#39;weight&#39;] as num).toDouble() / 10,<br>        &quot;height&quot;: (pokemonDetail[&#39;height&#39;] as num).toDouble() / 10,<br>        &quot;stats&quot;: Util.getStatValue(pokemonDetail[&#39;stats&#39;] as List&lt;dynamic&gt;)<br>      };<br>      PokemonData pokemonDataModel = PokemonData.fromJson(pokemonData);<br>      session.caches.local.put(&#39;pokemon${pokemonDataModel.id}&#39;, pokemonDataModel, lifetime: Duration(minutes: 5));<br>      return pokemonDataModel;<br>    } else {<br>      throw Exception(&#39;Failed to load Pokémon data&#39;);<br>    }<br>  }</pre><p>if you see we are doing caching of pokemon info as we are already calling the same api endpoint in the previous homepage so instead of again doing network call we get it from cache. <strong>Serverpod internally has caching mechanism which store this data in memory.</strong></p><p>If you run the servepod after generating code. you can hit the url here id will be pokemon id.</p><pre>http://localhost:8080/pokemonDetailPage/getPage?pokemon=$id</pre><p><strong>This we will be using on clicking the card so we will not be using this in session manager widget.</strong></p><p>So, now if you want to update any part of screen like ordering the widgets differently you just update the backend and app will show the changes or changing the background image of login screen all these things can now be changed from backend.</p><p>You will find all the code in <a href="https://github.com/ServeDynamicUI/pokedyn-app/"><strong>Pokedyn Repo</strong></a></p><p><strong>This is the Backend Part of Developing Full App using Serverpod and serve_dynamic_ui. There are more efficient ways to implement backend for Server Driven UI.</strong></p><h3>Thank You For Reading Article</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b540c5c6fb68" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/server-driven-ui-backend-implementation-from-scratch-using-serverpod-part-6-b540c5c6fb68">Server-Driven UI Backend Implementation from Scratch Using Serverpod: Part 6</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server-Driven UI in Flutter from Scratch: Part 5 — Building Complete App End-to-End using Serverpod]]></title>
            <link>https://levelup.gitconnected.com/server-driven-ui-in-flutter-from-scratch-part-5-building-complete-app-end-to-end-using-serverpod-c07ccacf5a11?source=rss-1e41946a95c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c07ccacf5a11</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[serverpod]]></category>
            <dc:creator><![CDATA[Sk Ahron]]></dc:creator>
            <pubDate>Sun, 28 Jul 2024 17:02:39 GMT</pubDate>
            <atom:updated>2024-07-30T06:21:33.592Z</atom:updated>
            <content:encoded><![CDATA[<h3>Server-Driven UI in Flutter from Scratch: Part 5 — Building Complete App End-to-End using Serverpod</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*0wYIVjd1OlWDegKkUKMNUw.jpeg" /><figcaption>serve_dynamic_ui</figcaption></figure><p>In this Article, We will be implementing the server driven UI app backend using <a href="https://serverpod.dev/"><strong>Serverpod</strong></a> which is dart based framework to build backend.</p><p>We will be building <strong>Pokedyn flutter app</strong> which uses <a href="https://pub.dev/packages/serve_dynamic_ui"><strong>serve_dynamic_ui</strong></a> package and <strong>Serverpod</strong> for backend.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FrC6ibQc4KpA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrC6ibQc4KpA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FrC6ibQc4KpA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7d8e74585e4df4be40fa4af1ac6afe3/href">https://medium.com/media/c7d8e74585e4df4be40fa4af1ac6afe3/href</a></iframe><p>This article will be more inclined towards designing UI for your server driven UI app. This article is just to give you an idea how you can build app server which serves dynamic UI for your app.</p><blockquote><strong>Note:</strong> This is not the most efficient way to implement your backend it is just to give you an idea.</blockquote><p>Choosing <a href="https://serverpod.dev/"><strong>Serverpod</strong></a> to develop our backend as it is dart based implementation to develop backends so do it checkout.</p><p>Lets Begin.</p><p>You might have got the idea what we are going to build. We will create a simple app which gives the Pokemon Details with basic authentication and good looking UI using <a href="https://pub.dev/packages/serve_dynamic_ui"><strong>serve_dynamic_ui</strong></a>.</p><blockquote><strong>Note:</strong> You must read previous parts as I will not cover what is already covered previously</blockquote><p><strong>Checkout</strong><a href="https://github.com/ServeDynamicUI/pokedyn-app"><strong> Pokedyn app code</strong></a></p><h4>Let Start Implementing</h4><p>As we are using <strong>serverpod</strong> and serverpod has a starter repo</p><p>you need to follow commands mentioned by serverpod</p><pre>dart pub global activate serverpod_cli</pre><pre>serverpod create pokedyn</pre><p>it will create starter code having main folders pokedyn_flutter, pokedyn_server and pokedyn_client.</p><p><strong>pokedyn_flutter:</strong> is the place our flutter app code will be there.</p><p><strong>pokedyn_server:</strong> is the place where we write backend logic.</p><p><strong>pokedyn_client:</strong> is the place where all the generated code will be created by serverpod.</p><p>So, first we will work in <strong>pokedyn_flutter</strong> folder.</p><p>this section will be mostly designing our UI by creating Json Structure which we want for each page.</p><ol><li>In <strong>pubspec.yaml</strong> add</li></ol><pre>serve_dynamic_ui: ^1.0.1</pre><p>this will get the <strong>serve_dynamic_ui</strong> dependency so that we can build our dynamic screens app.</p><p>2. Now, we will first create dynamic screen <strong>jsons</strong> which later we will fetch from our server as per our page endpoints.</p><p>We will first create json for this screen our <strong>login screen</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*EhYtPuTplhavhqxu41D5HA.gif" /><figcaption>login screen</figcaption></figure><p>if you see form elements are on top of full screen image. I have used <strong>dy_stack</strong> where <strong>dy_image</strong> and <strong>dy_column</strong> are in the stack.</p><pre>{<br>  &quot;type&quot;: &quot;dy_scaffold&quot;,<br>  &quot;data&quot;: {<br>    &quot;key&quot;: &quot;1236456&quot;,<br>    &quot;appBar&quot;: {<br>      &quot;pageTitle&quot;: &quot;Pokedyn Login&quot;,<br>      &quot;appBarGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xff42A5F5,0xffAB47BC&quot;<br>    },<br>    &quot;scrollable&quot;: false,<br>    &quot;mainAxisAlignment&quot;: &quot;start&quot;,<br>    &quot;children&quot;: [{<br>      &quot;type&quot;: &quot;dy_container&quot;,<br>      &quot;data&quot;: {<br>        &quot;key&quot;: &quot;223236423&quot;,<br>        &quot;backgroundColor&quot;: &quot;0xff90EE90&quot;,<br>        &quot;height&quot;: -1,<br>        &quot;child&quot;: {<br>          &quot;type&quot;: &quot;dy_stack&quot;,<br>          &quot;data&quot;: {<br>            &quot;key&quot;: &quot;2234656231&quot;,<br>            &quot;alignment&quot;: &quot;center&quot;,<br>            &quot;children&quot;: [<br>              {<br>                &quot;type&quot;: &quot;dy_container&quot;,<br>                &quot;data&quot;: {<br>                  &quot;key&quot;: &quot;123123&quot;,<br>                  &quot;child&quot;: {<br>                    &quot;type&quot;: &quot;dy_image&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;212226323233&quot;,<br>                      &quot;src&quot;: &quot;https://w0.peakpx.com/wallpaper/998/140/HD-wallpaper-pikachu-pokemon.jpg&quot;,<br>                      &quot;width&quot;: -1,<br>                      &quot;height&quot;: -1,<br>                      &quot;imageType&quot;: &quot;network&quot;,<br>                      &quot;fit&quot;: &quot;fill&quot;,<br>                      &quot;placeholderImagePath&quot;: &quot;assets/images/ic_login_placeholder.jpg&quot;,<br>                      &quot;transitionDuration&quot;: &quot;:::3:&quot;<br>                    }<br>                  }<br>                }<br>              },<br>              {<br>                &quot;type&quot;: &quot;dy_column&quot;,<br>                &quot;data&quot;: {<br>                  &quot;key&quot;: &quot;12313&quot;,<br>                  &quot;mainAxisAlignment&quot;: &quot;end&quot;,<br>                  &quot;children&quot;: [<br>                    {<br>                      &quot;type&quot;: &quot;dy_container&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;34755345345345&quot;,<br>                        &quot;width&quot;: 300,<br>                        &quot;child&quot;: {<br>                          &quot;type&quot;: &quot;dy_text_field&quot;,<br>                          &quot;data&quot;: {<br>                            &quot;key&quot;: &quot;784867234hwdf&quot;,<br>                            &quot;initialText&quot;: &quot;&quot;,<br>                            &quot;textFieldDecoration&quot;: {<br>                              &quot;textAlign&quot;: &quot;start&quot;,<br>                              &quot;obscureText&quot;: false,<br>                              &quot;maxLines&quot;: 1,<br>                              &quot;decoration&quot;: {<br>                                &quot;fillColor&quot;: &quot;0xFFFFFFFF&quot;,<br>                                &quot;filled&quot;: true,<br>                                &quot;hintText&quot;: &quot;Enter Email Address&quot;,<br>                                &quot;labelText&quot;: &quot;Email&quot;,<br>                                &quot;focusBorderColor&quot;: &quot;0xFFFFA500&quot;,<br>                                &quot;borderWidth&quot;: 3,<br>                                &quot;borderRadius&quot;: 10,<br>                                &quot;labelStyle&quot;: {<br>                                  &quot;fontSize&quot;: 15,<br>                                  &quot;fontWeight&quot;: &quot;bold&quot;,<br>                                  &quot;color&quot;: &quot;0xFF000000&quot;<br>                                },<br>                                &quot;hintStyle&quot;: {<br>                                  &quot;fontSize&quot;: 15,<br>                                  &quot;fontWeight&quot;: &quot;bold&quot;,<br>                                  &quot;color&quot;: &quot;0xFF888888&quot;<br>                                }<br>                              },<br>                              &quot;style&quot;: {<br>                                &quot;color&quot;: &quot;0xFF000000&quot;,<br>                                &quot;fontSize&quot;: 25<br>                              },<br>                              &quot;errorText&quot;: &quot;Please Enter Valid Email Address.&quot;,<br>                              &quot;errorTextStyle&quot;: {<br>                                &quot;fontWeight&quot;: &quot;bold&quot;,<br>                                &quot;color&quot;: &quot;0xffFF0000&quot;<br>                              },<br>                              &quot;cursorColor&quot;: &quot;0xFF0000FF&quot;<br>                            },<br>                            &quot;regexValidator&quot;: &quot;^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$&quot;<br>                          }<br>                        }<br>                      }<br>                    },<br>                    {<br>                      &quot;type&quot;: &quot;dy_sized_box&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;827487246&quot;,<br>                        &quot;height&quot;: 30<br>                      }<br>                    },<br>                    {<br>                      &quot;type&quot;: &quot;dy_container&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;98274924724&quot;,<br>                        &quot;width&quot;: 300,<br>                        &quot;child&quot;: {<br>                          &quot;type&quot;: &quot;dy_text_field&quot;,<br>                          &quot;data&quot;: {<br>                            &quot;key&quot;: &quot;8723462434&quot;,<br>                            &quot;initialText&quot;: &quot;&quot;,<br>                            &quot;textFieldDecoration&quot;: {<br>                              &quot;textAlign&quot;: &quot;start&quot;,<br>                              &quot;obscureText&quot;: false,<br>                              &quot;maxLines&quot;: 1,<br>                              &quot;decoration&quot;: {<br>                                &quot;fillColor&quot;: &quot;0xFFFFFFFF&quot;,<br>                                &quot;filled&quot;: true,<br>                                &quot;hintText&quot;: &quot;Enter User Name&quot;,<br>                                &quot;labelText&quot;: &quot;UserName&quot;,<br>                                &quot;focusBorderColor&quot;: &quot;0xFFFFA500&quot;,<br>                                &quot;borderWidth&quot;: 3,<br>                                &quot;borderRadius&quot;: 10,<br>                                &quot;labelStyle&quot;: {<br>                                  &quot;fontSize&quot;: 15,<br>                                  &quot;fontWeight&quot;: &quot;bold&quot;,<br>                                  &quot;color&quot;: &quot;0xFF000000&quot;<br>                                },<br>                                &quot;hintStyle&quot;: {<br>                                  &quot;fontSize&quot;: 15,<br>                                  &quot;fontWeight&quot;: &quot;bold&quot;,<br>                                  &quot;color&quot;: &quot;0xFF888888&quot;<br>                                }<br>                              },<br>                              &quot;style&quot;: {<br>                                &quot;color&quot;: &quot;0xFF000000&quot;,<br>                                &quot;fontSize&quot;: 25<br>                              },<br>                              &quot;errorText&quot;: &quot;User Name Should be At least 6 characters long.&quot;,<br>                              &quot;errorTextStyle&quot;: {<br>                                &quot;fontWeight&quot;: &quot;bold&quot;,<br>                                &quot;color&quot;: &quot;0xffFF0000&quot;<br>                              },<br>                              &quot;cursorColor&quot;: &quot;0xFF0000FF&quot;<br>                            },<br>                            &quot;regexValidator&quot;: &quot;^.{6,}$&quot;<br>                          }<br>                        }<br>                      }<br>                    },<br>                    {<br>                      &quot;type&quot;: &quot;dy_sized_box&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;82462842&quot;,<br>                        &quot;height&quot;: 30<br>                      }<br>                    },<br>                    {<br>                      &quot;type&quot;: &quot;dy_button&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;87628624&quot;,<br>                        &quot;buttonColor&quot;: &quot;0xff90EE90&quot;,<br>                        &quot;buttonBorderRadius&quot;: 10,<br>                        &quot;padding&quot;: &quot;10&quot;,<br>                        &quot;width&quot;: 200,<br>                        &quot;child&quot;: {<br>                          &quot;type&quot;: &quot;dy_text&quot;,<br>                          &quot;data&quot;: {<br>                            &quot;key&quot;: &quot;23242342&quot;,<br>                            &quot;text&quot;: &quot;Login&quot;,<br>                            &quot;style&quot;: {<br>                              &quot;color&quot;: &quot;0xffffffff&quot;,<br>                              &quot;fontWeight&quot;: &quot;bold&quot;,<br>                              &quot;fontSize&quot;: 20<br>                            }<br>                          }<br>                        },<br>                        &quot;action&quot;: {<br>                          &quot;actionString&quot;: &quot;/login&quot;<br>                        }<br>                      }<br>                    },<br>                    {<br>                      &quot;type&quot;: &quot;dy_sized_box&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;82462842&quot;,<br>                        &quot;height&quot;: 150<br>                      }<br>                    }<br>                  ]<br>                }<br>              }<br>            ]<br>          }<br>        }<br>      }<br>    }]<br>  }<br>}</pre><p>if you see, I am using <strong>dy_image</strong> where width and height of the image set is screen size by passing <strong>-1</strong>. if you pass negative value to <strong>height</strong> and <strong>width</strong> internally <strong>serve_dynamic_ui</strong> will consider it as full screen height and width not including app bar and status bar height. If you see I have also added <strong>transitionDuration </strong>which will give that smooth transition between placeholder image and network image.</p><pre>{<br>  &quot;type&quot;: &quot;dy_image&quot;,<br>  &quot;data&quot;: {<br>    &quot;key&quot;: &quot;212226323233&quot;,<br>    &quot;src&quot;: &quot;https://w0.peakpx.com/wallpaper/998/140/HD-wallpaper-pikachu-pokemon.jpg&quot;,<br>    &quot;width&quot;: -1,<br>    &quot;height&quot;: -1,<br>    &quot;imageType&quot;: &quot;network&quot;,<br>    &quot;fit&quot;: &quot;fill&quot;,<br>    &quot;placeholderImagePath&quot;: &quot;assets/images/ic_login_placeholder.jpg&quot;<br>  }<br>}</pre><p>Then In the <strong>dy_column</strong> we are using 2 dy_text_field widgets and a button</p><pre>{<br>  &quot;type&quot;: &quot;dy_column&quot;,<br>  &quot;data&quot;: {<br>    &quot;key&quot;: &quot;12313&quot;,<br>    &quot;mainAxisAlignment&quot;: &quot;end&quot;,<br>    &quot;children&quot;: [<br>      {<br>        &quot;type&quot;: &quot;dy_sized_box&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;82462842&quot;,<br>          &quot;height&quot;: 30<br>        }<br>      },<br>      {<br>        &quot;type&quot;: &quot;dy_container&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;34755345345345&quot;,<br>          &quot;width&quot;: 300,<br>          &quot;child&quot;: {<br>            &quot;type&quot;: &quot;dy_text_field&quot;,<br>            &quot;data&quot;: {<br>              &quot;key&quot;: &quot;784867234hwdf&quot;,<br>              &quot;initialText&quot;: &quot;&quot;,<br>              &quot;textFieldDecoration&quot;: {<br>                &quot;textAlign&quot;: &quot;start&quot;,<br>                &quot;obscureText&quot;: false,<br>                &quot;maxLines&quot;: 1,<br>                &quot;decoration&quot;: {<br>                  &quot;fillColor&quot;: &quot;0xFFFFFFFF&quot;,<br>                  &quot;filled&quot;: true,<br>                  &quot;hintText&quot;: &quot;Enter Email Address&quot;,<br>                  &quot;labelText&quot;: &quot;Email&quot;,<br>                  &quot;focusBorderColor&quot;: &quot;0xFFFFA500&quot;,<br>                  &quot;borderWidth&quot;: 3,<br>                  &quot;borderRadius&quot;: 10,<br>                  &quot;labelStyle&quot;: {<br>                    &quot;fontSize&quot;: 15,<br>                    &quot;fontWeight&quot;: &quot;bold&quot;,<br>                    &quot;color&quot;: &quot;0xFF000000&quot;<br>                  },<br>                  &quot;hintStyle&quot;: {<br>                    &quot;fontSize&quot;: 15,<br>                    &quot;fontWeight&quot;: &quot;bold&quot;,<br>                    &quot;color&quot;: &quot;0xFF888888&quot;<br>                  }<br>                },<br>                &quot;style&quot;: {<br>                  &quot;color&quot;: &quot;0xFF000000&quot;,<br>                  &quot;fontSize&quot;: 25<br>                },<br>                &quot;errorText&quot;: &quot;Please Enter Valid Email Address.&quot;,<br>                &quot;errorTextStyle&quot;: {<br>                  &quot;fontWeight&quot;: &quot;bold&quot;,<br>                  &quot;color&quot;: &quot;0xffFF0000&quot;<br>                },<br>                &quot;cursorColor&quot;: &quot;0xFF0000FF&quot;<br>              },<br>              &quot;regexValidator&quot;: &quot;^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$&quot;<br>            }<br>          }<br>        }<br>      },<br>      {<br>        &quot;type&quot;: &quot;dy_sized_box&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;827487246&quot;,<br>          &quot;height&quot;: 30<br>        }<br>      },<br>      {<br>        &quot;type&quot;: &quot;dy_container&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;98274924724&quot;,<br>          &quot;width&quot;: 300,<br>          &quot;child&quot;: {<br>            &quot;type&quot;: &quot;dy_text_field&quot;,<br>            &quot;data&quot;: {<br>              &quot;key&quot;: &quot;8723462434&quot;,<br>              &quot;initialText&quot;: &quot;&quot;,<br>              &quot;textFieldDecoration&quot;: {<br>                &quot;textAlign&quot;: &quot;start&quot;,<br>                &quot;obscureText&quot;: false,<br>                &quot;maxLines&quot;: 1,<br>                &quot;decoration&quot;: {<br>                  &quot;fillColor&quot;: &quot;0xFFFFFFFF&quot;,<br>                  &quot;filled&quot;: true,<br>                  &quot;hintText&quot;: &quot;Enter User Name&quot;,<br>                  &quot;labelText&quot;: &quot;UserName&quot;,<br>                  &quot;focusBorderColor&quot;: &quot;0xFFFFA500&quot;,<br>                  &quot;borderWidth&quot;: 3,<br>                  &quot;borderRadius&quot;: 10,<br>                  &quot;labelStyle&quot;: {<br>                    &quot;fontSize&quot;: 15,<br>                    &quot;fontWeight&quot;: &quot;bold&quot;,<br>                    &quot;color&quot;: &quot;0xFF000000&quot;<br>                  },<br>                  &quot;hintStyle&quot;: {<br>                    &quot;fontSize&quot;: 15,<br>                    &quot;fontWeight&quot;: &quot;bold&quot;,<br>                    &quot;color&quot;: &quot;0xFF888888&quot;<br>                  }<br>                },<br>                &quot;style&quot;: {<br>                  &quot;color&quot;: &quot;0xFF000000&quot;,<br>                  &quot;fontSize&quot;: 25<br>                },<br>                &quot;errorText&quot;: &quot;User Name Should be At least 6 characters long.&quot;,<br>                &quot;errorTextStyle&quot;: {<br>                  &quot;fontWeight&quot;: &quot;bold&quot;,<br>                  &quot;color&quot;: &quot;0xffFF0000&quot;<br>                },<br>                &quot;cursorColor&quot;: &quot;0xFF0000FF&quot;<br>              },<br>              &quot;regexValidator&quot;: &quot;^.{6,}$&quot;<br>            }<br>          }<br>        }<br>      },<br>      {<br>        &quot;type&quot;: &quot;dy_sized_box&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;82462842&quot;,<br>          &quot;height&quot;: 30<br>        }<br>      },<br>      {<br>        &quot;type&quot;: &quot;dy_button&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;87628624&quot;,<br>          &quot;buttonColor&quot;: &quot;0xff90EE90&quot;,<br>          &quot;buttonBorderRadius&quot;: 10,<br>          &quot;padding&quot;: &quot;10&quot;,<br>          &quot;width&quot;: 200,<br>          &quot;child&quot;: {<br>            &quot;type&quot;: &quot;dy_text&quot;,<br>            &quot;data&quot;: {<br>              &quot;key&quot;: &quot;23242342&quot;,<br>              &quot;text&quot;: &quot;Login&quot;,<br>              &quot;style&quot;: {<br>                &quot;color&quot;: &quot;0xffffffff&quot;,<br>                &quot;fontWeight&quot;: &quot;bold&quot;,<br>                &quot;fontSize&quot;: 20<br>              }<br>            }<br>          },<br>          &quot;action&quot;: {<br>            &quot;actionString&quot;: &quot;/login&quot;<br>          }<br>        }<br>      },<br>      {<br>        &quot;type&quot;: &quot;dy_sized_box&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;82462842&quot;,<br>          &quot;height&quot;: 150<br>        }<br>      }<br>    ]<br>  }<br>}</pre><p>I have set <strong>regex validators</strong> for both<strong> text field</strong> widgets and the <strong>dy_button</strong> click action string is <strong>/login</strong> this is a custom action which we will create.</p><p>So, we will create the <strong>login action handler</strong></p><pre>class LoginActionHandler extends ActionHandler {<br>  @override<br>  void handleAction(BuildContext? context, Uri action,<br>      Map&lt;String, dynamic&gt;? extras, OnHandledAction? onHandledAction) async {<br>    if (context?.mounted ?? false) {<br>      ActionHandlersRepo.handle(<br>          ActionDTO(&quot;/form&quot;, extras), extras![&#39;widget&#39;], context!,<br>          (value) async {<br>        if (value is Map) {<br>          SessionManagerState.instance.sessionStreamController.sink.add(<br>            SessionOnAuthenticatedEvent(<br>              authInfo: {<br>                &#39;email&#39;: value[&#39;textFieldData&#39;][0],<br>                &#39;userName&#39;: value[&#39;textFieldData&#39;][1],<br>              },<br>            ),<br>          );<br>        }<br>      });<br>    }<br>  }<br>}</pre><p>here is the code for it as after filling the details user presses the button it will call this action handler. If you see internally in this action we are calling <strong>/form</strong> action which help use to get all the form values if valid otherwise it will show the error text which we passed.</p><p>For <strong>serve_dynamic_ui</strong> to detect this custom action handler we have to register this handler.</p><pre>void main() {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  ServeDynamicUI.init(actionHandlers: {<br>    RegExp(r&#39;(^/?login/?$)&#39;): LoginActionHandler(),<br>  });<br>  runApp(const MyApp());<br>}</pre><p>I am registering the <strong>LoginActionHandler</strong> in init of package make sure you add this line. If you don’t call this before init it will create issues in page caching.</p><pre>WidgetsFlutterBinding.ensureInitialized();</pre><p>Now, to test this what we have to do is in <strong>runApp</strong> add <strong>MyApp</strong> widget which has <strong>ServeDynamicUIMaterialApp</strong> and also make sure to pass <strong>navigationKey</strong> otherwise <strong>serve_dynamic_ui</strong> will not be able to detect context of application properly.</p><pre>class MyApp extends StatefulWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  State&lt;MyApp&gt; createState() =&gt; _MyAppState();<br>}<br><br>class _MyAppState extends State&lt;MyApp&gt; {<br>  late GlobalKey&lt;NavigatorState&gt; navigationKey;<br>  @override<br>  void initState() {<br>    navigationKey = GlobalKey&lt;NavigatorState&gt;();<br>    super.initState();<br>  }<br>  @override<br>  Widget build(BuildContext context) {<br>    return ServeDynamicUIMaterialApp(<br>      navigatorKey: navigationKey,<br>      home: (context) {<br>        return ServeDynamicUI.fromAssets(<br>          &#39;assets/json/login_page.json&#39;,<br>        );<br>      },<br>      title: &#39;Flutter Demo&#39;,<br>      theme: ThemeData(<br>        colorScheme: ColorScheme.fromSeed(seedColor: Colors.green),<br>        useMaterial3: false,<br>      ),<br>      debugShowCheckedModeBanner: false,<br>    );<br>  }<br>}</pre><p>and run the app now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*9abJGP-qETEbO1qv1w0S5g.gif" /><figcaption>login screen</figcaption></figure><p>if you see after adding the values in fields error goes away but we are on same screen behind the scenes in login handler we have transitioned from <strong>NoAuthenticated</strong> to <strong>Authenticated</strong> State but we are not using <strong>SessionManagerWidget</strong> which is specifically developed for Session Management. check out <a href="https://medium.com/gitconnected/server-driven-ui-implementation-from-scratch-in-flutter-part-4-6159effa9a31"><strong>Part-4</strong></a><strong> </strong>article to know more about <strong>SessionManager</strong>.</p><pre>SessionManagerWidget(<br>  onUndetermined: () {<br>    return ServeDynamicUI.fromAssets(<br>      &#39;assets/json/auth_loader.json&#39;,<br>    );<br>  },<br>  onAuthenticated: () {<br>    return ServeDynamicUI.fromNetwork(<br>      DynamicRequest(<br>        url:<br>        &#39;http://$localhost:8080/pokedynHomepage/getPage?isPageCacheEnabled=true&#39;,<br>        requestType: RequestType.get,<br>        sendTimeout: const Duration(seconds: 15),<br>        receiveTimeout: const Duration(seconds: 15),<br>      ),<br>      templateJsonPath: &#39;assets/json/shimmers/pokedyn_home_page_shimmer.json&#39;,<br>    );<br>  },<br>  deAuthenticated: () {<br>    return ServeDynamicUI.fromNetwork(<br>      DynamicRequest(<br>        url:<br>        &#39;http://$localhost:8080/authPage/getPage?isPageCacheEnabled=true&#39;,<br>        requestType: RequestType.get,<br>        sendTimeout: const Duration(seconds: 5),<br>        receiveTimeout: const Duration(seconds: 5),<br>      ),<br>      templateJsonPath: &#39;assets/json/logout_loader.json&#39;,<br>    );<br>  },<br>  onAuthenticationInProgress: () {<br>    return ServeDynamicUI.fromAssets(<br>      &#39;assets/json/loader.json&#39;,<br>    );<br>  },<br>  deAuthenticationInProgress: () {<br>    return ServeDynamicUI.fromAssets(<br>      &#39;assets/json/loader.json&#39;,<br>    );<br>  },<br>  onAuthenticationExpired: () {<br>    return const SizedBox();<br>  },<br>  notAuthenticated: () {<br>    return ServeDynamicUI.fromNetwork(<br>      DynamicRequest(<br>        url:<br>        &#39;http://$localhost:8080/authPage/getPage?isPageCacheEnabled=true&#39;,<br>        requestType: RequestType.get,<br>        sendTimeout: const Duration(seconds: 5),<br>        receiveTimeout: const Duration(seconds: 5),<br>      ),<br>      templateJsonPath: &#39;assets/json/auth_loader.json&#39;,<br>    );<br>  },<br>)</pre><p>above is the <strong>SessionManager</strong> Widget based on session state we will get widgets. As you can see above for different states we have different widget builders. Don’t worry if you are seeing network urls we will be adding them later.</p><p>So, Now we will design our home page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*WXQdSbw71d_YR-VRH8uI0Q.gif" /><figcaption>home page pagainted</figcaption></figure><p>This <strong>HomePage</strong> is paginated as we will have lot of pokemons. we cannot fetch all the pokemons data at once and render them all at once. So we will use pagination. Refer <a href="https://medium.com/gitconnected/server-driven-ui-implementation-from-scratch-in-flutter-part-4-6159effa9a31"><strong>Part-4</strong></a> for <strong>Pagination</strong> Implementation.</p><pre>{<br>  &quot;type&quot;: &quot;dy_scaffold&quot;,<br>  &quot;data&quot;: {<br>    &quot;key&quot;: &quot;1236456&quot;,<br>    &quot;appBar&quot;: {<br>      &quot;pageTitle&quot;: &quot;Pokedyn Home Page&quot;,<br>      &quot;appBarGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xff42A5F5,0xffAB47BC&quot;,<br>      &quot;rightActions&quot;: [<br>        {<br>          &quot;type&quot;: &quot;dy_gesture_detector&quot;,<br>          &quot;data&quot;: {<br>            &quot;key&quot;: &quot;23424234&quot;,<br>            &quot;onTapAction&quot;: {<br>              &quot;actionString&quot;: &quot;/logOut&quot;<br>            },<br>            &quot;child&quot;: {<br>              &quot;type&quot;: &quot;dy_image&quot;,<br>              &quot;data&quot;: {<br>                &quot;key&quot;: &quot;24234234234&quot;,<br>                &quot;src&quot;: &quot;assets/images/ic_logout.png&quot;,<br>                &quot;height&quot;: 30,<br>                &quot;width&quot;: 30,<br>                &quot;imageType&quot;: &quot;asset&quot;,<br>                &quot;fit&quot;: &quot;fill&quot;<br>              }<br>            }<br>          }<br>        }<br>      ]<br>    },<br>    &quot;scrollable&quot;: true,<br>    &quot;paginated&quot;: true,<br>    &quot;mainAxisAlignment&quot;: &quot;start&quot;,<br>    &quot;padding&quot;: &quot;20&quot;,<br>    &quot;itemsSpacing&quot;: 10,<br>    &quot;nextUrl&quot;: &quot;assets/json/pokedyn_homepage?offset=5&amp;limit=10.json&quot;,<br>    &quot;children&quot;: [<br>      {<br>        &quot;type&quot;: &quot;dy_gesture_detector&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;345435345&quot;,<br>          &quot;onTapAction&quot;: {<br>            &quot;actionString&quot;: &quot;/moveToScreen&quot;,<br>            &quot;extras&quot;: {<br>              &quot;url&quot;: &quot;assets/json/pokemon_detail_page?pokemon=1.json&quot;,<br>              &quot;urlType&quot;: &quot;local&quot;,<br>              &quot;navigationType&quot;: &quot;screen&quot;,<br>              &quot;navigationStyle&quot;: &quot;push&quot;,<br>              &quot;loaderWidgetAssetPath&quot;: &quot;assets/json/shimmers/pokedyn_detail_page_shimmer.json&quot;<br>            }<br>          },<br>          &quot;child&quot;: {<br>            &quot;type&quot;: &quot;dy_container&quot;,<br>            &quot;data&quot;: {<br>              &quot;key&quot;: &quot;nTxG4llzAfgFnue&quot;,<br>              &quot;containerGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xff42A5F5,0xffAB47BC&quot;,<br>              &quot;height&quot;: 350,<br>              &quot;showBorder&quot;: true,<br>              &quot;borderColor&quot;: &quot;0xffffffff&quot;,<br>              &quot;borderRadius&quot;: 15,<br>              &quot;child&quot;: {<br>                &quot;type&quot;: &quot;dy_column&quot;,<br>                &quot;data&quot;: {<br>                  &quot;key&quot;: &quot;zd6C8y3RLOiXTRr&quot;,<br>                  &quot;children&quot;: [<br>                    {<br>                      &quot;type&quot;: &quot;dy_container&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;zYuTfvGJWBcXuW5&quot;,<br>                        &quot;child&quot;: {<br>                          &quot;type&quot;: &quot;dy_image&quot;,<br>                          &quot;data&quot;: {<br>                            &quot;key&quot;: &quot;zeNXHx8CCuj3dlu&quot;,<br>                            &quot;src&quot;: &quot;https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/1.png&quot;,<br>                            &quot;width&quot;: 250,<br>                            &quot;height&quot;: 200,<br>                            &quot;imageType&quot;: &quot;network&quot;,<br>                            &quot;fit&quot;: &quot;fill&quot;,<br>                            &quot;placeholderImagePath&quot;: &quot;assets/images/ic_pokemon_placeholder.png&quot;<br>                          }<br>                        }<br>                      }<br>                    },<br>                    {<br>                      &quot;type&quot;: &quot;dy_text&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;a3jiu8s4mdk1IzK&quot;,<br>                        &quot;text&quot;: &quot;bulbasaur&quot;,<br>                        &quot;style&quot;: {<br>                          &quot;color&quot;: &quot;0xffffffff&quot;,<br>                          &quot;fontWeight&quot;: &quot;bold&quot;,<br>                          &quot;fontSize&quot;: 20<br>                        }<br>                      }<br>                    },<br>                    {<br>                      &quot;type&quot;: &quot;dy_sized_box&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;rJgW6Zk6YbbAADk&quot;,<br>                        &quot;height&quot;: 30<br>                      }<br>                    },<br>                    {<br>                      &quot;type&quot;: &quot;dy_container&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;Ae37DJYj3s0NT1C&quot;,<br>                        &quot;backgroundColor&quot;: &quot;0xff7AC74C&quot;,<br>                        &quot;borderRadius&quot;: 20,<br>                        &quot;width&quot;: 250,<br>                        &quot;padding&quot;: &quot;10&quot;,<br>                        &quot;showBorder&quot;: true,<br>                        &quot;child&quot;: {<br>                          &quot;type&quot;: &quot;dy_text&quot;,<br>                          &quot;data&quot;: {<br>                            &quot;key&quot;: &quot;nAWlBajbvCQoaXQ&quot;,<br>                            &quot;text&quot;: &quot;Type: grass&quot;,<br>                            &quot;style&quot;: {<br>                              &quot;color&quot;: &quot;0xffffffff&quot;,<br>                              &quot;fontWeight&quot;: &quot;bold&quot;,<br>                              &quot;fontSize&quot;: 20<br>                            }<br>                          }<br>                        }<br>                      }<br>                    }<br>                  ]<br>                }<br>              }<br>            }<br>          }<br>        }<br>      },<br>      {<br>        &quot;type&quot;: &quot;dy_gesture_detector&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;456657657&quot;,<br>          &quot;onTapAction&quot;: {<br>            &quot;actionString&quot;: &quot;/moveToScreen&quot;,<br>            &quot;extras&quot;: {<br>              &quot;url&quot;: &quot;assets/json/pokemon_detail_page?pokemon=2.json&quot;,<br>              &quot;urlType&quot;: &quot;local&quot;,<br>              &quot;navigationType&quot;: &quot;screen&quot;,<br>              &quot;navigationStyle&quot;: &quot;push&quot;<br>            }<br>          },<br>          &quot;child&quot;: {<br>            &quot;type&quot;: &quot;dy_container&quot;,<br>            &quot;data&quot;: {<br>              &quot;key&quot;: &quot;jofXwHp6Eo7Dm8Y&quot;,<br>              &quot;containerGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xff42A5F5,0xffAB47BC&quot;,<br>              &quot;height&quot;: 350,<br>              &quot;showBorder&quot;: true,<br>              &quot;borderColor&quot;: &quot;0xffffffff&quot;,<br>              &quot;borderRadius&quot;: 15,<br>              &quot;child&quot;: {<br>                &quot;type&quot;: &quot;dy_column&quot;,<br>                &quot;data&quot;: {<br>                  &quot;key&quot;: &quot;vft9aYbZQZbp56Y&quot;,<br>                  &quot;children&quot;: [<br>                    {<br>                      &quot;type&quot;: &quot;dy_container&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;wrVTyPeSca0teFW&quot;,<br>                        &quot;child&quot;: {<br>                          &quot;type&quot;: &quot;dy_image&quot;,<br>                          &quot;data&quot;: {<br>                            &quot;key&quot;: &quot;CRkuwKwMrAjtwZZ&quot;,<br>                            &quot;src&quot;: &quot;https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/2.png&quot;,<br>                            &quot;width&quot;: 250,<br>                            &quot;height&quot;: 200,<br>                            &quot;imageType&quot;: &quot;network&quot;,<br>                            &quot;fit&quot;: &quot;fill&quot;,<br>                            &quot;placeholderImagePath&quot;: &quot;assets/images/ic_pokemon_placeholder.png&quot;<br>                          }<br>                        }<br>                      }<br>                    },<br>                    {<br>                      &quot;type&quot;: &quot;dy_text&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;B0yT0FmyBqlu4BF&quot;,<br>                        &quot;text&quot;: &quot;ivysaur&quot;,<br>                        &quot;style&quot;: {<br>                          &quot;color&quot;: &quot;0xffffffff&quot;,<br>                          &quot;fontWeight&quot;: &quot;bold&quot;,<br>                          &quot;fontSize&quot;: 20<br>                        }<br>                      }<br>                    },<br>                    {<br>                      &quot;type&quot;: &quot;dy_sized_box&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;H6NbRjb8EWpdeY1&quot;,<br>                        &quot;height&quot;: 30<br>                      }<br>                    },<br>                    {<br>                      &quot;type&quot;: &quot;dy_container&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;vlasgZgXgN3f0ZP&quot;,<br>                        &quot;backgroundColor&quot;: &quot;0xff7AC74C&quot;,<br>                        &quot;borderRadius&quot;: 20,<br>                        &quot;width&quot;: 250,<br>                        &quot;padding&quot;: &quot;10&quot;,<br>                        &quot;showBorder&quot;: true,<br>                        &quot;child&quot;: {<br>                          &quot;type&quot;: &quot;dy_text&quot;,<br>                          &quot;data&quot;: {<br>                            &quot;key&quot;: &quot;ll75AYgtN9NLdlh&quot;,<br>                            &quot;text&quot;: &quot;Type: grass&quot;,<br>                            &quot;style&quot;: {<br>                              &quot;color&quot;: &quot;0xffffffff&quot;,<br>                              &quot;fontWeight&quot;: &quot;bold&quot;,<br>                              &quot;fontSize&quot;: 20<br>                            }<br>                          }<br>                        }<br>                      }<br>                    }<br>                  ]<br>                }<br>              }<br>            }<br>          }<br>        }<br>      },<br>      {<br>        &quot;type&quot;: &quot;dy_gesture_detector&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;242424234&quot;,<br>          &quot;onTapAction&quot;: {<br>            &quot;actionString&quot;: &quot;/moveToScreen&quot;,<br>            &quot;extras&quot;: {<br>              &quot;url&quot;: &quot;assets/json/pokemon_detail_page?pokemon=3.json&quot;,<br>              &quot;urlType&quot;: &quot;local&quot;,<br>              &quot;navigationType&quot;: &quot;screen&quot;,<br>              &quot;navigationStyle&quot;: &quot;push&quot;<br>            }<br>          },<br>          &quot;child&quot;: {<br>            &quot;type&quot;: &quot;dy_container&quot;,<br>            &quot;data&quot;: {<br>              &quot;key&quot;: &quot;MnspjcOMAiroUGQ&quot;,<br>              &quot;containerGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xff42A5F5,0xffAB47BC&quot;,<br>              &quot;height&quot;: 350,<br>              &quot;showBorder&quot;: true,<br>              &quot;borderColor&quot;: &quot;0xffffffff&quot;,<br>              &quot;borderRadius&quot;: 15,<br>              &quot;child&quot;: {<br>                &quot;type&quot;: &quot;dy_column&quot;,<br>                &quot;data&quot;: {<br>                  &quot;key&quot;: &quot;LNHDHfHtnCtvrfr&quot;,<br>                  &quot;children&quot;: [<br>                    {<br>                      &quot;type&quot;: &quot;dy_container&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;aqN0pzdSPf8Q9VV&quot;,<br>                        &quot;child&quot;: {<br>                          &quot;type&quot;: &quot;dy_image&quot;,<br>                          &quot;data&quot;: {<br>                            &quot;key&quot;: &quot;39IrRDiIO5loMJO&quot;,<br>                            &quot;src&quot;: &quot;https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/3.png&quot;,<br>                            &quot;width&quot;: 250,<br>                            &quot;height&quot;: 200,<br>                            &quot;imageType&quot;: &quot;network&quot;,<br>                            &quot;fit&quot;: &quot;fill&quot;,<br>                            &quot;placeholderImagePath&quot;: &quot;assets/images/ic_pokemon_placeholder.png&quot;<br>                          }<br>                        }<br>                      }<br>                    },<br>                    {<br>                      &quot;type&quot;: &quot;dy_text&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;qqHjJVx3JDhzT7R&quot;,<br>                        &quot;text&quot;: &quot;venusaur&quot;,<br>                        &quot;style&quot;: {<br>                          &quot;color&quot;: &quot;0xffffffff&quot;,<br>                          &quot;fontWeight&quot;: &quot;bold&quot;,<br>                          &quot;fontSize&quot;: 20<br>                        }<br>                      }<br>                    },<br>                    {<br>                      &quot;type&quot;: &quot;dy_sized_box&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;2SR2lQU3CmESQWb&quot;,<br>                        &quot;height&quot;: 30<br>                      }<br>                    },<br>                    {<br>                      &quot;type&quot;: &quot;dy_container&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;WgL2aiyCEh5YfWX&quot;,<br>                        &quot;backgroundColor&quot;: &quot;0xff7AC74C&quot;,<br>                        &quot;borderRadius&quot;: 20,<br>                        &quot;width&quot;: 250,<br>                        &quot;padding&quot;: &quot;10&quot;,<br>                        &quot;showBorder&quot;: true,<br>                        &quot;child&quot;: {<br>                          &quot;type&quot;: &quot;dy_text&quot;,<br>                          &quot;data&quot;: {<br>                            &quot;key&quot;: &quot;RdaSht5Bm0Shryp&quot;,<br>                            &quot;text&quot;: &quot;Type: grass&quot;,<br>                            &quot;style&quot;: {<br>                              &quot;color&quot;: &quot;0xffffffff&quot;,<br>                              &quot;fontWeight&quot;: &quot;bold&quot;,<br>                              &quot;fontSize&quot;: 20<br>                            }<br>                          }<br>                        }<br>                      }<br>                    }<br>                  ]<br>                }<br>              }<br>            }<br>          }<br>        }<br>      },<br>      {<br>        &quot;type&quot;: &quot;dy_gesture_detector&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;2543654654&quot;,<br>          &quot;onTapAction&quot;: {<br>            &quot;actionString&quot;: &quot;/moveToScreen&quot;,<br>            &quot;extras&quot;: {<br>              &quot;url&quot;: &quot;assets/json/pokemon_detail_page?pokemon=4.json&quot;,<br>              &quot;urlType&quot;: &quot;local&quot;,<br>              &quot;navigationType&quot;: &quot;screen&quot;,<br>              &quot;navigationStyle&quot;: &quot;push&quot;<br>            }<br>          },<br>          &quot;child&quot;: {<br>            &quot;type&quot;: &quot;dy_container&quot;,<br>            &quot;data&quot;: {<br>              &quot;key&quot;: &quot;T8BhuiMFF7pXQV9&quot;,<br>              &quot;containerGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xff42A5F5,0xffAB47BC&quot;,<br>              &quot;height&quot;: 350,<br>              &quot;showBorder&quot;: true,<br>              &quot;borderColor&quot;: &quot;0xffffffff&quot;,<br>              &quot;borderRadius&quot;: 15,<br>              &quot;child&quot;: {<br>                &quot;type&quot;: &quot;dy_column&quot;,<br>                &quot;data&quot;: {<br>                  &quot;key&quot;: &quot;912o1MINcdR0rxj&quot;,<br>                  &quot;children&quot;: [<br>                    {<br>                      &quot;type&quot;: &quot;dy_container&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;VtAW6iDsZEXXYjB&quot;,<br>                        &quot;child&quot;: {<br>                          &quot;type&quot;: &quot;dy_image&quot;,<br>                          &quot;data&quot;: {<br>                            &quot;key&quot;: &quot;VZ1qUpYQ3fkGi2u&quot;,<br>                            &quot;src&quot;: &quot;https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/4.png&quot;,<br>                            &quot;width&quot;: 250,<br>                            &quot;height&quot;: 200,<br>                            &quot;imageType&quot;: &quot;network&quot;,<br>                            &quot;fit&quot;: &quot;fill&quot;,<br>                            &quot;placeholderImagePath&quot;: &quot;assets/images/ic_pokemon_placeholder.png&quot;<br>                          }<br>                        }<br>                      }<br>                    },<br>                    {<br>                      &quot;type&quot;: &quot;dy_text&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;5sT0JtGQR7om5en&quot;,<br>                        &quot;text&quot;: &quot;charmander&quot;,<br>                        &quot;style&quot;: {<br>                          &quot;color&quot;: &quot;0xffffffff&quot;,<br>                          &quot;fontWeight&quot;: &quot;bold&quot;,<br>                          &quot;fontSize&quot;: 20<br>                        }<br>                      }<br>                    },<br>                    {<br>                      &quot;type&quot;: &quot;dy_sized_box&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;Slo9CC2rG8CQ0Bt&quot;,<br>                        &quot;height&quot;: 30<br>                      }<br>                    },<br>                    {<br>                      &quot;type&quot;: &quot;dy_container&quot;,<br>                      &quot;data&quot;: {<br>                        &quot;key&quot;: &quot;qKxPyPEdFVnndBI&quot;,<br>                        &quot;backgroundColor&quot;: &quot;0xffEE8130&quot;,<br>                        &quot;borderRadius&quot;: 20,<br>                        &quot;width&quot;: 250,<br>                        &quot;padding&quot;: &quot;10&quot;,<br>                        &quot;showBorder&quot;: true,<br>                        &quot;child&quot;: {<br>                          &quot;type&quot;: &quot;dy_text&quot;,<br>                          &quot;data&quot;: {<br>                            &quot;key&quot;: &quot;PcPjZoUMIp2w3bQ&quot;,<br>                            &quot;text&quot;: &quot;Type: fire&quot;,<br>                            &quot;style&quot;: {<br>                              &quot;color&quot;: &quot;0xffffffff&quot;,<br>                              &quot;fontWeight&quot;: &quot;bold&quot;,<br>                              &quot;fontSize&quot;: 20<br>                            }<br>                          }<br>                        }<br>                      }<br>                    }<br>                  ]<br>                }<br>              }<br>            }<br>          }<br>        }<br>      }<br>    ],<br>    &quot;paginatedLoaderWidget&quot;: {<br>      &quot;type&quot;: &quot;dy_loader&quot;,<br>      &quot;data&quot;: {<br>        &quot;key&quot;: &quot;131454531&quot;,<br>        &quot;mainAxisAlignment&quot;: &quot;center&quot;,<br>        &quot;crossAxisAlignment&quot;: &quot;center&quot;,<br>        &quot;loadingText&quot;: &quot;Grabbing More Pokemons...&quot;,<br>        &quot;style&quot;: {<br>          &quot;color&quot;: &quot;0xFF000000&quot;,<br>          &quot;fontSize&quot;: 20<br>        }<br>      }<br>    }<br>  }<br>}</pre><p><strong>/logOut</strong> is the action handler to log out the user.</p><pre>class LogoutActionHandler extends ActionHandler {<br>  @override<br>  void handleAction(BuildContext? context, Uri action,<br>      Map&lt;String, dynamic&gt;? extras, OnHandledAction? onHandledAction) {<br>    if (context?.mounted ?? false) {<br>      SessionManagerState.instance.sessionStreamController.sink.add(SessionDeAuthenticatedEvent());<br>    }<br>  }<br>}</pre><p>This will simply add <strong>SessionDeAuthenticatedEvent()</strong> to stream and log out.</p><p>Then we will register this action handler as well.</p><pre>ServeDynamicUI.init(actionHandlers: {<br>  RegExp(r&#39;(^/?logOut/?$)&#39;): LogoutActionHandler(),<br>});</pre><p>If you see we have created one card for pokemon which we are repeating for all pokemons just data is changing which we will inflate the data in server.</p><pre>{<br>  &quot;type&quot;: &quot;dy_gesture_detector&quot;,<br>  &quot;data&quot;: {<br>    &quot;key&quot;: &quot;345435345&quot;,<br>    &quot;onTapAction&quot;: {<br>      &quot;actionString&quot;: &quot;/moveToScreen&quot;,<br>      &quot;extras&quot;: {<br>        &quot;url&quot;: &quot;assets/json/pokemon_detail_page?pokemon=1.json&quot;,<br>        &quot;urlType&quot;: &quot;local&quot;,<br>        &quot;navigationType&quot;: &quot;screen&quot;,<br>        &quot;navigationStyle&quot;: &quot;push&quot;,<br>        &quot;loaderWidgetAssetPath&quot;: &quot;assets/json/shimmers/pokedyn_detail_page_shimmer.json&quot;<br>      }<br>    },<br>    &quot;child&quot;: {<br>      &quot;type&quot;: &quot;dy_container&quot;,<br>      &quot;data&quot;: {<br>        &quot;key&quot;: &quot;nTxG4llzAfgFnue&quot;,<br>        &quot;containerGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xff42A5F5,0xffAB47BC&quot;,<br>        &quot;height&quot;: 350,<br>        &quot;showBorder&quot;: true,<br>        &quot;borderColor&quot;: &quot;0xffffffff&quot;,<br>        &quot;borderRadius&quot;: 15,<br>        &quot;child&quot;: {<br>          &quot;type&quot;: &quot;dy_column&quot;,<br>          &quot;data&quot;: {<br>            &quot;key&quot;: &quot;zd6C8y3RLOiXTRr&quot;,<br>            &quot;children&quot;: [<br>              {<br>                &quot;type&quot;: &quot;dy_container&quot;,<br>                &quot;data&quot;: {<br>                  &quot;key&quot;: &quot;zYuTfvGJWBcXuW5&quot;,<br>                  &quot;child&quot;: {<br>                    &quot;type&quot;: &quot;dy_image&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;zeNXHx8CCuj3dlu&quot;,<br>                      &quot;src&quot;: &quot;https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/1.png&quot;,<br>                      &quot;width&quot;: 250,<br>                      &quot;height&quot;: 200,<br>                      &quot;imageType&quot;: &quot;network&quot;,<br>                      &quot;fit&quot;: &quot;fill&quot;,<br>                      &quot;placeholderImagePath&quot;: &quot;assets/images/ic_pokemon_placeholder.png&quot;<br>                    }<br>                  }<br>                }<br>              },<br>              {<br>                &quot;type&quot;: &quot;dy_text&quot;,<br>                &quot;data&quot;: {<br>                  &quot;key&quot;: &quot;a3jiu8s4mdk1IzK&quot;,<br>                  &quot;text&quot;: &quot;bulbasaur&quot;,<br>                  &quot;style&quot;: {<br>                    &quot;color&quot;: &quot;0xffffffff&quot;,<br>                    &quot;fontWeight&quot;: &quot;bold&quot;,<br>                    &quot;fontSize&quot;: 20<br>                  }<br>                }<br>              },<br>              {<br>                &quot;type&quot;: &quot;dy_sized_box&quot;,<br>                &quot;data&quot;: {<br>                  &quot;key&quot;: &quot;rJgW6Zk6YbbAADk&quot;,<br>                  &quot;height&quot;: 30<br>                }<br>              },<br>              {<br>                &quot;type&quot;: &quot;dy_container&quot;,<br>                &quot;data&quot;: {<br>                  &quot;key&quot;: &quot;Ae37DJYj3s0NT1C&quot;,<br>                  &quot;backgroundColor&quot;: &quot;0xff7AC74C&quot;,<br>                  &quot;borderRadius&quot;: 20,<br>                  &quot;width&quot;: 250,<br>                  &quot;padding&quot;: &quot;10&quot;,<br>                  &quot;showBorder&quot;: true,<br>                  &quot;child&quot;: {<br>                    &quot;type&quot;: &quot;dy_text&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;nAWlBajbvCQoaXQ&quot;,<br>                      &quot;text&quot;: &quot;Type: grass&quot;,<br>                      &quot;style&quot;: {<br>                        &quot;color&quot;: &quot;0xffffffff&quot;,<br>                        &quot;fontWeight&quot;: &quot;bold&quot;,<br>                        &quot;fontSize&quot;: 20<br>                      }<br>                    }<br>                  }<br>                }<br>              }<br>            ]<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>I am using in-built dynamic widgets no custom widgets created. So we have to add <strong>nextUrl</strong> which will get us more data when user reaches end of list.</p><pre>&quot;nextUrl&quot;: &quot;assets/json/pokedyn_homepage?offset=5&amp;limit=10.json&quot;</pre><p>So, We have to create Json which will get new pokemon cards.</p><pre>{<br>  &quot;children&quot;: [<br>    {<br>      &quot;type&quot;: &quot;dy_gesture_detector&quot;,<br>      &quot;data&quot;: {<br>        &quot;key&quot;: &quot;234423245345&quot;,<br>        &quot;onTapAction&quot;: {<br>          &quot;actionString&quot;: &quot;/moveToScreen&quot;,<br>          &quot;extras&quot;: {<br>            &quot;url&quot;: &quot;assets/json/pokemon_detail_page?pokemon=5.json&quot;,<br>            &quot;urlType&quot;: &quot;local&quot;,<br>            &quot;navigationType&quot;: &quot;screen&quot;,<br>            &quot;navigationStyle&quot;: &quot;push&quot;<br>          }<br>        },<br>        &quot;child&quot;: {<br>          &quot;type&quot;: &quot;dy_container&quot;,<br>          &quot;data&quot;: {<br>            &quot;key&quot;: &quot;xkGialzhbHsItEO&quot;,<br>            &quot;containerGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xff42A5F5,0xffAB47BC&quot;,<br>            &quot;height&quot;: 350,<br>            &quot;showBorder&quot;: true,<br>            &quot;borderColor&quot;: &quot;0xffffffff&quot;,<br>            &quot;borderRadius&quot;: 15,<br>            &quot;child&quot;: {<br>              &quot;type&quot;: &quot;dy_column&quot;,<br>              &quot;data&quot;: {<br>                &quot;key&quot;: &quot;6wp3vERNCMqLFCn&quot;,<br>                &quot;children&quot;: [<br>                  {<br>                    &quot;type&quot;: &quot;dy_container&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;QqelLrd3Uu44ZqD&quot;,<br>                      &quot;child&quot;: {<br>                        &quot;type&quot;: &quot;dy_image&quot;,<br>                        &quot;data&quot;: {<br>                          &quot;key&quot;: &quot;ePmap5kTLhqVb6G&quot;,<br>                          &quot;src&quot;: &quot;https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/5.png&quot;,<br>                          &quot;width&quot;: 250,<br>                          &quot;height&quot;: 200,<br>                          &quot;imageType&quot;: &quot;network&quot;,<br>                          &quot;fit&quot;: &quot;fill&quot;,<br>                          &quot;placeholderImagePath&quot;: &quot;assets/images/ic_pokemon_placeholder.png&quot;<br>                        }<br>                      }<br>                    }<br>                  },<br>                  {<br>                    &quot;type&quot;: &quot;dy_text&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;LSIYIdWADUcLzQB&quot;,<br>                      &quot;text&quot;: &quot;charmeleon&quot;,<br>                      &quot;style&quot;: {<br>                        &quot;color&quot;: &quot;0xffffffff&quot;,<br>                        &quot;fontWeight&quot;: &quot;bold&quot;,<br>                        &quot;fontSize&quot;: 20<br>                      }<br>                    }<br>                  },<br>                  {<br>                    &quot;type&quot;: &quot;dy_sized_box&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;Z0ZQUjYGtA3ObcS&quot;,<br>                      &quot;height&quot;: 30<br>                    }<br>                  },<br>                  {<br>                    &quot;type&quot;: &quot;dy_container&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;ui79b9F1yKvd7jf&quot;,<br>                      &quot;backgroundColor&quot;: &quot;0xffEE8130&quot;,<br>                      &quot;borderRadius&quot;: 20,<br>                      &quot;width&quot;: 250,<br>                      &quot;padding&quot;: &quot;10&quot;,<br>                      &quot;showBorder&quot;: true,<br>                      &quot;child&quot;: {<br>                        &quot;type&quot;: &quot;dy_text&quot;,<br>                        &quot;data&quot;: {<br>                          &quot;key&quot;: &quot;ygT88KyymwtokxR&quot;,<br>                          &quot;text&quot;: &quot;Type: fire&quot;,<br>                          &quot;style&quot;: {<br>                            &quot;color&quot;: &quot;0xffffffff&quot;,<br>                            &quot;fontWeight&quot;: &quot;bold&quot;,<br>                            &quot;fontSize&quot;: 20<br>                          }<br>                        }<br>                      }<br>                    }<br>                  }<br>                ]<br>              }<br>            }<br>          }<br>        }<br>      }<br>    }<br>  ]<br>}</pre><p>this is structure of json which we fetch from <strong>nextUrl</strong> request call.</p><p>Now, we will put this created json and use this.</p><pre>ServeDynamicUI.fromAssets(<br>  &#39;assets/json/pokedyn_homepage.json&#39;,<br>)</pre><p>So, this is how you can add paginated homepage.</p><p>Now, last page is <strong>Pokemon Info Page</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*GWHG6y7OeD-esiHZzAPwXw.gif" /><figcaption>Pokemon Info</figcaption></figure><p>On <strong>Clicking</strong> on any Pokemon Card It opens up Pokemon Info.</p><p>Lets design this page.</p><pre>{<br>  &quot;type&quot;: &quot;dy_scaffold&quot;,<br>  &quot;data&quot;: {<br>    &quot;key&quot;: &quot;1236456&quot;,<br>    &quot;appBar&quot;: {<br>      &quot;pageTitle&quot;: &quot;Pokemon Info&quot;,<br>      &quot;appBarGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xff80b860,0xff619067&quot;,<br>      &quot;rightActions&quot;: [<br>        {<br>          &quot;type&quot;: &quot;dy_text&quot;,<br>          &quot;data&quot;: {<br>            &quot;key&quot;: &quot;243535345&quot;,<br>            &quot;text&quot;: &quot;#001&quot;,<br>            &quot;margin&quot;: &quot;10,0&quot;,<br>            &quot;style&quot;: {<br>              &quot;color&quot;: &quot;0xffffffff&quot;,<br>              &quot;fontWeight&quot;: &quot;bold&quot;,<br>              &quot;fontSize&quot;: 15<br>            }<br>          }<br>        }<br>      ]<br>    },<br>    &quot;scrollable&quot;: true,<br>    &quot;mainAxisAlignment&quot;: &quot;start&quot;,<br>    &quot;padding&quot;: &quot;20&quot;,<br>    &quot;itemsSpacing&quot;: 10,<br>    &quot;backgroundColor&quot;: &quot;0xff2b292c&quot;,<br>    &quot;height&quot;: -1,<br>    &quot;children&quot;: [<br>      {<br>        &quot;type&quot;: &quot;dy_carousel&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;213234324324&quot;,<br>          &quot;reusable&quot;: true,<br>          &quot;carouselOptions&quot;: {<br>            &quot;autoPlay&quot;: true,<br>            &quot;enlargeCenterPage&quot;: true,<br>            &quot;scrollDirection&quot;: &quot;horizontal&quot;,<br>            &quot;reverse&quot;: false,<br>            &quot;enableInfiniteScroll&quot;: false,<br>            &quot;viewportFraction&quot;: 1,<br>            &quot;height&quot;: 300<br>          },<br>          &quot;children&quot;: [<br>            {<br>              &quot;type&quot;: &quot;dy_card&quot;,<br>              &quot;data&quot;: {<br>                &quot;key&quot;: &quot;123454545234343&quot;,<br>                &quot;margin&quot;: &quot;10&quot;,<br>                &quot;padding&quot;: &quot;10&quot;,<br>                &quot;elevation&quot;: 10,<br>                &quot;linearGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xff94cbae,0xff619067&quot;,<br>                &quot;borderRadius&quot;: 20,<br>                &quot;child&quot;: {<br>                  &quot;type&quot;: &quot;dy_image&quot;,<br>                  &quot;data&quot;: {<br>                    &quot;key&quot;: &quot;212226323233&quot;,<br>                    &quot;src&quot;: &quot;https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/1.png&quot;,<br>                    &quot;width&quot;: 450,<br>                    &quot;imageType&quot;: &quot;network&quot;,<br>                    &quot;fit&quot;: &quot;fill&quot;,<br>                    &quot;placeholderImagePath&quot;: &quot;assets/images/ic_pokemon_placeholder.png&quot;<br>                  }<br>                }<br>              }<br>            },<br>            {<br>              &quot;type&quot;: &quot;dy_card&quot;,<br>              &quot;data&quot;: {<br>                &quot;key&quot;: &quot;3453453453&quot;,<br>                &quot;margin&quot;: &quot;10&quot;,<br>                &quot;padding&quot;: &quot;10&quot;,<br>                &quot;elevation&quot;: 10,<br>                &quot;linearGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xff80b860,0xff619067&quot;,<br>                &quot;borderRadius&quot;: 20,<br>                &quot;child&quot;: {<br>                  &quot;type&quot;: &quot;dy_image&quot;,<br>                  &quot;data&quot;: {<br>                    &quot;key&quot;: &quot;3534534535&quot;,<br>                    &quot;src&quot;: &quot;https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/shiny/1.png&quot;,<br>                    &quot;width&quot;: 450,<br>                    &quot;imageType&quot;: &quot;network&quot;,<br>                    &quot;fit&quot;: &quot;fill&quot;,<br>                    &quot;placeholderImagePath&quot;: &quot;assets/images/ic_pokemon_placeholder.png&quot;<br>                  }<br>                }<br>              }<br>            }<br>          ]<br>        }<br>      },<br>      {<br>        &quot;type&quot;: &quot;dy_container&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;345353535&quot;,<br>          &quot;margin&quot;: &quot;0,20&quot;,<br>          &quot;child&quot;: {<br>            &quot;type&quot;: &quot;dy_text&quot;,<br>            &quot;data&quot;: {<br>              &quot;key&quot;: &quot;35353535&quot;,<br>              &quot;text&quot;: &quot;Balbasaur&quot;,<br>              &quot;style&quot;: {<br>                &quot;color&quot;: &quot;0xffffffff&quot;,<br>                &quot;fontWeight&quot;: &quot;bold&quot;,<br>                &quot;fontSize&quot;: 35<br>              }<br>            }<br>          }<br>        }<br>      },<br>      {<br>        &quot;type&quot;: &quot;dy_row&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;131434&quot;,<br>          &quot;mainAxisAlignment&quot;: &quot;center&quot;,<br>          &quot;children&quot;: [<br>            {<br>              &quot;type&quot;: &quot;dy_column&quot;,<br>              &quot;data&quot;: {<br>                &quot;key&quot;: &quot;131434&quot;,<br>                &quot;children&quot;: [<br>                  {<br>                    &quot;type&quot;: &quot;dy_container&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;35435345345&quot;,<br>                      &quot;backgroundColor&quot;: &quot;0xff8eaec5&quot;,<br>                      &quot;borderRadius&quot;: 20,<br>                      &quot;width&quot;: 150,<br>                      &quot;padding&quot;: &quot;10&quot;,<br>                      &quot;showBorder&quot;: true,<br>                      &quot;child&quot;: {<br>                        &quot;type&quot;: &quot;dy_text&quot;,<br>                        &quot;data&quot;: {<br>                          &quot;key&quot;: &quot;35345345&quot;,<br>                          &quot;text&quot;: &quot;Water&quot;,<br>                          &quot;style&quot;: {<br>                            &quot;color&quot;: &quot;0xffffffff&quot;,<br>                            &quot;fontWeight&quot;: &quot;bold&quot;,<br>                            &quot;fontSize&quot;: 15<br>                          }<br>                        }<br>                      }<br>                    }<br>                  },<br>                  {<br>                    &quot;type&quot;: &quot;dy_sized_box&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;23424234&quot;,<br>                      &quot;height&quot;: 25<br>                    }<br>                  },<br>                  {<br>                    &quot;type&quot;: &quot;dy_text&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;24243453454&quot;,<br>                      &quot;text&quot;: &quot;70.5 KG&quot;,<br>                      &quot;style&quot;: {<br>                        &quot;color&quot;: &quot;0xffffffff&quot;,<br>                        &quot;fontWeight&quot;: &quot;bold&quot;,<br>                        &quot;fontSize&quot;: 18<br>                      }<br>                    }<br>                  },<br>                  {<br>                    &quot;type&quot;: &quot;dy_sized_box&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;34533535&quot;,<br>                      &quot;height&quot;: 10<br>                    }<br>                  },<br>                  {<br>                    &quot;type&quot;: &quot;dy_text&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;345353534&quot;,<br>                      &quot;text&quot;: &quot;Weight&quot;,<br>                      &quot;style&quot;: {<br>                        &quot;color&quot;: &quot;0xff555254&quot;,<br>                        &quot;fontWeight&quot;: &quot;bold&quot;,<br>                        &quot;fontSize&quot;: 15<br>                      }<br>                    }<br>                  }<br>                ]<br>              }<br>            },<br>            {<br>              &quot;type&quot;: &quot;dy_sized_box&quot;,<br>              &quot;data&quot;: {<br>                &quot;key&quot;: &quot;343445&quot;,<br>                &quot;width&quot;: 20<br>              }<br>            },<br>            {<br>              &quot;type&quot;: &quot;dy_column&quot;,<br>              &quot;data&quot;: {<br>                &quot;key&quot;: &quot;131434&quot;,<br>                &quot;children&quot;: [<br>                  {<br>                    &quot;type&quot;: &quot;dy_container&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;9879345734&quot;,<br>                      &quot;backgroundColor&quot;: &quot;0xff719c8f&quot;,<br>                      &quot;borderRadius&quot;: 20,<br>                      &quot;width&quot;: 150,<br>                      &quot;padding&quot;: &quot;10&quot;,<br>                      &quot;showBorder&quot;: true,<br>                      &quot;child&quot;: {<br>                        &quot;type&quot;: &quot;dy_text&quot;,<br>                        &quot;data&quot;: {<br>                          &quot;key&quot;: &quot;427345345&quot;,<br>                          &quot;text&quot;: &quot;Leaves&quot;,<br>                          &quot;style&quot;: {<br>                            &quot;color&quot;: &quot;0xffffffff&quot;,<br>                            &quot;fontWeight&quot;: &quot;bold&quot;,<br>                            &quot;fontSize&quot;: 15<br>                          }<br>                        }<br>                      }<br>                    }<br>                  },<br>                  {<br>                    &quot;type&quot;: &quot;dy_sized_box&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;22424234234&quot;,<br>                      &quot;height&quot;: 25<br>                    }<br>                  },<br>                  {<br>                    &quot;type&quot;: &quot;dy_text&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;234344345345&quot;,<br>                      &quot;text&quot;: &quot;1.5 M&quot;,<br>                      &quot;style&quot;: {<br>                        &quot;color&quot;: &quot;0xffffffff&quot;,<br>                        &quot;fontWeight&quot;: &quot;bold&quot;,<br>                        &quot;fontSize&quot;: 18<br>                      }<br>                    }<br>                  },<br>                  {<br>                    &quot;type&quot;: &quot;dy_sized_box&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;24245345&quot;,<br>                      &quot;height&quot;: 10<br>                    }<br>                  },<br>                  {<br>                    &quot;type&quot;: &quot;dy_text&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;353535345&quot;,<br>                      &quot;text&quot;: &quot;Height&quot;,<br>                      &quot;style&quot;: {<br>                        &quot;color&quot;: &quot;0xff555254&quot;,<br>                        &quot;fontWeight&quot;: &quot;bold&quot;,<br>                        &quot;fontSize&quot;: 15<br>                      }<br>                    }<br>                  }<br>                ]<br>              }<br>            }<br>          ]<br>        }<br>      },<br>      {<br>        &quot;type&quot;: &quot;dy_container&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;234242424234&quot;,<br>          &quot;margin&quot;: &quot;0,20,0,0&quot;,<br>          &quot;child&quot;: {<br>            &quot;type&quot;: &quot;dy_text&quot;,<br>            &quot;data&quot;: {<br>              &quot;key&quot;: &quot;245435345&quot;,<br>              &quot;text&quot;: &quot;Base Stats&quot;,<br>              &quot;style&quot;: {<br>                &quot;color&quot;: &quot;0xff8c8d8d&quot;,<br>                &quot;fontWeight&quot;: &quot;bold&quot;,<br>                &quot;fontSize&quot;: 20<br>              }<br>            }<br>          }<br>        }<br>      },<br>      {<br>        &quot;type&quot;: &quot;dy_column&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;134234234&quot;,<br>          &quot;interItemSpacing&quot;: 20,<br>          &quot;children&quot;: [<br>            {<br>              &quot;type&quot;: &quot;dy_percentage_indicator&quot;,<br>              &quot;data&quot;: {<br>                &quot;key&quot;: &quot;34343434&quot;,<br>                &quot;type&quot;: &quot;linear&quot;,<br>                &quot;linearPercentIndicator&quot;: {<br>                  &quot;percent&quot;: 0.76,<br>                  &quot;lineHeight&quot;: 18,<br>                  &quot;linearGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xFF808000,0xFFFF0000&quot;,<br>                  &quot;animation&quot;: true,<br>                  &quot;animationDuration&quot;: 1000,<br>                  &quot;barRadius&quot;: 10,<br>                  &quot;backgroundColor&quot;: &quot;0xffffffff&quot;,<br>                  &quot;center&quot;: {<br>                    &quot;type&quot;: &quot;dy_text&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;2424234&quot;,<br>                      &quot;text&quot;: &quot;168/300&quot;,<br>                      &quot;style&quot;: {<br>                        &quot;fontSize&quot;: 15,<br>                        &quot;fontWeight&quot;: &quot;bold&quot;,<br>                        &quot;color&quot;: &quot;0xff000000&quot;<br>                      }<br>                    }<br>                  },<br>                  &quot;leading&quot;: {<br>                    &quot;type&quot;: &quot;dy_container&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;2342435435435&quot;,<br>                      &quot;width&quot;: 40,<br>                      &quot;child&quot;: {<br>                        &quot;type&quot;: &quot;dy_text&quot;,<br>                        &quot;data&quot;: {<br>                          &quot;key&quot;: &quot;343434&quot;,<br>                          &quot;text&quot;: &quot;HP&quot;,<br>                          &quot;style&quot;: {<br>                            &quot;fontSize&quot;: 15,<br>                            &quot;fontWeight&quot;: &quot;bold&quot;,<br>                            &quot;color&quot;: &quot;0xffffffff&quot;<br>                          }<br>                        }<br>                      }<br>                    }<br>                  }<br>                }<br>              }<br>            },<br>            {<br>              &quot;type&quot;: &quot;dy_percentage_indicator&quot;,<br>              &quot;data&quot;: {<br>                &quot;key&quot;: &quot;24234234&quot;,<br>                &quot;type&quot;: &quot;linear&quot;,<br>                &quot;linearPercentIndicator&quot;: {<br>                  &quot;percent&quot;: 0.69,<br>                  &quot;lineHeight&quot;: 18,<br>                  &quot;animation&quot;: true,<br>                  &quot;animationDuration&quot;: 1000,<br>                  &quot;barRadius&quot;: 10,<br>                  &quot;backgroundColor&quot;: &quot;0xffffffff&quot;,<br>                  &quot;linearGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xFF006400,0xfffda626&quot;,<br>                  &quot;center&quot;: {<br>                    &quot;type&quot;: &quot;dy_text&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;24234234234&quot;,<br>                      &quot;text&quot;: &quot;205/300&quot;,<br>                      &quot;style&quot;: {<br>                        &quot;fontSize&quot;: 15,<br>                        &quot;fontWeight&quot;: &quot;bold&quot;,<br>                        &quot;color&quot;: &quot;0xff000000&quot;<br>                      }<br>                    }<br>                  },<br>                  &quot;leading&quot;: {<br>                    &quot;type&quot;: &quot;dy_container&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;345345345345&quot;,<br>                      &quot;width&quot;: 40,<br>                      &quot;child&quot;: {<br>                        &quot;type&quot;: &quot;dy_text&quot;,<br>                        &quot;data&quot;: {<br>                          &quot;key&quot;: &quot;234345345345&quot;,<br>                          &quot;text&quot;: &quot;ATK&quot;,<br>                          &quot;style&quot;: {<br>                            &quot;fontSize&quot;: 15,<br>                            &quot;fontWeight&quot;: &quot;bold&quot;,<br>                            &quot;color&quot;: &quot;0xffffffff&quot;<br>                          }<br>                        }<br>                      }<br>                    }<br>                  }<br>                }<br>              }<br>            },<br>            {<br>              &quot;type&quot;: &quot;dy_percentage_indicator&quot;,<br>              &quot;data&quot;: {<br>                &quot;key&quot;: &quot;34343434&quot;,<br>                &quot;type&quot;: &quot;linear&quot;,<br>                &quot;linearPercentIndicator&quot;: {<br>                  &quot;percent&quot;: 0.92,<br>                  &quot;lineHeight&quot;: 18,<br>                  &quot;animation&quot;: true,<br>                  &quot;animationDuration&quot;: 1000,<br>                  &quot;barRadius&quot;: 10,<br>                  &quot;backgroundColor&quot;: &quot;0xffffffff&quot;,<br>                  &quot;linearGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xff0290e9,0xfffff000&quot;,<br>                  &quot;center&quot;: {<br>                    &quot;type&quot;: &quot;dy_text&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;2424234&quot;,<br>                      &quot;text&quot;: &quot;64/300&quot;,<br>                      &quot;style&quot;: {<br>                        &quot;fontSize&quot;: 15,<br>                        &quot;fontWeight&quot;: &quot;bold&quot;,<br>                        &quot;color&quot;: &quot;0xff000000&quot;<br>                      }<br>                    }<br>                  },<br>                  &quot;leading&quot;: {<br>                    &quot;type&quot;: &quot;dy_container&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;02947247944753&quot;,<br>                      &quot;width&quot;: 40,<br>                      &quot;child&quot;: {<br>                        &quot;type&quot;: &quot;dy_text&quot;,<br>                        &quot;data&quot;: {<br>                          &quot;key&quot;: &quot;92482428724&quot;,<br>                          &quot;text&quot;: &quot;DEF&quot;,<br>                          &quot;style&quot;: {<br>                            &quot;fontSize&quot;: 15,<br>                            &quot;fontWeight&quot;: &quot;bold&quot;,<br>                            &quot;color&quot;: &quot;0xffffffff&quot;<br>                          }<br>                        }<br>                      }<br>                    }<br>                  }<br>                }<br>              }<br>            },<br>            {<br>              &quot;type&quot;: &quot;dy_percentage_indicator&quot;,<br>              &quot;data&quot;: {<br>                &quot;key&quot;: &quot;34343434&quot;,<br>                &quot;type&quot;: &quot;linear&quot;,<br>                &quot;linearPercentIndicator&quot;: {<br>                  &quot;percent&quot;: 0.66,<br>                  &quot;lineHeight&quot;: 18,<br>                  &quot;animation&quot;: true,<br>                  &quot;animationDuration&quot;: 1000,<br>                  &quot;barRadius&quot;: 10,<br>                  &quot;backgroundColor&quot;: &quot;0xffffffff&quot;,<br>                  &quot;linearGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xff8eafc4,0xff6e7ac4&quot;,<br>                  &quot;center&quot;: {<br>                    &quot;type&quot;: &quot;dy_text&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;927469264876758345&quot;,<br>                      &quot;text&quot;: &quot;200/300&quot;,<br>                      &quot;style&quot;: {<br>                        &quot;fontSize&quot;: 15,<br>                        &quot;fontWeight&quot;: &quot;bold&quot;,<br>                        &quot;color&quot;: &quot;0xff000000&quot;<br>                      }<br>                    }<br>                  },<br>                  &quot;leading&quot;: {<br>                    &quot;type&quot;: &quot;dy_container&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;9836749727234&quot;,<br>                      &quot;width&quot;: 40,<br>                      &quot;child&quot;: {<br>                        &quot;type&quot;: &quot;dy_text&quot;,<br>                        &quot;data&quot;: {<br>                          &quot;key&quot;: &quot;9724279472394&quot;,<br>                          &quot;text&quot;: &quot;SPD&quot;,<br>                          &quot;style&quot;: {<br>                            &quot;fontSize&quot;: 15,<br>                            &quot;fontWeight&quot;: &quot;bold&quot;,<br>                            &quot;color&quot;: &quot;0xffffffff&quot;<br>                          }<br>                        }<br>                      }<br>                    }<br>                  }<br>                }<br>              }<br>            },<br>            {<br>              &quot;type&quot;: &quot;dy_percentage_indicator&quot;,<br>              &quot;data&quot;: {<br>                &quot;key&quot;: &quot;34343434&quot;,<br>                &quot;type&quot;: &quot;linear&quot;,<br>                &quot;linearPercentIndicator&quot;: {<br>                  &quot;percent&quot;: 0.85,<br>                  &quot;lineHeight&quot;: 18,<br>                  &quot;animation&quot;: true,<br>                  &quot;animationDuration&quot;: 1000,<br>                  &quot;barRadius&quot;: 10,<br>                  &quot;backgroundColor&quot;: &quot;0xffffffff&quot;,<br>                  &quot;linearGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xff378a3a,0xff8a3a37&quot;,<br>                  &quot;center&quot;: {<br>                    &quot;type&quot;: &quot;dy_text&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;2424234&quot;,<br>                      &quot;text&quot;: &quot;295/1000&quot;,<br>                      &quot;style&quot;: {<br>                        &quot;fontSize&quot;: 15,<br>                        &quot;fontWeight&quot;: &quot;bold&quot;,<br>                        &quot;color&quot;: &quot;0xff000000&quot;<br>                      }<br>                    }<br>                  },<br>                  &quot;leading&quot;: {<br>                    &quot;type&quot;: &quot;dy_container&quot;,<br>                    &quot;data&quot;: {<br>                      &quot;key&quot;: &quot;23345345345&quot;,<br>                      &quot;width&quot;: 40,<br>                      &quot;child&quot;: {<br>                        &quot;type&quot;: &quot;dy_text&quot;,<br>                        &quot;data&quot;: {<br>                          &quot;key&quot;: &quot;3534534535&quot;,<br>                          &quot;text&quot;: &quot;EXP&quot;,<br>                          &quot;style&quot;: {<br>                            &quot;fontSize&quot;: 15,<br>                            &quot;fontWeight&quot;: &quot;bold&quot;,<br>                            &quot;color&quot;: &quot;0xffffffff&quot;<br>                          }<br>                        }<br>                      }<br>                    }<br>                  }<br>                }<br>              }<br>            }<br>          ]<br>        }<br>      }<br>    ]<br>  }<br>}</pre><p>Main widgets here are the carousel and percent indicator. <strong>serve_dynamic_ui</strong> uses <a href="https://pub.dev/packages/carousel_slider"><strong>carousel_slider</strong></a> and <a href="https://pub.dev/packages/percent_indicator"><strong>percent_indicator</strong></a> and create <strong>dy_carousel</strong> and <strong>dy_percent_indicator</strong> as wrapper over these widget for dynamic widgets.</p><pre>{<br>  &quot;type&quot;: &quot;dy_carousel&quot;,<br>  &quot;data&quot;: {<br>    &quot;key&quot;: &quot;213234324324&quot;,<br>    &quot;reusable&quot;: true,<br>    &quot;carouselOptions&quot;: {<br>      &quot;autoPlay&quot;: true,<br>      &quot;enlargeCenterPage&quot;: true,<br>      &quot;scrollDirection&quot;: &quot;horizontal&quot;,<br>      &quot;reverse&quot;: false,<br>      &quot;enableInfiniteScroll&quot;: false,<br>      &quot;viewportFraction&quot;: 1,<br>      &quot;height&quot;: 300<br>    },<br>    &quot;children&quot;: [<br>      {<br>        &quot;type&quot;: &quot;dy_card&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;123454545234343&quot;,<br>          &quot;margin&quot;: &quot;10&quot;,<br>          &quot;padding&quot;: &quot;10&quot;,<br>          &quot;elevation&quot;: 10,<br>          &quot;linearGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xff94cbae,0xff619067&quot;,<br>          &quot;borderRadius&quot;: 20,<br>          &quot;child&quot;: {<br>            &quot;type&quot;: &quot;dy_image&quot;,<br>            &quot;data&quot;: {<br>              &quot;key&quot;: &quot;212226323233&quot;,<br>              &quot;src&quot;: &quot;https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/1.png&quot;,<br>              &quot;width&quot;: 450,<br>              &quot;imageType&quot;: &quot;network&quot;,<br>              &quot;fit&quot;: &quot;fill&quot;,<br>              &quot;placeholderImagePath&quot;: &quot;assets/images/ic_pokemon_placeholder.png&quot;<br>            }<br>          }<br>        }<br>      },<br>      {<br>        &quot;type&quot;: &quot;dy_card&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;3453453453&quot;,<br>          &quot;margin&quot;: &quot;10&quot;,<br>          &quot;padding&quot;: &quot;10&quot;,<br>          &quot;elevation&quot;: 10,<br>          &quot;linearGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xff80b860,0xff619067&quot;,<br>          &quot;borderRadius&quot;: 20,<br>          &quot;child&quot;: {<br>            &quot;type&quot;: &quot;dy_image&quot;,<br>            &quot;data&quot;: {<br>              &quot;key&quot;: &quot;3534534535&quot;,<br>              &quot;src&quot;: &quot;https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/shiny/1.png&quot;,<br>              &quot;width&quot;: 450,<br>              &quot;imageType&quot;: &quot;network&quot;,<br>              &quot;fit&quot;: &quot;fill&quot;,<br>              &quot;placeholderImagePath&quot;: &quot;assets/images/ic_pokemon_placeholder.png&quot;<br>            }<br>          }<br>        }<br>      }<br>    ]<br>  }<br>}</pre><p>In the <strong>dy_carousel</strong> I have added <strong>dy_card.</strong></p><pre>&quot;carouselOptions&quot;: {<br>      &quot;autoPlay&quot;: true,<br>      &quot;enlargeCenterPage&quot;: true,<br>      &quot;scrollDirection&quot;: &quot;horizontal&quot;,<br>      &quot;reverse&quot;: false,<br>      &quot;enableInfiniteScroll&quot;: false,<br>      &quot;viewportFraction&quot;: 1,<br>      &quot;height&quot;: 300<br>}</pre><p>these are the options i have set you can set your own.</p><p>Now, we create <strong>dy_percent_indicator</strong></p><pre>{<br>  &quot;type&quot;: &quot;dy_percentage_indicator&quot;,<br>  &quot;data&quot;: {<br>    &quot;key&quot;: &quot;24234234&quot;,<br>    &quot;type&quot;: &quot;linear&quot;,<br>    &quot;linearPercentIndicator&quot;: {<br>      &quot;percent&quot;: 0.69,<br>      &quot;lineHeight&quot;: 18,<br>      &quot;animation&quot;: true,<br>      &quot;animationDuration&quot;: 1000,<br>      &quot;barRadius&quot;: 10,<br>      &quot;backgroundColor&quot;: &quot;0xffffffff&quot;,<br>      &quot;linearGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xFF006400,0xfffda626&quot;,<br>      &quot;center&quot;: {<br>        &quot;type&quot;: &quot;dy_text&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;24234234234&quot;,<br>          &quot;text&quot;: &quot;205/300&quot;,<br>          &quot;style&quot;: {<br>            &quot;fontSize&quot;: 15,<br>            &quot;fontWeight&quot;: &quot;bold&quot;,<br>            &quot;color&quot;: &quot;0xff000000&quot;<br>          }<br>        }<br>      },<br>      &quot;leading&quot;: {<br>        &quot;type&quot;: &quot;dy_container&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;345345345345&quot;,<br>          &quot;width&quot;: 40,<br>          &quot;child&quot;: {<br>            &quot;type&quot;: &quot;dy_text&quot;,<br>            &quot;data&quot;: {<br>              &quot;key&quot;: &quot;234345345345&quot;,<br>              &quot;text&quot;: &quot;ATK&quot;,<br>              &quot;style&quot;: {<br>                &quot;fontSize&quot;: 15,<br>                &quot;fontWeight&quot;: &quot;bold&quot;,<br>                &quot;color&quot;: &quot;0xffffffff&quot;<br>              }<br>            }<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p><strong>This shows one of the stat. we add 4 stats about a pokemon.</strong></p><p>This is how we build json pages.</p><p>Now, last is to add <strong>shimmer pages.</strong></p><pre>{<br>  &quot;type&quot;: &quot;dy_shimmer_stack&quot;,<br>  &quot;data&quot;: {<br>    &quot;key&quot;: &quot;2234656231&quot;,<br>    &quot;alignment&quot;: &quot;center&quot;,<br>    &quot;shimmerBaseColor&quot;: &quot;0xff3b3b3b&quot;,<br>    &quot;height&quot;: 300,<br>    &quot;borderRadius&quot;: 20,<br>    &quot;margin&quot;: &quot;10&quot;,<br>    &quot;children&quot;: [<br>      {<br>        &quot;type&quot;: &quot;dy_positioned&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;131313&quot;,<br>          &quot;child&quot;: {<br>            &quot;type&quot;: &quot;dy_container&quot;,<br>            &quot;data&quot;: {<br>              &quot;key&quot;: &quot;234234234&quot;,<br>              &quot;containerGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xff42A5F5,0xffAB47BC&quot;,<br>              &quot;borderColor&quot;: &quot;0xff000000&quot;,<br>              &quot;borderRadius&quot;: 20,<br>              &quot;margin&quot;: &quot;10&quot;,<br>              &quot;showBorder&quot;: true,<br>              &quot;child&quot;: {<br>                &quot;type&quot;: &quot;dy_image&quot;,<br>                &quot;data&quot;: {<br>                  &quot;key&quot;: &quot;242424234234&quot;,<br>                  &quot;src&quot;: &quot;assets/images/ic_pokemon_placeholder.png&quot;,<br>                  &quot;width&quot;: 350,<br>                  &quot;height&quot;: 300,<br>                  &quot;imageType&quot;: &quot;asset&quot;,<br>                  &quot;fit&quot;: &quot;fill&quot;,<br>                  &quot;placeholderImagePath&quot;: &quot;assets/images/ic_pokemon_placeholder.png&quot;<br>                }<br>              }<br>            }<br>          }<br>        }<br>      }<br>    ]<br>  }<br>}</pre><p>This is the card shimmer stack which we will show while we fetch our page json from network.</p><p>these shimmer pages path we can add using <strong>templateStringJson</strong>.</p><h4><em>You can find full shimmer page jsons </em><a href="https://github.com/ServeDynamicUI/pokedyn-app/tree/main/pokedyn_flutter/assets/json/shimmers"><em>here</em></a><em>.</em></h4><p><strong><em>To know more about Shimmers read </em></strong><a href="https://medium.com/gitconnected/server-driven-ui-implementation-from-scratch-in-flutter-part-4-6159effa9a31"><strong><em>Part-4</em></strong></a></p><p><strong>This article has become very long I will write its continuation in next article where we only talk about developing backend using serverpod for our app.</strong></p><h3><strong>Thank You For Reading Article</strong></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c07ccacf5a11" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/server-driven-ui-in-flutter-from-scratch-part-5-building-complete-app-end-to-end-using-serverpod-c07ccacf5a11">Server-Driven UI in Flutter from Scratch: Part 5 — Building Complete App End-to-End using Serverpod</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server-Driven UI Implementation from Scratch in Flutter: Part 4]]></title>
            <link>https://levelup.gitconnected.com/server-driven-ui-implementation-from-scratch-in-flutter-part-4-6159effa9a31?source=rss-1e41946a95c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6159effa9a31</guid>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[flutter-widget]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[server-driven-ui]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Sk Ahron]]></dc:creator>
            <pubDate>Fri, 26 Jul 2024 16:00:40 GMT</pubDate>
            <atom:updated>2024-07-26T16:00:40.256Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*5wbK6pevdt_iwhj66Zy5vQ.jpeg" /><figcaption>serve dynamic ui image</figcaption></figure><p><strong>After long time, I am continuing writing article about server driven ui, we will continue server-driven ui implementation in Flutter where we will discuss Page Caching, Pagination, Session Management.</strong></p><blockquote><strong>Pre-requisite:</strong> Please read <a href="https://medium.com/gitconnected/server-driven-ui-implementation-from-scratch-in-flutter-part-1-basics-71364ddd323e"><strong>Part-1</strong></a><strong>, </strong><a href="https://medium.com/gitconnected/server-driven-ui-implementation-from-scratch-in-flutter-part-2-6ae7947a7c9b"><strong>Part-2</strong></a><strong> </strong>and <a href="https://medium.com/gitconnected/server-driven-ui-implementation-from-scratch-in-flutter-part-3-e931cb570662"><strong>Part-3</strong></a> of server-driven UI otherwise you will not understand the context of this article.</blockquote><p><strong>I have updated </strong><a href="https://pub.dev/packages/serve_dynamic_ui"><strong>serve_dynamic_ui</strong></a><strong> package which is based on server-driven-ui. Do Checkout.</strong></p><h3>In this article we will implement:</h3><ol><li><strong>Page Caching using Hive</strong></li><li><strong>Pagination in Page Level</strong></li><li><strong>Session Management</strong></li><li><strong>Shimmer Loading</strong></li></ol><h4>Let us start with <strong>Page Caching</strong></h4><ol><li>We have to create an <strong>Entity</strong> which will contain data about a specific request url and details about the page.</li></ol><pre>@HiveType(typeId: 0)<br>class PageEntity {<br>  @HiveField(0)<br>  final String pageKey;<br><br>  @HiveField(1)<br>  final String page;<br><br>  @HiveField(2)<br>  final int updatedAt;<br><br>  PageEntity(this.pageKey, this.page, this.updatedAt);<br>}</pre><p><strong>pageKey</strong> is the encoded version of requested page url using sha256 algo you can use any hashing algo.</p><p><strong>page</strong> is the stringified version of page.</p><p><strong>updatedAt</strong> is time at which page is updated for a request url.</p><p>2. Now, I will create a <strong>Dao</strong> which will have the CRUD operations we need</p><pre>class CachedPageDao {<br>  final Box&lt;PageEntity&gt; box = Hive.box&lt;PageEntity&gt;(&#39;cachedPages&#39;);<br><br>  CachedPageDao._privateConstructor();<br><br>  static final CachedPageDao instance = CachedPageDao._privateConstructor();<br><br>  Future&lt;void&gt; insertCachedPage(PageEntity pageEntity) async {<br>    await box.put(pageEntity.pageKey, pageEntity);<br>  }<br><br>  Future&lt;List&lt;PageEntity&gt;&gt; getAllCachedPage() async {<br>    return box.values.toList();<br>  }<br><br>  Future&lt;PageEntity?&gt; findCachedPageByPageKey(String pageKey) async {<br>    return box.get(pageKey);<br>  }<br><br>  Future&lt;int&gt; deleteCachedPagesOlderThanTime(int time) async {<br>    final keysToDelete = box.values<br>        .where((page) =&gt; page.updatedAt &lt; time)<br>        .map((page) =&gt; page.pageKey)<br>        .toList();<br>    await box.deleteAll(keysToDelete);<br>    return keysToDelete.length;<br>  }<br><br>  Future&lt;int&gt; deleteCachedPageIfOlderThanTime(String pageKey, int time) async {<br>    final page = box.get(pageKey);<br>    if (page != null &amp;&amp; page.updatedAt &lt; time) {<br>      await box.delete(pageKey);<br>      return 1;<br>    }<br>    return 0;<br>  }<br><br>  Future&lt;int&gt; deleteAllCachedPages() async {<br>    final count = box.length;<br>    await box.clear();<br>    return count;<br>  }<br><br>  Future&lt;int&gt; deleteCachePageByKey(String pageKey) async {<br>    await box.delete(pageKey);<br>    return 1;<br>  }<br>}</pre><p>here i have created hive box <strong>cachedPages</strong>.</p><p>3. Now we have to create a singleton database provider which will help us to call CRUD operations.</p><pre>//code snippet taken from serve_dynamic_ui<br>class ServeDynamicUIDatabaseProvider {<br>  ServeDynamicUIDatabaseProvider._privateConstructor();<br><br>  static final ServeDynamicUIDatabaseProvider instance =<br>      ServeDynamicUIDatabaseProvider._privateConstructor();<br><br>  CachedPageDao? _database;<br><br>  Future&lt;CachedPageDao&gt; get database async {<br>    if (_database == null) {<br>      await _initHive();<br>    }<br>    _database ??= CachedPageDao.instance;<br>    return _database!;<br>  }<br><br>  Future&lt;void&gt; _initHive() async {<br>    await Hive.initFlutter(&#39;serve_dynamic_ui&#39;);<br>    Hive.registerAdapter(PageEntityAdapter());<br>    await Hive.openBox&lt;PageEntity&gt;(&#39;cachedPages&#39;);<br>  }<br>}</pre><p>if you can see , <strong>_initHive()</strong> we have to initialize hive and open hive box <strong>cachedPages</strong> to perform CRUD operations.</p><p>4. We also have to set <strong>TTL(Time to Live) </strong>basically we want to evict the page rows who have become stale.</p><pre>--dart-define=PAGE_CACHE_KEEP_TIME_IN_SEC=10</pre><p>this is arg we will use from environment to use as cache time. you can get the value using this</p><pre>const String.fromEnvironment(&#39;PAGE_CACHE_KEEP_TIME_IN_SEC&#39;)</pre><pre>//code snippet from serve_dynamic_ui<br>static Future&lt;bool&gt; deleteCachedPagesOlderThanSetCacheTime() async {<br>  try {<br>    int? cacheTime = await Util.getPageCacheTime();<br>    if (Util.isValid(cacheTime)) {<br>      int lastTime = DateTime.now().subtract(Duration(seconds: cacheTime!)).millisecondsSinceEpoch;<br>      CachedPageDao serveDynamicUIDatabase =<br>          await ServeDynamicUIDatabaseProvider.instance.database;<br>      int? deletedPages = await serveDynamicUIDatabase.deleteCachedPagesOlderThanTime(lastTime);<br>      debugPrint(&#39;Deleted pages count: $deletedPages&#39;);<br>      return Util.isValid(deletedPages) &amp;&amp; deletedPages &gt; 0;<br>    }<br>  } catch (e) {<br>    debugPrint(&#39;Some error occurred: $e&#39;);<br>  }<br>  return false;<br>}</pre><p>Above, you can see i am getting the <strong>cacheTime</strong> and trying to find the time less than which we will remove page rows. Add this <strong>deleteCachedPagesOlderThanSetCacheTime</strong> method in<strong> init()</strong> of widget.</p><p>If you run the app and if you have stored a <strong>PageEntity</strong> you will get in log</p><pre>deleted page bc2e0369602309ee2ca9bf4db9b5f856fd3407baa425d0086821b7604959f28d? : 1</pre><p>as i already have page it deleted it as time set is <strong>10 secs.</strong></p><h4>Now, Let discuss about <strong>Pagination in Page Level(Scaffold).</strong></h4><p><strong>1.</strong>Before implementing we should know about pagination in a list. when there is a big list of data which we want to render on screen if we fetch all data at once it will choke network as well as it creates performance issues in app as well so what we do is as we scroll to bottom we fetch more data we fetch data in chunks.</p><p><strong>2.</strong> So, In <strong>dy_scaffold</strong> widget we have <strong>children,</strong> list of <strong>DynamicWidgets</strong> we will have few child items in it and when we scroll to bottom we fetch more data.<br>So, first we need, <strong>isPaginated</strong> and <strong>nextUrl</strong> properties added in <strong>dy_scaffold</strong>.</p><p>Then we will create a paginated list view.</p><pre>Widget _paginatedListWidget(List&lt;Widget&gt; widgets) {<br>    return ListView.separated(<br>      controller: _scrollController,<br>      shrinkWrap: true,<br>      itemBuilder: (context, index) {<br>        return widgets[index];<br>      },<br>      separatorBuilder: (context, index) {<br>        return Container(<br>          height: itemsSpacing,<br>        );<br>      },<br>      itemCount: widgets.length,<br>    );<br>  }</pre><p>this is <strong>ListView.Seprated</strong> widget which will build widgets which arevisible on screen it is like <strong>recyclable list</strong>.</p><p>We can’t use this directly as we have to implement pagination where we will append new children from <strong>nextUrl</strong> as we reach list bottom.</p><pre>Widget _paginatedWidget() {<br>  return ValueListenableBuilder(<br>      valueListenable: _scaffoldState.pageDataEventNotifier,<br>      builder: (context, event, _) {<br>        List&lt;Widget&gt; widgets = WidgetUtil.childrenFilter(event.children)<br>            .map((child) =&gt; child.build(context))<br>            .toList();<br>        if (event is PageSuccessEvent || event is PageProgressEvent) {<br>          if (!showPaginatedLoaderOnTop &amp;&amp;<br>              StringUtil.isNotEmptyNorNull(_scaffoldState.nextUrl) &amp;&amp;<br>              widgets.isNotEmpty) {<br>            if (paginatedLoaderWidget == null) {<br>              widgets.add(_loaderWidget());<br>            } else {<br>              widgets.add(paginatedLoaderWidget!.build(context));<br>            }<br>          }<br>          return _paginatedListWidget(widgets);<br>        } else if (event is PageErrorEvent) {<br>          return _paginatedListWidget(widgets);<br>        }<br>        return const SizedBox.shrink();<br>      });<br>}</pre><p>We will use this Widget in body of scaffold. we are having <strong>pageDataEventNotifier</strong> which will help to get children.</p><p>3. Now, we will create <strong>DyScaffoldState</strong> where we will keep logic of fetching new children. This class has to extend <strong>ScrollListener</strong> which will listen to scroll changes of list view if you have noticed we have attached scroll controller to list view.</p><pre>class DyScaffoldState extends ScrollListener {<br>  String? nextUrl;<br>  DynamicScaffold _parent;<br>  late bool _isFetchingPageInProgress;<br>  late ValueNotifier&lt;PageDataEvent&gt; pageDataEventNotifier;<br>  late ValueNotifier&lt;bool&gt; showPaginatedLoaderOnTopNotifier;<br><br>  bool get isFetchingPageInProgress =&gt; _isFetchingPageInProgress;<br><br>  DyScaffoldState(this.nextUrl, this._parent) {<br>    DynamicListeners.addListener(_parent.key, this);<br>    _isFetchingPageInProgress = false;<br>    pageDataEventNotifier = ValueNotifier(PageSuccessEvent(_parent.children));<br>    showPaginatedLoaderOnTopNotifier = ValueNotifier(_isFetchingPageInProgress);<br>  }<br><br>  _fetch() async {<br>    ...<br>  }<br><br>  @override<br>  void onScrolled(String? widgetKey) {<br>    debugPrint(<br>        &#39;dy_scaffold ${_parent.appBar!.pageTitle} onScrolled $widgetKey&#39;);<br>  }<br><br>  @override<br>  void onScrolledToEnd(String? widgetKey) {<br>    debugPrint(<br>        &#39;dy_scaffold ${_parent.appBar!.pageTitle}  onScrolledToEnd $widgetKey&#39;);<br>    _fetch();<br>  }<br><br>  @override<br>  void onScrolledToStart(String? widgetKey) {<br>    debugPrint(<br>        &#39;dy_scaffold ${_parent.appBar!.pageTitle}  onScrolledToStart $widgetKey&#39;);<br>  }<br>}</pre><p>in the <strong>constructor</strong> init we will add <strong>pageKey</strong> and add in scroll listener list.</p><p>if you see <strong>onScrollToEnd</strong> we will call <strong>_fetch()</strong>.</p><p>we will add the listener to listeners list.</p><pre>DyScaffoldState(this.nextUrl, this._parent) {<br>    DynamicListeners.addListener(_parent.key, this);<br>    _isFetchingPageInProgress = false;<br>    pageDataEventNotifier = ValueNotifier(PageSuccessEvent(_parent.children));<br>    showPaginatedLoaderOnTopNotifier = ValueNotifier(_isFetchingPageInProgress);<br>}</pre><p>4. Now, we will fetch json using <strong>nextUrl. </strong>The Json which we fetch from <strong>nextUrl</strong> should be in a specific format.</p><pre>{<br>  &quot;nextUrl&quot;: &quot;https://your_domain.com/homepage?offset=10&amp;limit=10&quot;<br>  &quot;children&quot;: [{<br>    &quot;type&quot;: &quot;dy_container&quot;,<br>    &quot;data&quot;: {<br>      &quot;key&quot;: &quot;1231223233&quot;,<br>      &quot;child&quot;: {<br>        &quot;type&quot;: &quot;dy_card&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;123994545123&quot;,<br>          &quot;color&quot;: &quot;0xffff0000&quot;,<br>          &quot;margin&quot;: &quot;10&quot;,<br>          &quot;elevation&quot;: 10,<br>          &quot;linearGradient&quot;: &quot;-1.0,0.0;1.0,0.0;0xff6D59D4,0xff879CFB&quot;,<br>          &quot;borderRadius&quot;: 20,<br>          &quot;child&quot;: {<br>            &quot;type&quot;: &quot;dy_text&quot;,<br>            &quot;data&quot;: {<br>              &quot;key&quot;: &quot;343245454&quot;,<br>              &quot;text&quot;: &quot;Card&quot;,<br>              &quot;height&quot;: 100,<br>              &quot;width&quot;: 200,<br>              &quot;textAlign&quot;: &quot;center&quot;,<br>              &quot;style&quot;: {<br>                &quot;color&quot;: &quot;0xffffffff&quot;,<br>                &quot;fontSize&quot;: 25,<br>                &quot;fontWeight&quot;: &quot;bold&quot;<br>              }<br>            }<br>          }<br>        }<br>      }<br>    }<br>  }]<br>}</pre><p>So what we do is fetch this json and append the children list to end of main list.</p><pre>_fetch() async {<br>  try {<br>    if (_isFetchingPageInProgress == false &amp;&amp; StringUtil.isNotEmptyNorNull(nextUrl)) {<br>      _isFetchingPageInProgress = true;<br>      showPaginatedLoaderOnTopNotifier.value = _isFetchingPageInProgress;<br>      await Future.delayed(const Duration(milliseconds: 500));<br>      pageDataEventNotifier.value =<br>          PageProgressEvent(pageDataEventNotifier.value.children);<br>      Map&lt;String, dynamic&gt; jsonResponse = {};<br><br>      if (StringUtil.isUrlAssetPath(nextUrl!)) {<br>        jsonResponse = await WidgetUtil.loadJson(nextUrl!);<br>      } else {<br>        jsonResponse = jsonDecode((await NetworkHandler.getJsonFromRequest(<br>              DynamicRequest(<br>                  url: nextUrl!,<br>                  requestType: RequestType.get,<br>                  sendTimeout: Duration(seconds: 20),<br>                  receiveTimeout: Duration(seconds: 20)),<br>            ))<br>                ?.data<br>                ?.toString() ??<br>            &#39;&#39;);<br>      }<br><br>      List&lt;DynamicWidget&gt; newChildren = [];<br><br>      List&lt;Map&lt;String, dynamic&gt;&gt;? newChildrenMap =<br>          List.from(jsonResponse[&#39;children&#39;] as Iterable&lt;dynamic&gt;);<br><br>      for (var child in newChildrenMap) {<br>        newChildren.add(DynamicWidget.fromJson(child)..parent = _parent);<br>      }<br><br>      if (Util.isValidList&lt;dynamic&gt;(newChildrenMap)) {<br>        nextUrl = jsonResponse[&#39;nextUrl&#39;] ?? &#39;&#39;;<br>      } else {<br>        nextUrl = &#39;&#39;;<br>      }<br>      pageDataEventNotifier.value.children?.addAll(newChildren);<br>      pageDataEventNotifier.value =<br>          PageSuccessEvent(pageDataEventNotifier.value.children);<br><br>      _isFetchingPageInProgress = false;<br>      showPaginatedLoaderOnTopNotifier.value = _isFetchingPageInProgress;<br>    }<br>  } on Error catch (e) {<br>    pageDataEventNotifier.value =<br>        PageErrorEvent(pageDataEventNotifier.value.children, e.toString());<br>  } on Exception catch (e) {<br>    pageDataEventNotifier.value =<br>        PageErrorEvent(pageDataEventNotifier.value.children, e.toString());<br>  } finally {<br>    _isFetchingPageInProgress = false;<br>    showPaginatedLoaderOnTopNotifier.value = _isFetchingPageInProgress;<br>  }<br>}</pre><p>This is full code of <strong>_fetch().</strong></p><p>if you run the app you will see this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*Eehe_SqxheOdJ1E2x-DO-Q.gif" /></figure><p>You can do your own customizations like above i have added loader on scroll end and the card comes up.</p><h4>Now, We will discuss <strong>Session Manager</strong></h4><ol><li>Session Management means handling authentication scenarios such as <strong>NoAuthenticated</strong>, <strong>Authenticated</strong>, <strong>AuthenticationExpired</strong> and other scenarios. This is a generic implementation nothing new.</li></ol><p>2. For <strong>Session Management</strong> we first have to create a <strong>Session State</strong> class in this we will keep logic of session states.</p><pre>//code snippet from serve_dynamic_ui<br>class SessionManagerState {<br>  static final SessionManagerState _instance =<br>      SessionManagerState._privateConstructor();<br><br>  static const String _authKey = &#39;AUTH_DETAILS&#39;;<br>  static const String _authSessionKey = &#39;AUTH_SESSION_KEY&#39;;<br>  static final SecureStorage _secureStorage = SecureStorage.instance;<br><br>  SessionManagerState._privateConstructor() {<br>    _sessionStreamController.sink.add(SessionUndeterminedEvent());<br>    _sendAuthenticatedStreamIfAuthenticated();<br>  }<br><br>  ///singleton instance of [SessionManagerState]<br>  static SessionManagerState get instance {<br>    return _instance;<br>  }<br><br>  final StreamController&lt;SessionEvent&gt; _sessionStreamController =<br>      StreamController&lt;SessionEvent&gt;.broadcast();<br><br>  ///stream thorugh which events are received<br>  Stream&lt;SessionEvent&gt; get sessionStream =&gt; _sessionStreamController.stream;<br><br>  ///controller to pass the events<br>  StreamController&lt;SessionEvent&gt; get sessionStreamController =&gt;<br>      _sessionStreamController;<br><br>  static String generateRandomSessionString(int length) {<br>    const characters =<br>        &#39;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&#39;;<br>    Random random = Random();<br>    return List.generate(<br>            length, (index) =&gt; characters[random.nextInt(characters.length)])<br>        .join();<br>  }<br><br>  static Future&lt;void&gt; clearAuthDetails() async {<br>    await _secureStorage.delete(key: _authKey);<br>    await _secureStorage.delete(key: _authSessionKey);<br>  }<br><br>  static Future&lt;void&gt; storeAuthDetails({dynamic authDetails}) async {<br>    if (authDetails is Map) {<br>      await _secureStorage.put(key: _authKey, value: jsonEncode(authDetails));<br>    }<br>    await _secureStorage.put(<br>        key: _authSessionKey, value: generateRandomSessionString(10));<br>  }<br><br>  _sendAuthenticatedStreamIfAuthenticated() async {<br>    Future.delayed(const Duration(milliseconds: 1000), () async {<br>      bool isValid = StringUtil.isNotEmptyNorNull(<br>          await _secureStorage.get(key: _authSessionKey));<br>      if (isValid) {<br>        _sessionStreamController.sink.add(SessionOnAuthenticatedEvent());<br>      } else {<br>        _sessionStreamController.sink.add(SessionNotAuthenticatedEvent());<br>      }<br>    });<br>  }<br><br>  ///dispose the stream<br>  void dispose() async {<br>    await _sessionStreamController.close();<br>  }<br>}</pre><p>We have <strong>sessionStream</strong> which we will use in <strong>StreamBuilder</strong> as we get session stream we use different widget builders based on session events.</p><pre>SessionManagerState._privateConstructor() {<br>    _sessionStreamController.sink.add(SessionUndeterminedEvent());<br>    _sendAuthenticatedStreamIfAuthenticated();<br>}</pre><p>as we initialize the State we first pass <strong>Undetermined</strong> State and then we will check <strong>authentication state</strong> of user by calling <strong>_sendAuthenticatedStreamIfAuthenticated().</strong></p><pre>_sendAuthenticatedStreamIfAuthenticated() async {<br>  Future.delayed(const Duration(milliseconds: 1000), () async {<br>    bool isValid = StringUtil.isNotEmptyNorNull(<br>        await _secureStorage.get(key: _authSessionKey));<br>    if (isValid) {<br>      _sessionStreamController.sink.add(SessionOnAuthenticatedEvent());<br>    } else {<br>      _sessionStreamController.sink.add(SessionNotAuthenticatedEvent());<br>    }<br>  });<br>}</pre><p>We have stored <strong>authInfo</strong> value in this <strong>AUTH_SESSION_KEY </strong>securely using secure storage. This <strong>authInfo</strong> should be stored as <strong>Map</strong> if not passed we add random session key.</p><pre>static Future&lt;void&gt; storeAuthDetails({dynamic authDetails}) async {<br>  if (authDetails is Map) {<br>    await _secureStorage.put(key: _authKey, value: jsonEncode(authDetails));<br>  }<br>  await _secureStorage.put(<br>      key: _authSessionKey, value: generateRandomSessionString(10));<br>}</pre><p>3. Now, we will create a <strong>SessionManagerWidget</strong></p><pre>class SessionManagerWidget extends StatefulWidget {<br>  final WidgetCreator onUndetermined;<br>  final WidgetCreator onAuthenticated;<br>  final WidgetCreator deAuthenticated;<br>  final WidgetCreator? onAuthenticationInProgress;<br>  final WidgetCreator? onAuthenticationExpired;<br>  final WidgetCreator notAuthenticated;<br>  final WidgetCreator? deAuthenticationInProgress;<br>  final WidgetCreator? onAuthenticationFailed;<br>  final WidgetContainer? widgetContainer;<br><br>  const SessionManagerWidget({<br>    super.key,<br>    required this.onUndetermined,<br>    required this.onAuthenticated,<br>    required this.deAuthenticated,<br>    required this.onAuthenticationInProgress,<br>    required this.onAuthenticationExpired,<br>    required this.notAuthenticated,<br>    this.deAuthenticationInProgress,<br>    this.onAuthenticationFailed,<br>    this.widgetContainer,<br>  });<br><br>  @override<br>  State&lt;SessionManagerWidget&gt; createState() =&gt; _SessionManagerWidgetState();<br>}<br><br>class _SessionManagerWidgetState extends State&lt;SessionManagerWidget&gt; {<br>  @override<br>  Widget build(BuildContext context) {<br>    return StreamBuilder(<br>      stream: SessionManagerState.instance.sessionStream,<br>      builder: (context, snapshot) {<br>        Widget child;<br>        if (!snapshot.hasData) {<br>          child = widget.onUndetermined.call();<br>        } else {<br>          if (snapshot.data is SessionNotAuthenticatedEvent) {<br>            child = widget.notAuthenticated.call();<br>          } else if (snapshot.data is SessionOnAuthenticatedEvent) {<br>            child = widget.onAuthenticated.call();<br>          } else if (snapshot.data is SessionDeAuthenticatedEvent) {<br>            child = widget.deAuthenticated.call();<br>          } else if (snapshot.data is SessionOnAuthenticationInProgressEvent &amp;&amp;<br>              widget.onAuthenticationInProgress != null) {<br>            child = widget.onAuthenticationInProgress!.call();<br>          } else if (snapshot.data is SessionAuthenticationExpiredEvent &amp;&amp;<br>              widget.onAuthenticationExpired != null) {<br>            child = widget.onAuthenticationExpired!.call();<br>          } else if (snapshot.data is SessionDeAuthenticationInProgressEvent &amp;&amp;<br>              widget.deAuthenticationInProgress != null) {<br>            child = widget.deAuthenticationInProgress!.call();<br>          } else if (snapshot.data is SessionAuthenticationFailedEvent &amp;&amp;<br>              widget.onAuthenticationFailed != null) {<br>            child = widget.onAuthenticationFailed!.call();<br>          } else {<br>            child = widget.onUndetermined.call();<br>          }<br>        }<br><br>        if (widget.widgetContainer != null) {<br>          return widget.widgetContainer!(child);<br>        }<br>        return AnimatedSwitcher(<br>          duration: const Duration(milliseconds: 500),<br>          transitionBuilder: (Widget child, Animation&lt;double&gt; animation) {<br>            return FadeTransition(<br>                opacity: Tween&lt;double&gt;(begin: 0.8, end: 1.0).animate(animation),<br>                child: child);<br>          },<br>          child: child,<br>        );<br>      },<br>    );<br>  }<br><br>  @override<br>  void dispose() {<br>    SessionManagerState.instance.dispose();<br>    super.dispose();<br>  }<br>}</pre><p>this is just a simple widget based on various sesion events we will replace various widget builders and transition using animation.</p><p>4. Now, to use this we have to update Session Like this</p><pre>SessionManagerState.instance.sessionStreamController.sink.add(<br>  SessionOnAuthenticatedEvent(<br>    authInfo: {<br>      &#39;email&#39;: value[&#39;textFieldData&#39;][0],<br>      &#39;userName&#39;: value[&#39;textFieldData&#39;][1],<br>    },<br>  ),<br>);</pre><p>like this you will update session to authenticated and so on.</p><p>5. Now, to use <strong>SessionManagerWidget</strong></p><pre>SessionManagerWidget(<br>  onUndetermined: () {<br>    return ServeDynamicUI.fromAssets(<br>      &#39;assets/json/loader.json&#39;,<br>    );<br>  },<br>  onAuthenticated: () {<br>    return ServeDynamicUI.fromNetwork(<br>      DynamicRequest(<br>        url:<br>            &#39;https://raw.githubusercontent.com/ServeDynamicUI/serve_dynamic_ui/main/example/assets/json/list_view.json?isPageCacheEnabled=true&#39;,<br>        requestType: RequestType.get,<br>      ),<br>      templateJsonPath:<br>          &#39;assets/json/shimmer_pages/default_page_shimmer.json&#39;,<br>    );<br>  },<br>  deAuthenticated: () {<br>    return ServeDynamicUI.fromNetwork(<br>      DynamicRequest(<br>        url:<br>            &#39;https://raw.githubusercontent.com/ServeDynamicUI/serve_dynamic_ui/main/example/assets/json/sample.json?isPageCacheEnabled=true&#39;,<br>        requestType: RequestType.get,<br>      ),<br>      templateJsonPath:<br>          &#39;assets/json/shimmer_pages/default_page_shimmer.json&#39;,<br>    );<br>  },<br>  onAuthenticationInProgress: () {<br>    return ServeDynamicUI.fromAssets(<br>      &#39;assets/json/loader.json&#39;,<br>    );<br>  },<br>  deAuthenticationInProgress: () {<br>    return ServeDynamicUI.fromAssets(<br>      &#39;assets/json/loader.json&#39;,<br>    );<br>  },<br>  onAuthenticationExpired: () {<br>    return const SizedBox();<br>  },<br>  notAuthenticated: () {<br>    return ServeDynamicUI.fromNetwork(<br>      DynamicRequest(<br>          url:<br>              &#39;https://raw.githubusercontent.com/ServeDynamicUI/serve_dynamic_ui/main/example/assets/json/sample.json?isPageCacheEnabled=true&#39;,<br>          requestType: RequestType.get,<br>          sendTimeout: const Duration(seconds: 10),<br>          receiveTimeout: const Duration(seconds: 10)),<br>      templateJsonPath:<br>          &#39;assets/json/shimmer_pages/default_page_shimmer.json&#39;,<br>    );<br>  },<br>  onAuthenticationFailed: () {<br>    return ServeDynamicUI.fromAssets(<br>      &#39;assets/json/loader.json&#39;,<br>    );<br>  },<br>)</pre><p>this is how you will use this widget, you can use both <strong>static and dynamic screens</strong> based on your requirements.</p><p>On click of login button it will be authenticated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*coYENUvPvYiWqbD4KDi94g.gif" /></figure><h4>Now, Last is <strong>Shimmer Loading Pages.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*UlsQrHjhvAjmg_294BDShw.gif" /></figure><p>As you can see above while we fetch homepage json we show shimmer page effects.</p><p>So lets start</p><ol><li>We will be using <a href="https://pub.dev/packages/shimmer">shimmer</a> package to implement shimmer effects in widgets. you can add shimmers on any widget using shimmer package.</li><li>So we will be creating shimmer json page.</li></ol><pre>{<br>  &quot;type&quot;: &quot;dy_scaffold&quot;,<br>  &quot;data&quot;: {<br>    &quot;key&quot;: &quot;default_page_shimmer&quot;,<br>    &quot;crossAxisAlignment&quot;: &quot;start&quot;,<br>    &quot;appBar&quot;: {<br>      &quot;pageTitle&quot;: &quot;Flutter Server UI Home Screen&quot;<br>    },<br>    &quot;padding&quot;: &quot;10,0,10,10&quot;,<br>    &quot;children&quot;: [<br>      {<br>        &quot;type&quot;: &quot;dy_shimmer_column&quot;,<br>        &quot;data&quot;: {<br>          &quot;key&quot;: &quot;dy_shimmer_column&quot;,<br>          &quot;itemCount&quot;: 10,<br>          &quot;interItemSpacing&quot;: 10,<br>          &quot;childItems&quot;: [<br>            {<br>              &quot;type&quot;: &quot;dy_shimmer_widget_card&quot;,<br>              &quot;data&quot;: {<br>                &quot;key&quot;: &quot;dy_shimmer_widget_card&quot;,<br>                &quot;padding&quot;: &quot;10,15,15,15&quot;,<br>                &quot;margin&quot;: &quot;2&quot;,<br>                &quot;height&quot;: 80,<br>                &quot;borderRadius&quot;: 10,<br>                &quot;prefixImage&quot;: {<br>                  &quot;type&quot;: &quot;dy_shimmer_image&quot;,<br>                  &quot;data&quot;: {<br>                    &quot;key&quot;: &quot;dy_shimmer_image&quot;,<br>                    &quot;placeholderImagePath&quot;: &quot;assets/images/icon_placeholder.png&quot;,<br>                    &quot;clipBorderRadius&quot;: 10,<br>                    &quot;height&quot;: 50,<br>                    &quot;width&quot;: 50,<br>                    &quot;fit&quot;: &quot;fill&quot;,<br>                    &quot;shimmerBaseColor&quot;: &quot;0x00000000&quot;<br>                  }<br>                },<br>                &quot;body&quot;: {<br>                  &quot;type&quot;: &quot;dy_shimmer_column&quot;,<br>                  &quot;data&quot;: {<br>                    &quot;key&quot;: &quot;dy_shimmer_column&quot;,<br>                    &quot;itemCount&quot;: 1,<br>                    &quot;interItemSpacing&quot;: 10,<br>                    &quot;crossAxisAlignment&quot;: &quot;start&quot;,<br>                    &quot;childItems&quot;: [<br>                      {<br>                        &quot;type&quot;: &quot;dy_shimmer_button&quot;,<br>                        &quot;data&quot;: {<br>                          &quot;key&quot;: &quot;dy_shimmer_button&quot;,<br>                          &quot;height&quot;: 10,<br>                          &quot;width&quot;: 100,<br>                          &quot;buttonBorderRadius&quot;: 0,<br>                          &quot;shimmerBaseColor&quot;: &quot;0xFFE0E0E0&quot;,<br>                          &quot;shimmerHighlightColor&quot;: &quot;0xFFF5F5F5&quot;<br>                        }<br>                      },<br>                      {<br>                        &quot;type&quot;: &quot;dy_shimmer_row&quot;,<br>                        &quot;data&quot;: {<br>                          &quot;key&quot;: &quot;dy_shimmer_row&quot;,<br>                          &quot;itemCount&quot;: 1,<br>                          &quot;interItemSpacing&quot;: 0,<br>                          &quot;crossAxisAlignment&quot;: &quot;start&quot;,<br>                          &quot;childItems&quot;: [<br>                            {<br>                              &quot;type&quot;: &quot;dy_shimmer_button&quot;,<br>                              &quot;data&quot;: {<br>                                &quot;key&quot;: &quot;dy_shimmer_button&quot;,<br>                                &quot;height&quot;: 10,<br>                                &quot;width&quot;: 200,<br>                                &quot;buttonBorderRadius&quot;: 0,<br>                                &quot;shimmerBaseColor&quot;: &quot;0xFFE0E0E0&quot;,<br>                                &quot;shimmerHighlightColor&quot;: &quot;0xFFF5F5F5&quot;<br>                              }<br>                            }<br>                          ]<br>                        }<br>                      }<br>                    ]<br>                  }<br>                }<br>              }<br>            }<br>          ]<br>        }<br>      }<br>    ]<br>  }<br>}</pre><p>I have created a <strong>shimmer_column</strong> in this we will have list of widgets which will be repeated <strong>itemCount </strong>times<strong>.</strong> If you saw the JSON same<strong> dy_shimmer_widget_card</strong> is repeated 10 times.</p><p>3. Lets build <strong>dy_shimmer_column</strong> this is not really adding any shimmer effect but it will repeat the shimmer widgets.</p><pre>DynamicShimmerColumn({<br>  required this.key,<br>  required this.itemCount,<br>  required this.childItems,<br>  this.mainAxisAlignment,<br>  this.crossAxisAlignment,<br>  this.interItemSpacing = 10,<br>  this.height,<br>  this.width,<br>})</pre><pre>@override<br>Widget build(BuildContext context) {<br>  return Column(<br>    mainAxisAlignment: mainAxisAlignment ?? MainAxisAlignment.start,<br>    crossAxisAlignment: crossAxisAlignment ?? CrossAxisAlignment.center,<br>    children: WidgetUtil.dynamicWidgetsSpacing(<br>      context,<br>      _listView(context),<br>      interItemSpacing,<br>      isHorizontal: false,<br>    ),<br>  );<br>}<br><br>List&lt;DynamicWidget&gt; _listView(BuildContext context) {<br>  List&lt;DynamicWidget&gt; widgets = [];<br><br>  if (itemCount &gt; 0) {<br>    for (int i = 0; i &lt; itemCount; i++) {<br>      if (childWidgets != null) {<br>        widgets.addAll(childItems!.toList());<br>      }<br>    }<br>  }<br>  return widgets;<br>}</pre><p>if you see in column widget we are adding the same <strong>childItems</strong> to widgets list <strong>itemCount</strong> times.</p><p>4. So lets build one of the dynamic shimmer widget <strong>dy_shimmer_button.</strong></p><pre>DynamicShimmerButton({<br>  required this.key,<br>  this.shimmerBaseColor,<br>  this.shimmerHighlightColor,<br>  super.width,<br>  super.height,<br>  super.buttonBorderRadius,<br>})</pre><p>this is the constructor where pass <strong>shimmerBaseColor</strong> and <strong>shimmerHighlightColor.</strong></p><pre>@override<br>Widget build(BuildContext context) {<br>  Widget buttonContent = Container(<br>    decoration: BoxDecoration(<br>      color: shimmerBaseColor ?? Colors.grey,<br>      borderRadius: BorderRadius.all(<br>        Radius.circular(<br>          buttonBorderRadius ?? 0,<br>        ),<br>      ),<br>    ),<br>    height: height,<br>    width: width,<br>  );<br><br>  return Shimmer.fromColors(<br>    baseColor: shimmerBaseColor ?? Colors.grey,<br>    highlightColor: shimmerHighlightColor ?? Colors.white,<br>    child: buttonContent,<br>  );<br>}</pre><p>I just simply wrapped <strong>Shimmer.fromColors()</strong> with button content.</p><p>and then register this dynamic widget so that we can use this in json.</p><pre>DynamicWidgetHandlerRepo.addDynamicWidgetHandler(<br>    &#39;dy_shimmer_button&#39;, (json) =&gt; DynamicShimmerButton.fromJson(json));</pre><p>you can build your own dynamic shimmers based on your requirement.</p><p><strong>That is it for this article. We have learnt lot of things in this article.</strong></p><h3>Thank You For Reading the Article</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6159effa9a31" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/server-driven-ui-implementation-from-scratch-in-flutter-part-4-6159effa9a31">Server-Driven UI Implementation from Scratch in Flutter: Part 4</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Blockchain based Crowdfunding React native app: Part 1]]></title>
            <link>https://levelup.gitconnected.com/build-blockchain-based-crowdfunding-react-native-app-part-1-5ec1f03adf37?source=rss-1e41946a95c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ec1f03adf37</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <dc:creator><![CDATA[Sk Ahron]]></dc:creator>
            <pubDate>Mon, 03 Jun 2024 15:56:40 GMT</pubDate>
            <atom:updated>2024-06-03T15:56:40.475Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*KAh9kVEZCQtQ6ivQ9Jjy1w.png" /></figure><blockquote><strong>Note:</strong> You must be familiar with blockchain terms and solidity knowledge is required.</blockquote><p>In this article I will explain how you can build a blockchain based react native app. In this Part, I will explain the smart contract which i created for a Crowdfunding App which has CRUD operations like in normal react native app.</p><p>here is the <a href="https://github.com/Arunshaik2001/crowd-funding-app"><strong>Github link</strong></a></p><p><strong><em>Functionalities of the app:</em></strong></p><ol><li><strong>Create a funding campaign.</strong></li><li><strong>Update a campaign.</strong></li><li><strong>Delete a campaign.</strong></li><li><strong>Donate tokens to a campaign.</strong></li><li><strong>Withdraw raised amount.</strong></li><li><strong>Automatic end campaigns as per their timeline.</strong></li></ol><p><a href="https://youtu.be/TbLBYCSeUbc">https://youtu.be/TbLBYCSeUbc</a></p><p><a href="https://youtu.be/PM9i8Cabmuk">https://youtu.be/PM9i8Cabmuk</a></p><p>Below is the smart contract for crowdfunding. Don’t worry i will explain below contract.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.7;<br><br>import &quot;@chainlink/contracts/src/v0.8/automation/AutomationCompatible.sol&quot;;<br><br>contract CrowdFunding is AutomationCompatibleInterface {<br>    error CrowdFunding__NoCampaign(uint id);<br>    error CrowdFunding__NotCampaignOwner(uint id, address sender);<br>    error CrowdFunding__WithdrawFailed(uint id);<br>    error CrowdFunding__CampaignDeletionFailed(uint id);<br>    error CrowdFunding__NoTokenToWithdraw(uint id);<br>    error CrowdFunding__UpkeepNotNeeded();<br><br>    event CrowdFunding__CampaignCreated(uint indexed id);<br>    event CrowdFunding__CampaignUpdated(uint indexed id);<br>    event CrowdFunding__CampaignDeleted(uint indexed id);<br>    event CrowdFunding__TokenSent(uint indexed id);<br>    event CrowdFunding__WithdrawSuccess(uint indexed id, uint indexed amountRaised);<br><br>    struct Campaign {<br>        uint id;<br>        string title;<br>        string description;<br>        string image;<br>        uint startDate;<br>        uint endDate;<br>        uint amountRaised;<br>        uint amountWithdrawn;<br>        address[] funders;<br>        address owner;<br>    }<br><br><br>    uint256 public counter;<br>    mapping (uint =&gt; Campaign) private campaigns;<br>    mapping (uint =&gt; uint) private campaignIndexes;<br>    Campaign[] campaignsList;<br>    uint private campaignCount;<br>    uint private actualCount;<br><br>    uint256 public lastTimeStamp;<br><br>    constructor(){<br>        campaignCount = 1;<br>        lastTimeStamp = block.timestamp;<br>    }<br><br>    modifier campaignOwner(uint _id) {<br>        if(campaigns[_id].id == 0){<br>            revert CrowdFunding__NoCampaign(_id);<br>        }<br><br>        if(campaigns[_id].owner != msg.sender){<br>            revert CrowdFunding__NotCampaignOwner(_id, msg.sender);<br>        }<br><br>        _;<br>    }<br><br>    function createCampaign(string memory _title, string memory _description, string memory _image, uint _startDate, uint _endDate) external{<br>        Campaign memory campaign = Campaign(campaignCount, _title, _description, _image, _startDate, _endDate, 0, 0, new address[](0), msg.sender);<br>        campaigns[campaignCount] = campaign;<br>        campaignsList.push(campaign);<br>        campaignIndexes[campaignCount] = campaignsList.length - 1;<br>        campaignCount++;<br>        actualCount++;<br>        emit CrowdFunding__CampaignCreated(campaignCount-1);<br>    }<br><br>    function updateCampaign(uint _id, string memory _title, string memory _description, string memory _image, uint _endDate) external campaignOwner(_id){<br>        Campaign memory campaign = Campaign(_id, _title, _description, _image, campaigns[_id].startDate, _endDate, campaigns[_id].amountRaised, campaigns[_id].amountWithdrawn, campaigns[_id].funders, campaigns[_id].owner);<br>        campaigns[_id] = campaign;<br>        campaignsList[campaignIndexes[_id]] = campaign;<br><br>        emit CrowdFunding__CampaignUpdated(_id);<br>    }<br><br>    function endCampaign(uint _id) public {<br>        if(campaigns[_id].id == 0){<br>            revert CrowdFunding__NoCampaign(_id);<br>        }<br><br>        if(campaigns[_id].amountRaised &gt; 0){<br>            bool success = withdraw(_id);<br>            if(!success){<br>                revert CrowdFunding__CampaignDeletionFailed(_id);<br>            }<br>        }<br><br>        delete campaigns[_id];<br>        delete campaignsList[campaignIndexes[_id]];<br>        actualCount--;<br>        emit CrowdFunding__CampaignDeleted(_id);<br>    }<br><br>    function sendTokenToCampaign(uint _id) external payable{<br>        if(campaigns[_id].id == 0){<br>            revert CrowdFunding__NoCampaign(_id);<br>        }<br>        Campaign storage campaign = campaigns[_id];<br>        campaign.amountRaised += msg.value;<br>        campaign.funders.push(msg.sender);<br><br>        campaigns[_id] = campaign;<br>        campaignsList[campaignIndexes[_id]] = campaign;<br>        emit CrowdFunding__TokenSent(_id);<br>    }<br><br>    function getCampaignById(uint _id) public view returns (Campaign memory){<br>        if(campaigns[_id].id == 0){<br>            revert CrowdFunding__NoCampaign(_id);<br>        }<br>        return campaigns[_id];<br>    }<br><br>    function totalCampaignActive() external view returns (uint){<br>        return actualCount;<br>    }<br><br>    function withdraw(uint _id) public campaignOwner(_id) returns (bool){<br>        if(campaigns[_id].id == 0){<br>            revert CrowdFunding__NoCampaign(_id);<br>        }<br><br>        if(campaigns[_id].amountRaised == 0){<br>            revert CrowdFunding__NoTokenToWithdraw(_id);<br>        }<br><br>        if(campaigns[_id].amountWithdrawn &lt; campaigns[_id].amountRaised){<br>            uint amountWithdrw = campaigns[_id].amountWithdrawn;<br>            uint sendAmount = campaigns[_id].amountRaised - amountWithdrw;<br>            campaigns[_id].amountWithdrawn += sendAmount;<br>            campaignsList[campaignIndexes[_id]] = campaigns[_id];<br>            (bool success, ) = payable(campaigns[_id].owner).call{value: sendAmount}(&quot;&quot;);<br><br>            if(!success){<br>                revert CrowdFunding__WithdrawFailed(_id);<br>            }<br><br>            emit CrowdFunding__WithdrawSuccess(_id, campaigns[_id].amountRaised);<br><br>            return success;<br>        }<br>        else{<br>            revert CrowdFunding__WithdrawFailed(_id);<br>        }<br>    }<br><br>    function getCurrentTime()public view returns(uint){<br>        return block.timestamp;<br>    }<br><br>    function getCampaigns() public view returns (Campaign[] memory){<br>        return campaignsList;<br>    }<br><br><br>    function checkUpkeep(<br>        bytes calldata /* checkData */<br>    )<br>        external<br>        view<br>        override<br>        returns (bool upkeepNeeded, bytes memory performData)<br>    {<br>        for(uint index = 0 ; index &lt; campaignsList.length ; index++){<br>            Campaign memory cmpgn = campaignsList[index];<br>            <br>            if(cmpgn.id &gt; 0 &amp;&amp; block.timestamp &gt;= cmpgn.endDate){<br>                return (true, performData);<br>            }<br>        }<br><br>        return (false, performData);<br>    }<br><br>    function performUpkeep(bytes calldata /* performData */) external override {<br>        lastTimeStamp = block.timestamp;<br>        for(uint index = 0 ; index &lt; campaignsList.length ; index++){<br>            Campaign memory cmpgn = campaignsList[index];<br>            if(cmpgn.id &gt; 0 &amp;&amp; block.timestamp &gt;= cmpgn.endDate){<br>                endCampaign(cmpgn.id);<br>            }<br>        }<br>        counter = counter + 1;<br>    }<br>}</pre><p>I have created a<strong> struct campaign </strong>which holds all the info about a campaign</p><pre>struct Campaign {<br>        uint id;<br>        string title;<br>        string description;<br>        string image;<br>        uint startDate;<br>        uint endDate;<br>        uint amountRaised;<br>        uint amountWithdrawn;<br>        address[] funders;<br>        address owner;<br>    }</pre><p><strong>id:</strong> represents the unique value assigned to it.<br><strong>title:</strong> the header of the campaign.<br><strong>description:</strong> description about the campaign.<br><strong>startDate:</strong> is the date when the campaign is created in seconds.<br><strong>endDate</strong>: is the ending date in seconds.<br><strong>amountRaised:</strong> is the total amount donated to this campaign.<br><strong>amountWithdrawn:</strong> is the amount withdrawn by the owner so far.<br><strong>funders:</strong> is the list of funder addresses who donated.<br><strong>owner: </strong>is the owner address who created the campaign.</p><pre>constructor(){<br>        campaignCount = 1;<br>        lastTimeStamp = block.timestamp;<br>    }</pre><p>in the <strong>constructor</strong> i have initialised the <strong>campaignCount</strong> to 1 means <strong>ids</strong> of campaign will start from 1 and increment by 1.</p><pre>function createCampaign(string memory _title, string memory _description, string memory _image, uint _startDate, uint _endDate) external{<br>        Campaign memory campaign = Campaign(campaignCount, _title, _description, _image, _startDate, _endDate, 0, 0, new address[](0), msg.sender);<br>        campaigns[campaignCount] = campaign;<br>        campaignsList.push(campaign);<br>        campaignIndexes[campaignCount] = campaignsList.length - 1;<br>        campaignCount++;<br>        actualCount++;<br>        emit CrowdFunding__CampaignCreated(campaignCount-1);<br>    }</pre><p>Now, the create campaign where user will pass the parameters and create a campaign object and will store the campaign in map as well push the object in a list and then increment <strong>campaignCount</strong> and <strong>actualCount</strong> after successfully performing all operations will emit an event <strong>CrowdFunding__CampaignCreated.</strong></p><blockquote><strong>Note</strong>: <strong>actualCount</strong> will tell the count of campaigns active, as deleting an item from array will make the object to take default values but not remove it.</blockquote><pre>function updateCampaign(uint _id, string memory _title, string memory _description, string memory _image, uint _endDate) external campaignOwner(_id){<br>        Campaign memory campaign = Campaign(_id, _title, _description, _image, campaigns[_id].startDate, _endDate, campaigns[_id].amountRaised, campaigns[_id].amountWithdrawn, campaigns[_id].funders, campaigns[_id].owner);<br>        campaigns[_id] = campaign;<br>        campaignsList[campaignIndexes[_id]] = campaign;<br><br>        emit CrowdFunding__CampaignUpdated(_id);<br>    }</pre><p>Now, if you want to update the campaign parameters you want to update.<br>I have kept <strong>title, description, endDate, and image</strong> updatable. So create a new campaign object and store it to same mapping and at correct index place. Or you can even get the same campaign instance from mapping and update the values assign back it will be more gas efficient.</p><p>if you see this function i have set a <strong>modifier</strong> <strong>campaignOwner</strong>. I added this modifier so that only the user address who created the campaign can only update the campaign to keep other addresses to update it.</p><pre>modifier campaignOwner(uint _id) {<br>        if(campaigns[_id].id == 0){<br>            revert CrowdFunding__NoCampaign(_id);<br>        }<br><br>        if(campaigns[_id].owner != msg.sender){<br>            revert CrowdFunding__NotCampaignOwner(_id, msg.sender);<br>        }<br><br>        _;<br>    }</pre><p>Now to <strong>end a campaign</strong> we will delete the mapping of id and remove it from the campaign list and reduce actual count before ending a campaign i am checking if amount raised has some value if yes withdraw and send the tokens to owner of the campaign. It will only set objects to default value.</p><pre> [<br>    {<br>      &quot;type&quot;: &quot;BigNumber&quot;,<br>      &quot;hex&quot;: &quot;0x00&quot;<br>    },<br>    &quot;&quot;,<br>    &quot;&quot;,<br>    &quot;&quot;,<br>    {<br>      &quot;type&quot;: &quot;BigNumber&quot;,<br>      &quot;hex&quot;: &quot;0x00&quot;<br>    },<br>    {<br>      &quot;type&quot;: &quot;BigNumber&quot;,<br>      &quot;hex&quot;: &quot;0x00&quot;<br>    },<br>    {<br>      &quot;type&quot;: &quot;BigNumber&quot;,<br>      &quot;hex&quot;: &quot;0x00&quot;<br>    },<br>    [],<br>    &quot;0x0000000000000000000000000000000000000000&quot;<br>  ]</pre><pre>function endCampaign(uint _id) public {<br>        if(campaigns[_id].id == 0){<br>            revert CrowdFunding__NoCampaign(_id);<br>        }<br><br>        if(campaigns[_id].amountRaised &gt; 0){<br>            bool success = withdraw(_id);<br>            if(!success){<br>                revert CrowdFunding__CampaignDeletionFailed(_id);<br>            }<br>        }<br><br>        delete campaigns[_id];<br>        delete campaignsList[campaignIndexes[_id]];<br>        actualCount--;<br>        emit CrowdFunding__CampaignDeleted(_id);<br>    }</pre><p>I have kept this <strong>public</strong> so anyone can end campaign and i have done one more thing i have <strong>automated</strong> this method so that it can be called by <a href="https://dev.chain.link/products/automation"><strong>chainlink keeper</strong></a><strong> </strong>nodes to auto end campaigns whose end date is passed. I will show how to do this later in this article.</p><pre>    function sendTokenToCampaign(uint _id) external payable{<br>        if(campaigns[_id].id == 0){<br>            revert CrowdFunding__NoCampaign(_id);<br>        }<br>        Campaign storage campaign = campaigns[_id];<br>        campaign.amountRaised += msg.value;<br>        campaign.funders.push(msg.sender);<br><br>        campaigns[_id] = campaign;<br>        campaignsList[campaignIndexes[_id]] = campaign;<br>        emit CrowdFunding__TokenSent(_id);<br>    }</pre><p>above method is to donate to a campaign if you want a function to accept token you need to set it as <strong>payable</strong> so that this method can be called with sending tokens. as you can see i have updated <strong>amountRaised</strong> and added the address who sent token in the array of <strong>funders</strong> of the campaign.</p><pre>function withdraw(uint _id) public campaignOwner(_id) returns (bool){<br>        if(campaigns[_id].id == 0){<br>            revert CrowdFunding__NoCampaign(_id);<br>        }<br><br>        if(campaigns[_id].amountRaised == 0){<br>            revert CrowdFunding__NoTokenToWithdraw(_id);<br>        }<br><br>        if(campaigns[_id].amountWithdrawn &lt; campaigns[_id].amountRaised){<br>            uint amountWithdrw = campaigns[_id].amountWithdrawn;<br>            uint sendAmount = campaigns[_id].amountRaised - amountWithdrw;<br>            campaigns[_id].amountWithdrawn += sendAmount;<br>            campaignsList[campaignIndexes[_id]] = campaigns[_id];<br>            (bool success, ) = payable(campaigns[_id].owner).call{value: sendAmount}(&quot;&quot;);<br><br>            if(!success){<br>                revert CrowdFunding__WithdrawFailed(_id);<br>            }<br><br>            emit CrowdFunding__WithdrawSuccess(_id, campaigns[_id].amountRaised);<br><br>            return success;<br>        }<br>        else{<br>            revert CrowdFunding__WithdrawFailed(_id);<br>        }<br>    }</pre><p>Now, the withdraw function where i have put a check if <strong>amountWithdrawn</strong> so far is less than <strong>amountRaised</strong> then only user can withdraw left amount. I have updated the state before sending the tokens.</p><p>These are the main functions of the smart contract and rest are basically <strong>getter</strong> functions.</p><p><strong>Now, I will show you how you can automate the smart contract using chainlink automation.</strong></p><pre>import &quot;@chainlink/contracts/src/v0.8/automation/AutomationCompatible.sol&quot;;</pre><p>you need to import this in your smart contract. To add automation in contract you need to implement 2 functions which are in <strong>AutomationCompatible</strong> solidity file provided by chainlink if you are using remix it will import without adding any dependency but if you are working on vscode install this using:</p><p><strong>yarn add @chainlink/contracts</strong></p><pre>function checkUpkeep(<br>        bytes calldata /* checkData */<br>    )<br>        external<br>        view<br>        override<br>        returns (bool upkeepNeeded, bytes memory performData)<br>    {<br>        //upkeepNeeded = (block.timestamp - lastTimeStamp) &gt; interval;<br>        for(uint index = 0 ; index &lt; campaignsList.length ; index++){<br>            Campaign memory cmpgn = campaignsList[index];<br>            <br>            if(cmpgn.id &gt; 0 &amp;&amp; block.timestamp &gt;= cmpgn.endDate){<br>                return (true, performData);<br>            }<br>        }<br><br>        return (false, performData);<br>    }<br><br>    function performUpkeep(bytes calldata /* performData */) external override {<br>        lastTimeStamp = block.timestamp;<br>        for(uint index = 0 ; index &lt; campaignsList.length ; index++){<br>            Campaign memory cmpgn = campaignsList[index];<br>            if(cmpgn.id &gt; 0 &amp;&amp; block.timestamp &gt;= cmpgn.endDate){<br>                endCampaign(cmpgn.id);<br>            }<br>        }<br>        counter = counter + 1;<br>    }</pre><p><strong>checkUpKeep</strong> is called off-chain using chainlink nodes. if upkeep is need then on-chain it calls <strong>performUpkeep</strong> to perform operations you want.</p><p>so here i have custom logic which is i<strong>f current time is greater than or equals to any campaign endDate in seconds then we need to perform upkeep. </strong>In <strong>performUpkeep</strong> i just simply calling <strong>endCampaign</strong> function which i discussed above.</p><p>Before it starts working we need to register this contract on chainlink automation so that registry contracts can know that a contract is registered.<br><a href="https://automation.chain.link/mumbai">https://automation.chain.link/</a></p><p>You can register your deployed contract. I have deployed my contract on <strong>polygon mumbai testnet</strong>.</p><p>It looks like this after registering. you can see there are 3 <strong>performUpkeep</strong> calls as i was doing testing. this is how you can register.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vU5xrsWTKj0zt4mpSXXsTw.png" /></figure><p>So, writing the smart contract for crowdfunding is done. you can improve the smart contract more and modify as per your needs.</p><p><strong>That’s it for this part. In the next part we will see how to interact with the deployed smart contract using thirdweb in bare react native.</strong></p><h3>Thank You</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ec1f03adf37" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/build-blockchain-based-crowdfunding-react-native-app-part-1-5ec1f03adf37">Build Blockchain based Crowdfunding React native app: Part 1</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Blockchain based Crowdfunding React native app: Part 2]]></title>
            <link>https://levelup.gitconnected.com/build-blockchain-based-crowdfunding-react-native-app-part-2-e7b2b89292cf?source=rss-1e41946a95c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7b2b89292cf</guid>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Sk Ahron]]></dc:creator>
            <pubDate>Mon, 03 Jun 2024 15:56:21 GMT</pubDate>
            <atom:updated>2024-06-03T15:56:21.599Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*JjZweuPBPWe8aPyZDu1tsQ.png" /></figure><blockquote><strong><em>Note: </em></strong>Please check out Part 1 to understand the smart contract implementation of the crowdfunding app.</blockquote><p>In this part, we will learn how to interact with your deployed smart contract using <a href="https://www.npmjs.com/package/@thirdweb-dev/react-native">thirdweb react native sdk</a>. It provides easy way to interact with blockchain.</p><blockquote><strong><em>Note:</em></strong> You must be having knowledge of react native.</blockquote><p>Let’s get started</p><p>Here is the <a href="https://github.com/Arunshaik2001/crowd-funding-app"><strong>Github link</strong></a></p><p>This is the app we are going to build performing CRUD operations.</p><p><a href="https://youtu.be/TbLBYCSeUbc">https://youtu.be/TbLBYCSeUbc</a></p><p><a href="https://youtu.be/PM9i8Cabmuk">https://youtu.be/PM9i8Cabmuk</a></p><p><strong>Step 1: </strong>Set up <strong>thirdweb</strong> in your app.</p><p>if you are creating new react native project use this command</p><pre>npx thirdweb create --template react-native-typescript-starter</pre><p>It will download a template which has <strong>thirdweb</strong> dependencies.</p><p><strong>Step 2:</strong> Go to <strong>thirdweb</strong> and connect your wallet. I am using metamask account which has <strong>sepolia and mumbai</strong> test tokens. you can also get test link faucets online.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9oQtO7osrUA6I-lifjZPJw.png" /></figure><p>You will need your <strong>client id</strong> which is required to connect to thirdweb and interact with the smart contract deployed.</p><p><strong>Step 3:</strong> In contracts tab, you need to import your contract so that thirdweb sdk can connect with your contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hGpM3NRgcbPNv8cWkdQheQ.png" /></figure><p>You need to verify your smart contract on <a href="https://sourcify.dev/#/verifier">sourcify</a> in order to detect the abi by thirdweb or you can use thirdweb cli to deploy and auto verify.</p><p><strong>Step 4:</strong> In the <strong>App.tsx</strong> you are already getting default app ready. In the .env file <strong>TW_CLIENT_ID</strong> is present set it with your client id which you got.</p><p><strong>TW_CLIENT_ID=518d9XXXXXXXXXXXX3d9f4</strong></p><p>my <strong>active chain</strong> is <strong>mumbai</strong> you may set it to other chain depending upon your usecase</p><p><strong>Step 5:</strong> I am going to need navigation in the app so i use <strong>react-navigation</strong> library for <strong>navigations</strong>. <br>If you are not familiar with navigation in react native check out my <a href="https://medium.com/gitconnected/navigation-in-react-native-apps-8c9b02250bce"><strong>article</strong></a>.</p><pre>const Stack = createNativeStackNavigator();<br>const BottomTabs = createMaterialBottomTabNavigator();<br><br>const MainStack = () =&gt; {<br>  return (<br>    &lt;Stack.Navigator<br>      screenOptions={{<br>        headerBackVisible: false,<br>      }}&gt;<br>      &lt;Stack.Screen<br>        name=&quot;OnboardScreen&quot;<br>        component={OnboardingScreen}<br>        options={{title: &#39;Connect Wallet&#39;}}<br>      /&gt;<br>      &lt;Stack.Screen<br>        name=&quot;HomeTabScreen&quot;<br>        component={HomeTabScreen}<br>        options={{<br>          headerShown: false,<br>        }}<br>      /&gt;<br>      &lt;Stack.Screen<br>        name=&quot;CampaignDetailScreen&quot;<br>        component={CampaignDetailScreen}<br>        options={{title: &#39;Create Campaign&#39;, headerBackVisible: true}}<br>      /&gt;<br>    &lt;/Stack.Navigator&gt;<br>  );<br>};<br><br>function HomeScreenStack({route, navigation}) {<br>  return (<br>    &lt;&gt;<br>      &lt;Stack.Navigator&gt;<br>        &lt;Stack.Screen<br>          name=&quot;HomeScreen&quot;<br>          component={HomeScreen}<br>          options={{<br>            title: &#39;Home&#39;,<br>            headerRight: ({size}) =&gt; {<br>              return (<br>                &lt;Pressable<br>                  onPress={() =&gt; {<br>                    navigation.navigate(&#39;CampaignDetailScreen&#39;, {<br>                      isCreate: true,<br>                      campaign: undefined,<br>                    });<br>                  }}&gt;<br>                  &lt;Icon name=&quot;plus&quot; size={24} /&gt;<br>                &lt;/Pressable&gt;<br>              );<br>            },<br>          }}<br>        /&gt;<br>      &lt;/Stack.Navigator&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>function YourCampaignScreenStack({route, navigation}) {<br>  return (<br>    &lt;Stack.Navigator&gt;<br>      &lt;Stack.Screen<br>        name=&quot;YourCampaignScreen&quot;<br>        component={YourCampaignScreen}<br>        options={{<br>          title: &#39;Your Campaigns&#39;,<br>          headerRight: ({size}) =&gt; {<br>            return (<br>              &lt;Pressable<br>                onPress={() =&gt; {<br>                  navigation.navigate(&#39;CampaignDetailScreen&#39;, {<br>                    isCreate: true,<br>                    campaign: undefined,<br>                  });<br>                }}&gt;<br>                &lt;Icon name=&quot;plus&quot; size={24} /&gt;<br>              &lt;/Pressable&gt;<br>            );<br>          },<br>        }}<br>      /&gt;<br>    &lt;/Stack.Navigator&gt;<br>  );<br>}<br><br>function HomeTabScreen({route, navigation}) {<br>  return (<br>    &lt;&gt;<br>      &lt;BottomTabs.Navigator<br>        barStyle={{<br>          marginLeft: 10,<br>          marginRight: 10,<br>          borderRadius: 10,<br>          borderWidth: 1,<br>        }}&gt;<br>        &lt;BottomTabs.Screen<br>          name=&quot;HomeScreenBottomTab&quot;<br>          component={HomeScreenStack}<br>          options={{<br>            title: &#39;Home&#39;,<br>            tabBarIcon: ({focused, color, size}) =&gt; {<br>              return (<br>                &lt;Icon<br>                  name=&quot;home&quot;<br>                  size={24}<br>                  color={focused ? &#39;#8B0000&#39; : color}<br>                /&gt;<br>              );<br>            },<br>          }}<br>        /&gt;<br>        &lt;BottomTabs.Screen<br>          name=&quot;YourCampaignScreenBottomTab&quot;<br>          component={YourCampaignScreenStack}<br>          options={{<br>            title: &quot;Your&#39;s&quot;,<br>            tabBarIcon: ({focused, color, size}) =&gt; {<br>              return (<br>                &lt;Icon<br>                  name=&quot;bandcamp&quot;<br>                  size={24}<br>                  color={focused ? &#39;#8B0000&#39; : color}<br>                /&gt;<br>              );<br>            },<br>          }}<br>        /&gt;<br>      &lt;/BottomTabs.Navigator&gt;<br>      &lt;Toast /&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>const App = () =&gt; {<br>  return (<br>    &lt;NavigationContainer&gt;<br>      {<br>        &lt;ThirdwebProvider<br>          activeChain={&#39;mumbai&#39;}<br>          clientId={Config.TW_CLIENT_ID}<br>          supportedWallets={[<br>            metamaskWallet({<br>              recommended: true,<br>            }),<br>            rainbowWallet(),<br>            walletConnect({<br>              recommended: true,<br>            }),<br>            trustWallet(),<br>            localWallet(),<br>          ]}&gt;<br>          &lt;MainStack /&gt;<br>        &lt;/ThirdwebProvider&gt;<br>      }<br>    &lt;/NavigationContainer&gt;<br>  );<br>};<br></pre><p>So I wrapped everything in <strong>NavigationContainer</strong> where I have put my <strong>MainStack</strong> which use Stack Navigation where I have kept 2 Screens and a <strong>Bottom Navigator</strong>.</p><p>Now, the onboarding screen is the first screen visible to user which simply shows Connect wallet button this functionality under the hood is performed by connect wallet sdk.</p><pre>const OnboardingScreen = ({route, navigation}) =&gt; {<br>  const address = useAddress();<br>  const isDarkMode = useColorScheme() === &#39;dark&#39;;<br><br>  function navigateToHomeScreen() {<br>    navigation.replace(&#39;HomeTabScreen&#39;);<br>  }<br><br>  const textStyles = {<br>    color: isDarkMode ? Colors.white : Colors.black,<br>    ...styles.heading,<br>  };<br><br>  return (<br>    &lt;View style={styles.view}&gt;<br>      &lt;Text style={textStyles}&gt;Welcome to RN Crowd Funding App&lt;/Text&gt;<br>      &lt;ConnectWallet /&gt;<br>      {address != undefined ? (<br>        &lt;View style={styles.fixedButtonContainer}&gt;<br>          &lt;GradientButton<br>            onPress={() =&gt; {<br>              navigateToHomeScreen();<br>            }}<br>            title=&quot;Continue&quot;<br>          /&gt;<br>        &lt;/View&gt;<br>      ) : null}<br>    &lt;/View&gt;<br>  );<br>};</pre><p>So, now you can use hooks provided by thirdweb here i am using <strong>useAddress</strong> hook to check if there is any account connected so that if address is present I am showing <strong>continue</strong> button. User has to connect to a wallet to access homescreen.</p><p><strong>Step 6: </strong>Once, wallet is connected user can continue. In the homescreen we have to load all the campaigns. To do so we must need to connect to our deployed contract for that you need the contract address.</p><pre>const HomeScreen = () =&gt; {<br>  const {contract} = useContract(&#39;0x8a4AD413059Be74cE3125876D3382bE71dFAAE8e&#39;);<br><br>  const {data: contracts, isLoading} = useContractRead(<br>    contract,<br>    &#39;getCampaigns&#39;,<br>  );<br><br>  const contractList = contracts?.filter(item =&gt; item.id &gt; BigNumber.from(0));<br><br>  return (<br>    &lt;View style={styles.container}&gt;<br>      &lt;FlatList<br>        data={contractList}<br>        renderItem={({item}) =&gt; &lt;CampaignPreview campaign={item} main={true} /&gt;}<br>        keyExtractor={item =&gt; item.id.toString()}<br>        ListEmptyComponent={() =&gt; (<br>          &lt;View style={styles.centeredView}&gt;<br>            &lt;Text style={{color: &#39;red&#39;}}&gt;No Campaigns Found....&lt;/Text&gt;<br>          &lt;/View&gt;<br>        )}<br>      /&gt;<br>    &lt;/View&gt;<br>  );<br>};</pre><pre>0x8a4AD413059Be74cE3125876D3382bE71dFAAE8e: this is mumbai testnet deployed contract address</pre><p>to read your contract functions you need to use <strong>useContract</strong> hook passing you contract address.</p><pre>const {contract} = useContract(&#39;0x8a4AD413059Be74cE3125876D3382bE71dFAAE8e&#39;);</pre><p><strong>if your solidity function is pure, view functions then it is a read operation.</strong></p><p>so in our case <strong>getCampaigns</strong> is a read operation we need to use <strong>useContractRead</strong> hook.</p><pre>const {data: contracts, isLoading} = useContractRead(<br>    contract,<br>    &#39;getCampaigns&#39;,<br>);</pre><p>once we get list of campaigns we will filter if <strong>id</strong> is greater than zero or not.</p><p>then pass it to <strong>Filterlist</strong>.</p><p>This Campaign Preview item is used in both <strong>Home tab</strong> and <strong>Your’s tab</strong> list item. <strong>OnClick</strong> of this item will vary depending upon where it is rendered if in home tab then if the current user wallet address is not equal to campaign owner address then user can donate on click of the campaign preview. if its in Your’s tab on click of it user will get menu option to update, delete and withdraw raised amount.</p><pre>type CampaignPreviewProp = {<br>  campaign: Campaign;<br>  main: boolean;<br>  deleteCampaign?: (() =&gt; Promise&lt;void&gt;) | null;<br>  updateCampaign?: () =&gt; void | null;<br>};<br><br>const CampaignPreview = ({<br>  campaign,<br>  main,<br>  deleteCampaign,<br>  updateCampaign,<br>}: CampaignPreviewProp) =&gt; {<br>  const [bottomSheetVisible, setBottomSheetVisible] = useState(false);<br><br>  const {contract} = useContract(Config.CONTRACT_ADDRESS);<br><br>  const {<br>    mutateAsync: sendTokenToCampaign,<br>    isLoading: sendTokenToCampaignLoading,<br>  } = useContractWrite(contract, &#39;sendTokenToCampaign&#39;);<br><br>  const {mutateAsync: withdraw, isLoading: withdrawLoading} = useContractWrite(<br>    contract,<br>    &#39;withdraw&#39;,<br>  );<br><br>  const address = useAddress();<br><br>  const showBottomSheet = () =&gt; {<br>    setBottomSheetVisible(true);<br>  };<br><br>  const hideBottomSheet = () =&gt; {<br>    setBottomSheetVisible(false);<br>  };<br><br>  const showToast = (title: string, description: string) =&gt; {<br>    Toast.show({<br>      type: &#39;success&#39;,<br>      text1: title,<br>      text2: description,<br>    });<br>  };<br><br>  const menuActions: MenuAction[] = [<br>    {<br>      id: &#39;update&#39;,<br>      title: &#39;Update Campaign&#39;,<br>      titleColor: &#39;#46F289&#39;,<br>      imageColor: &#39;#46F289&#39;,<br>      state: &#39;on&#39;,<br>    },<br>    {<br>      id: &#39;delete&#39;,<br>      title: &#39;Delete Campaign&#39;,<br>      attributes: {<br>        destructive: false,<br>      },<br>      image: Platform.select({<br>        ios: &#39;trash&#39;,<br>        android: &#39;ic_menu_delete&#39;,<br>      }),<br>    },<br>  ];<br><br>  if (!main &amp;&amp; Number(campaign.amountRaised) &gt; 0) {<br>    menuActions.push({<br>      id: &#39;withdraw&#39;,<br>      title: &#39;Withdraw Raised Amount&#39;,<br>      titleColor: &#39;#46F289&#39;,<br>      imageColor: &#39;#46F289&#39;,<br>      state: &#39;on&#39;,<br>    });<br>  }<br><br>  return (<br>    &lt;TouchableOpacity<br>      onPress={() =&gt; {<br>        if (main &amp;&amp; campaign.owner !== address) {<br>          showBottomSheet();<br>        }<br>      }}&gt;<br>      &lt;View style={styles.container}&gt;<br>        {main ? (<br>          &lt;&gt;<br>            &lt;Details campaign={campaign} /&gt;<br>            &lt;TokenBottomSheet<br>              isVisible={bottomSheetVisible}<br>              onClose={hideBottomSheet}<br>              handleButtonClick={async value =&gt; {<br>                const response = await sendTokenToCampaign({<br>                  args: [campaign.id],<br>                  overrides: {<br>                    value: BigNumber.from(value),<br>                  },<br>                });<br><br>                if (response.receipt.confirmations &gt; 0) {<br>                  hideBottomSheet();<br>                  showToast(&#39;Sent token&#39;, &#39;thank you for donating...&#39;);<br>                }<br>              }}<br>            /&gt;<br>          &lt;/&gt;<br>        ) : (<br>          &lt;MenuView<br>            title=&quot;Menu Title&quot;<br>            onPressAction={async ({nativeEvent}) =&gt; {<br>              if (nativeEvent.event == &#39;delete&#39;) {<br>                deleteCampaign?.call(this);<br>              } else if (nativeEvent.event == &#39;update&#39;) {<br>                updateCampaign?.call(this);<br>              } else {<br>                const res = await withdraw({args: [campaign.id]});<br>                if (res.receipt.confirmations &gt; 0) {<br>                  showToast(<br>                    &#39;Withdraw Successful&#39;,<br>                    &#39;You have withdrawn raised amount...&#39;,<br>                  );<br>                }<br>              }<br>            }}<br>            actions={menuActions}<br>            shouldOpenOnLongPress={false}&gt;<br>            &lt;Details campaign={campaign} /&gt;<br>          &lt;/MenuView&gt;<br>        )}<br>      &lt;/View&gt;<br>    &lt;/TouchableOpacity&gt;<br>  );<br>};</pre><p>Now, to send tokens we need to call <strong>sendTokenToCampaign</strong> function which is payable.</p><pre>const {<br>    mutateAsync: sendTokenToCampaign,<br>    isLoading: sendTokenToCampaignLoading,<br>} = useContractWrite(contract, &#39;sendTokenToCampaign&#39;);</pre><p>so <strong>useContractWrite</strong> hook provides a <strong>mutation</strong> and <strong>mutation async</strong>. i am using async one you can sync too. On success of this method you will get <strong>transaction receipt</strong></p><p>Now, to <strong>withdraw amount raised</strong> again we will use <strong>useContractWrite</strong> hook.</p><p>You can <strong>delete a campaign</strong> again using the same write hook passing the correct function name.</p><p><strong>Step 7: </strong>Now, <strong>YourCampaignScreen</strong> where I have <strong>useContractWrite</strong> hook for <strong>endCampaign</strong>. This screen shows the campaigns created by the current user wallet owner.</p><pre>const YourCampaignScreen = ({route, navigation}) =&gt; {<br>  const {contract} = useContract(Config.CONTRACT_ADDRESS);<br><br>  const {data: contracts, isLoading} = useContractRead(<br>    contract,<br>    &#39;getCampaigns&#39;,<br>  );<br><br>  const {mutateAsync: createCampaign, isLoading: settingName} =<br>    useContractWrite(contract, &#39;createCampaign&#39;);<br><br>  const address = useAddress();<br><br>  const contractList = contracts?.filter(<br>    item =&gt; item.id &gt; BigNumber.from(0) &amp;&amp; address === item.owner,<br>  );<br><br>  const {mutateAsync: endCampaign, isLoading: endCampaignLoading} =<br>    useContractWrite(contract, &#39;endCampaign&#39;);<br><br><br>  const showToast = (title: string, description: string) =&gt; {<br>    Toast.show({<br>      type: &#39;success&#39;,<br>      text1: title,<br>      text2: description,<br>    });<br>  };<br><br>  return (<br>    &lt;View style={styles.container}&gt;<br>      &lt;FlatList<br>        data={contractList}<br>        renderItem={({item}) =&gt; (<br>          &lt;CampaignPreview<br>            campaign={item}<br>            main={false}<br>            updateCampaign={() =&gt; {<br>              navigation.push(&#39;CampaignDetailScreen&#39;, {<br>                isCreate: false,<br>                campaign: item,<br>              });<br>            }}<br>            deleteCampaign={async () =&gt; {<br>              const response = await endCampaign({args: [item.id]});<br>              if (response.receipt.confirmations &gt; 0) {<br>                showToast(<br>                  &#39;Deleted Campaign&#39;,<br>                  &#39;Successfully deleted &#39; + item.title,<br>                );<br>              }<br>            }}<br>          /&gt;<br>        )}<br>        keyExtractor={item =&gt; item.id.toString()}<br>        ListEmptyComponent={() =&gt; (<br>          &lt;View style={styles.centeredView}&gt;<br>            &lt;Text style={{color: &#39;red&#39;}}&gt;<br>              You Have No Campaigns Created....<br>            &lt;/Text&gt;<br>          &lt;/View&gt;<br>        )}<br>      /&gt;<br>    &lt;/View&gt;<br>  );<br>};</pre><p><strong>Step 8:</strong> Now, to update or create a campaign i have created another name <strong>CampaignDetailScreen</strong> . It has Image, Title, Description, Start Date picker and end date picker. The image input field should be <a href="https://docs-ipfs-tech.ipns.dweb.link/"><strong>ipfs</strong></a><strong> </strong>pinned CID(content identifier) address. I have used <a href="https://pinata.cloud/"><strong>pinata</strong></a> to upload an image and get the CID. the images on homescreen is rendered using <strong>Image</strong> component and <strong>url</strong> is prefixed with <strong>pinata gateway</strong>. I have created a Rounded Button Component separately which you can find in the github repo. So If user wants to create a campaign user can click + icon on homescreen and create a campaign using <strong>createCampaign</strong> mutate function passing all the data which we are taking from user and if user clicks on his/her own campaign from Your’s tab then user can update the campaign using <strong>updateCampaign </strong>passing the campaign id.</p><pre>const CampaignDetailScreen = ({route, navigation}) =&gt; {<br>  const isCreate = route.params.isCreate;<br>  const campaign = isCreate<br>    ? {<br>        id: 1,<br>        title: &#39;&#39;,<br>        description: &#39;&#39;,<br>        image: &#39;&#39;,<br>        owner: &#39;&#39;,<br>        amountRaised: 0,<br>        funders: [],<br>        startDate: getSecondsFromDate(new Date()),<br>        endDate: getSecondsFromDate(new Date()),<br>      }<br>    : route.params.campaign;<br><br>  const [startDate, setStartDate] = useState(<br>    new Date(Number(campaign.startDate) * 1000),<br>  );<br>  const [date, setDate] = useState(new Date(Number(campaign.endDate) * 1000));<br>  const [open, setOpen] = useState(false);<br>  const [openStart, setOpenStart] = useState(false);<br>  const [editableImageURl, setEditableImageUrl] = useState(campaign.image);<br>  const [editableTitle, setEditableTitle] = useState(campaign.title);<br>  const [editableDescription, setEditableDescription] = useState(<br>    campaign.description,<br>  );<br>  const [editableOwner, setEditableOwner] = useState(campaign.owner);<br><br>  const {contract} = useContract(Config.CONTRACT_ADDRESS);<br><br>  const {mutateAsync: updateCampaign, isLoading: updateCampaignLoading} =<br>    useContractWrite(contract, &#39;updateCampaign&#39;);<br><br>  const {mutateAsync: createCampaign, isLoading: createCampaignLoading} =<br>    useContractWrite(contract, &#39;createCampaign&#39;);<br><br><br>  const showToast = (title: string, description: string) =&gt; {<br>    Toast.show({<br>      type: &#39;success&#39;,<br>      text1: title,<br>      text2: description,<br>    });<br>  };<br><br>  return (<br>    &lt;View style={styles.card}&gt;<br>      &lt;View style={styles.detailsContainer}&gt;<br>        &lt;TextInput<br>          style={styles.editableText}<br>          value={editableImageURl}<br>          onChangeText={setEditableImageUrl}<br>          placeholder=&quot;Image Url&quot;<br>        /&gt;<br>        &lt;TextInput<br>          style={styles.editableText}<br>          value={editableTitle}<br>          onChangeText={setEditableTitle}<br>          placeholder=&quot;Title&quot;<br>        /&gt;<br>        &lt;TextInput<br>          style={styles.editableText}<br>          value={editableDescription}<br>          onChangeText={setEditableDescription}<br>          placeholder=&quot;Description&quot;<br>          multiline<br>        /&gt;<br>        &lt;View style={styles.additionalDetails}&gt;<br>          &lt;TextInput<br>            style={styles.editableText}<br>            value={editableOwner}<br>            onChangeText={setEditableOwner}<br>            placeholder=&quot;Owner&quot;<br>          /&gt;<br><br>          {isCreate ? (<br>            &lt;View&gt;<br>              &lt;RoundedButton<br>                title={`Select start date\n\n${startDate.toLocaleString(<br>                  &#39;en-Us&#39;,<br>                  {<br>                    year: &#39;numeric&#39;,<br>                    month: &#39;long&#39;,<br>                    day: &#39;numeric&#39;,<br>                    hour: &#39;numeric&#39;,<br>                    minute: &#39;numeric&#39;,<br>                    second: &#39;numeric&#39;,<br>                    hour12: true,<br>                  },<br>                )}`}<br>                onPress={() =&gt; {<br>                  setOpenStart(true);<br>                }}<br>              /&gt;<br>              &lt;DatePicker<br>                modal<br>                open={openStart}<br>                date={startDate}<br>                mode=&quot;datetime&quot;<br>                onConfirm={date =&gt; {<br>                  setOpenStart(false);<br>                  setStartDate(date);<br>                }}<br>                onCancel={() =&gt; {<br>                  setOpenStart(false);<br>                }}<br>              /&gt;<br>              &lt;View style={{height: 10}}&gt;&lt;/View&gt;<br>            &lt;/View&gt;<br>          ) : null}<br>          &lt;RoundedButton<br>            title={`Select end date\n\n${date.toLocaleString(&#39;en-Us&#39;, {<br>              year: &#39;numeric&#39;,<br>              month: &#39;long&#39;,<br>              day: &#39;numeric&#39;,<br>              hour: &#39;numeric&#39;,<br>              minute: &#39;numeric&#39;,<br>              second: &#39;numeric&#39;,<br>              hour12: true,<br>            })}`}<br>            onPress={() =&gt; {<br>              setOpen(true);<br>            }}<br>          /&gt;<br>          &lt;View style={{height: 10}}&gt;&lt;/View&gt;<br>          &lt;RoundedButton<br>            title={isCreate ? &#39;Create Campaign&#39; : &#39;Update Campaign Details&#39;}<br>            onPress={async () =&gt; {<br>              if (isCreate) {<br>                const response = await createCampaign({<br>                  args: [<br>                    editableTitle,<br>                    editableDescription,<br>                    editableImageURl,<br>                    BigNumber.from(Math.floor(startDate.getTime() / 1000)),<br>                    BigNumber.from(Math.floor(date.getTime() / 1000)),<br>                  ],<br>                });<br>                console.log(response.receipt);<br><br>                if (response.receipt.confirmations &gt; 0) {<br>                  showToast(<br>                    &#39;Created Campaign&#39;,<br>                    &#39;Successfully created &#39; + campaign.title,<br>                  );<br>                }<br>              } else {<br>                const response = await updateCampaign({<br>                  args: [<br>                    campaign.id,<br>                    editableTitle,<br>                    editableDescription,<br>                    editableImageURl,<br>                    BigNumber.from(Math.floor(date.getTime() / 1000)),<br>                  ],<br>                });<br>                console.log(response.receipt);<br><br>                if (response.receipt.confirmations &gt; 0) {<br>                  showToast(<br>                    &#39;Updated Campaign&#39;,<br>                    &#39;Successfully updated &#39; + campaign.title,<br>                  );<br>                }<br>              }<br>            }}<br>          /&gt;<br>          &lt;DatePicker<br>            modal<br>            open={open}<br>            date={date}<br>            mode=&quot;datetime&quot;<br>            onConfirm={date =&gt; {<br>              setOpen(false);<br>              setDate(date);<br>            }}<br>            onCancel={() =&gt; {<br>              setOpen(false);<br>            }}<br>          /&gt;<br>        &lt;/View&gt;<br>      &lt;/View&gt;<br>    &lt;/View&gt;<br>  );<br>};</pre><p><strong>Step 9:</strong> If you want to pick an image while creating campaign and get the <strong>CID</strong> corresponding to the picked image on create campaign button click. we can use <strong>react-native-image-picker</strong> to pick the image and then we will create our own server which takes the image in <strong>base64 encoding</strong> and then upload the image to <strong>pinata</strong> to pin the image and get the <strong>CID</strong> which we will send back to our app which the can be passed to <strong>createCampaign</strong> mutation.</p><p>So, first let’s import image picker.</p><pre>yarn add react-native-image-picker</pre><p>So, after this create a method to pick image from gallery and get base64 string</p><pre>async function openImagePicker() {<br>    const options: ImageLibraryOptions = {<br>      mediaType: &#39;photo&#39;,<br>      includeBase64: true,<br>      quality: 0.6,<br>    };<br>    const result = await launchImageLibrary(options);<br>    if (result.assets != null) {<br>      base64ImageUri = `data:${result!.assets![0].type};base64,${result!<br>        .assets![0].base64!}`;<br>      setSelectedImage(result!.assets![0].uri!);<br>    }<br>}</pre><p>as you can see i have provided options object where i have included Base64 to get base64 string.</p><p>now, base64 converted image is in this format: <strong><em>data:{EXTENSTION};base64,{ENCODED_STRING}</em></strong></p><p><strong>we will upload the imageString to our server.</strong></p><p><strong>Step 9:</strong> Now, to upload image to our server we need to pass base64 image string and image name which we use in our <strong>backend</strong> while uploading to pinata. So here i am using <strong>FormData</strong> in which we will pass our base64 encoded string and image name</p><pre>async function uploadImage(): Promise&lt;string&gt; {<br>    try {<br>      const formData = new FormData();<br>      formData.append(&#39;base64image&#39;, base64ImageUri);<br>      formData.append(&#39;imageName&#39;, imageName);<br><br>      const response = await fetch(&#39;https://{YOUR_BACKEND_IP}:{PORT}/upload/image&#39;, {<br>        method: &#39;POST&#39;,<br>        headers: {<br>          &#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;,<br>        },<br>        body: formData,<br>      });<br><br>      if (response.ok) {<br>        const responseBody = await response.json();<br>        return responseBody.cid;<br>      }<br>      return &#39;&#39;;<br>    } catch (error) {<br>      console.error(&#39;Error:&#39;, error);<br>      return &#39;&#39;;<br>    }<br>  }</pre><p><strong>Step 10: </strong>Now, the last step is to create our <strong>http server</strong> which has 1 API <strong>/upload/image</strong> is the path. I am using <strong>express</strong> package which is standard in node.js. I am not that good in node.js but managed to get the API working.</p><p>from the request body we will get the base64 image and breaking the string to get extension and encoded value and then writing the encoded value to a file. the file name is same as the file name we sent from our app. once we create the image in <strong>./images</strong> folder we will read the file using ‘fs’ now in node backend we will install <strong>pinata sdk</strong>.</p><p><strong>yarn add @pinata/sdk</strong></p><p>You need an account on pinata cloud after creating account create API key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ad3IVnzuKwtXLb6JXinUsQ.png" /></figure><p>create New key and copy <strong>secret</strong> key and <strong>api</strong> key and initialize pinata sdk</p><p>and now as we want to pin our received image to get <strong>CID</strong></p><pre>const uploadImage = async (req, res, next) =&gt; {<br>  var matches = req.body.base64image.match(/^data:([A-Za-z-+/]+);base64,(.+)$/),<br>    response = {};<br>  if (matches.length !== 3) {<br>    return new Error(&quot;Invalid input string&quot;);<br>  }<br><br>  response.type = matches[1];<br>  response.data = new Buffer.from(matches[2], &quot;base64&quot;);<br>  let decodedImg = response;<br>  let imageBuffer = decodedImg.data;<br>  let type = decodedImg.type;<br>  let extension = mime.getExtension(type);<br>  let fileName = `${req.body.imageName}.` + extension;<br>  try {<br>    fs.writeFileSync(&quot;./images/&quot; + fileName, imageBuffer, &quot;utf8&quot;);<br>    const pinata = new pinataSdk({<br>      pinataApiKey: process.env.API_KEY,<br>      pinataSecretApiKey: process.env.SECRET_KEY,<br>    });<br><br>    const readableStreamForFile = fs.createReadStream(<br>      `./images/${req.body.imageName}.${extension}`<br>    );<br>    const options = {<br>      pinataMetadata: {<br>        name: req.body.imageName,<br>      },<br>      pinataOptions: {<br>        cidVersion: 0,<br>      },<br>    };<br>    const response = await pinata.pinFileToIPFS(readableStreamForFile, options);<br>    console.log(response);<br>    return res.send({ status: &quot;success&quot;, cid: response.IpfsHash });<br>  } catch (e) {<br>    next(e);<br>  }<br>};<br><br>app.post(&quot;/upload/image&quot;, uploadImage);</pre><p>we are calling <strong>pinFileToIPFS</strong> to pin the image file and giving some metadata like giving image a name on pinata.</p><p>So, now if you run the server calling <strong>node index.js.</strong></p><p>and now calling this API from postman to test</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-P6-Tq-h44ES_o2mt4_zJw.png" /></figure><p>you can see you are getting the <strong>CID</strong> if you want test if the image is pinned or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gkjZ-wCn5D6nPmx7D0FD0A.png" /></figure><p>See, image is available.</p><p><strong>We stored the image off-chain on ipfs nodes and getting the CID and storing it on blockchain because storing big files on-chain is very costly.</strong></p><p>You will find all my code in my Github Repo.</p><h4><strong>This is how you can read and write to blockchain using thirdweb react native sdk and use ipfs nodes to store data in decentralized way.</strong></h4><h3>Thank You</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7b2b89292cf" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/build-blockchain-based-crowdfunding-react-native-app-part-2-e7b2b89292cf">Build Blockchain based Crowdfunding React native app: Part 2</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CCAvenue Payment Integration in Android using Node.js]]></title>
            <link>https://proandroiddev.com/ccavenue-payment-integration-in-android-using-node-js-88b1955f0f22?source=rss-1e41946a95c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/88b1955f0f22</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[ccavenue]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Sk Ahron]]></dc:creator>
            <pubDate>Sun, 24 Sep 2023 12:12:05 GMT</pubDate>
            <atom:updated>2023-09-24T12:12:05.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*H3i_qd7VStYErI1G5LWobA.png" /></figure><p>In this article, I will explain how to integrate CCAvenue Payment integration in Android and the backend using node.js.</p><blockquote><strong>Note:</strong> you need to have a CCAvenue account created with your domain/ip whitelisted to make transactions in production and testing environment.</blockquote><p>You have to register your business on ccAvenue after successful registration you will get <strong>workingKey</strong>, <strong>accessCode, </strong>and <strong>merchantId.</strong></p><p><strong>Prerequisite</strong>: You should have some experience in node.js</p><p>Now, we will code our backend in Node.js</p><p>So, the dependency I am using is here.</p><pre>&quot;body-parser&quot;: &quot;^1.20.2&quot;,<br>&quot;cors&quot;: &quot;^2.8.5&quot;,<br>&quot;crypto-js&quot;: &quot;^4.1.1&quot;,<br>&quot;dotenv&quot;: &quot;^16.3.1&quot;,<br>&quot;express&quot;: &quot;^4.18.2&quot;,<br>&quot;node-ccavenue&quot;: &quot;^1.0.5&quot;</pre><p>the main dependency used is <strong>node-ccavenue</strong> this package will help us to call ccAvenue servers to make payments.</p><p>so, In the<strong> index.js</strong> file copy this</p><pre>var express = require(&quot;express&quot;);<br>var app = express();<br>var cors = require(&quot;cors&quot;);<br>const dotenv = require(&quot;dotenv&quot;);<br>const bodyParser = require(&quot;body-parser&quot;);<br><br>app.use(cors());<br>app.use(express.json());<br>dotenv.config();<br><br>const paymentRouter = require(&quot;./routes/payment.routes&quot;);<br><br>app.get(&quot;/&quot;, function (req, res) {<br>  res.send(&quot;CCavenu server!!&quot;);<br>});<br><br>app.use(&quot;/api&quot;, bodyParser.urlencoded(), paymentRouter);<br><br>var server = app.listen(3000, function () {<br>  var host = server.address().address;<br>  var port = server.address().port;<br><br>  console.log(&quot;Example app listening at http://localhost:3000&quot;, host, port);<br>});</pre><p>Here what I have done is started a server on <strong>3000 </strong>port and created a path <strong>/api.</strong></p><p>now the paymentRouter has 2 POST APIs <strong>/request/phone and /response</strong></p><pre>var express = require(&quot;express&quot;);<br>var paymentController = require(&quot;../controllers/payment.controller&quot;);<br>var paymentRouter = express.Router();<br><br>paymentRouter.post(<br>  &quot;/request/phone&quot;,<br>  paymentController.handlePaymentControllerPhone<br>);<br>paymentRouter.post(<br>  &quot;/response&quot;,<br>  paymentController.handleResponsePaymentController<br>);<br><br>module.exports = paymentRouter;</pre><p>this is the <strong>payment.routes.js</strong> file</p><p>So, the <strong>/request/phone</strong> will be called by the client app to get the <strong>payment link</strong> which we will use in the webview to make payment.</p><p><strong>/response</strong> POST call will be called by ccAvenue servers to send the payment success or failure status. Once ccAvenue sends payload based on status we we will redirect to success or failure pages created.</p><p>So, now we will have to write code for handling request to get payment links. so the mobile app will send details about <strong>order_id</strong>, and <strong>amount</strong> to this POST call and this will return the payment link. You can also pass <strong>access_code </strong>and <strong>working_key </strong>from the client to the server to create an encrypted value.</p><pre>static async handlePaymentControllerPhone(req, res, next) {<br>    try {<br>      const ccav = new nodeCCAvenue.Configure({<br>        ...req.body.keys,<br>        merchant_id: &quot;MERCHANT_ID&quot;,<br>      });<br>      const orderParams = {<br>        redirect_url: encodeURIComponent(<br>          `https://DOMAIN/api/response?access_code=${req.body.keys?.access_code}&amp;working_key=${req.body.keys?.working_key}`<br>        ),<br>        cancel_url: encodeURIComponent(<br>          `https://DOMAIN/api/response?access_code=${req.body.keys?.access_code}&amp;working_key=${req.body.keys?.working_key}`<br>        ),<br>        billing_name: &quot;Name of the customer&quot;,<br>        currency: &quot;INR&quot;,<br>        ...req.body.orderParams,<br>      };<br>      const encryptedOrderData = ccav.getEncryptedOrder(orderParams);<br>      res.setHeader(&quot;content-type&quot;, &quot;application/json&quot;);<br>      res.status(200).json({<br>        payLink: `https://secure.ccavenue.com/transaction/transaction.do?command=initiateTransaction&amp;access_code=${req.body.keys.access_code}&amp;encRequest=${encryptedOrderData}`,<br>      });<br>    } catch (err) {<br>      next(err);<br>    }<br>}</pre><p>So I will send back the ccAvenue link to show it in webview.</p><p>the URL sending should be in the correct format mentioned by ccAvenue.</p><p>Now, we will also write code for handling response sent by ccAvenue servers after payment failure or success.</p><pre>static async handleResponsePaymentController(req, res, next) {<br>    try {<br>      var encryption = req.body.encResp;<br>      const ccav = new nodeCCAvenue.Configure({<br>        ...req.query,<br>        merchant_id: &quot;MERCHANT_ID&quot;,<br>      });<br>      var ccavResponse = ccav.redirectResponseToJson(encryption);<br>      var ciphertext = CryptoJS.AES.encrypt(<br>        JSON.stringify(ccavResponse),<br>        &quot;Astro&quot;<br>      ).toString();<br>      if (ccavResponse[&quot;order_status&quot;] == &quot;Success&quot;) {<br>        res.redirect(<br>          `https://DOMAIN/transaction?type=success&amp;val=${ciphertext}`<br>        );<br>      } else {<br>        res.redirect(<br>          `https://DOMAIN/transaction?val=${ciphertext}`<br>        );<br>      }<br>    } catch (error) {<br>      next(error);<br>    }<br>  }</pre><p>this is simple based on <strong>order_status </strong>I will redirect the user to my success page or failure page.</p><p>Now, you have to run the server locally by running this command</p><p><strong>npm start</strong></p><p>Now, if you hit the API from your POSTMAN</p><p>you should get the response. if you run this cURL</p><pre>curl --location &#39;http://localhost:3000/api/request/phone&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--data &#39;{<br>        &quot;orderParams&quot;: {<br>          &quot;order_id&quot;: 1694784153561_12344&quot;,<br>          &quot;amount&quot;: 100,<br>          &quot;language&quot;: &quot;en&quot;<br>        },<br>        &quot;keys&quot;: {<br>          &quot;working_key&quot;: &quot;WORKING_KEY&quot;,<br>          &quot;access_code&quot;: &quot;ACCESS_CODE&quot;<br>        }<br>}&#39;</pre><pre>{<br>    &quot;payLink&quot;: &quot;https://secure.ccavenue.com/transaction/transaction.do?command=initiateTransaction&amp;access_code=ACCESS_CODE&amp;encRequest=d7XXXXXXXXXXX7161XXXXXXXXXXXXXXXXX0a9ca963XXXXXXXXXXXXcb94ffc25a666XXXXX&quot;<br>}</pre><p><strong>So, Now let’s integrate payments into the Mobile App.</strong></p><p>Now, create an Android project.</p><p><strong>Step 1:</strong> You need to make the POST call to the local host server.</p><p>I am using retrofit to make HTTP calls.</p><pre>implementation &quot;com.squareup.retrofit2:retrofit:2.9.0&quot;<br>implementation &quot;com.squareup.retrofit2:converter-gson:2.9.0&quot;</pre><p>Now, create <strong>ApiService.kt</strong> where you will create a method to make Post Request.</p><pre>interface ApiService {<br><br>    @Headers(&quot;Content-Type: application/json&quot;)<br>    @POST(&quot;api/request/phone&quot;)<br>    suspend fun sendPhoneRequest(@Body request: RequestBody): ApiResponse <br>}</pre><p>You need to have data models of input and output.</p><pre>data class RequestBody(<br>    val orderParams: OrderParams,<br>    val keys: Keys<br>)<br><br>data class OrderParams(<br>    val order_id: String,<br>    val amount: Int,<br>    val language: String<br>)<br><br>data class Keys(<br>    val working_key: String,<br>    val access_code: String<br>)<br><br>data class ApiResponse(<br>    val payLink: String<br>)</pre><p>Step 2: Now, create<strong> ApiClient.kt</strong> where you define the configuration to make HTTP calls.</p><pre>object ApiClient {<br>    private const val BASE_URL = &quot;http://10.0.2.2:3000/&quot;<br><br>    private val retrofit: Retrofit = Retrofit.Builder()<br>        .baseUrl(BASE_URL)<br>        .addConverterFactory(GsonConverterFactory.create())<br>        .build()<br><br>    val apiService: ApiService = retrofit.create(ApiService::class.java)<br>}</pre><p><strong>Here I am using localhost and to test on the emulator you need to mention the above BASE_URL.</strong></p><p>To make HTTP call you need to define the network_security_config file<br>you don’t need in the case of <strong>https</strong></p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;network-security-config&gt;<br>    &lt;base-config cleartextTrafficPermitted=&quot;true&quot;&gt;<br>        &lt;trust-anchors&gt;<br>            &lt;certificates src=&quot;system&quot; /&gt;<br>            &lt;certificates src=&quot;user&quot; /&gt;<br>        &lt;/trust-anchors&gt;<br>    &lt;/base-config&gt;<br>&lt;/network-security-config&gt;</pre><p>and put this in res-&gt;xml</p><p>now in <strong>AndroidManifest.xml</strong></p><p>under the application tag put this in its config</p><pre>android:networkSecurityConfig=&quot;@xml/network_security_config&quot;</pre><p>and make sure you have added this permission</p><pre>&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;</pre><p><strong>Step 3:</strong> Now you need to create a suspend method to call this POST request from your composable.</p><pre>class Repo {<br><br>    companion object{<br>        suspend fun sendPhoneRequest(request: RequestBody): ApiResponse {<br>            val apiService = ApiClient.apiService<br>            return withContext(Dispatchers.IO) {<br>                apiService.sendPhoneRequest(request)<br>            }<br>        }<br>    }<br>}</pre><p><strong>Step 4: </strong>Now, the last step is to show in UI.</p><pre>class MainActivity : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            PaymentAppTheme {<br>             <br>                Surface(<br>                    modifier = Modifier.fillMaxSize(),<br>                    color = MaterialTheme.colors.background<br>                ) {<br>                    MainView()<br>                }<br>            }<br>        }<br>    }<br>}<br><br>@Composable<br>fun MainView() {<br>    var paylink by remember { mutableStateOf(&quot;&quot;) }<br><br>    val coroutineScope = rememberCoroutineScope()<br>    <br>    if(paylink.isNotEmpty()){<br>        WebViewScreen(url = paylink)<br>    }<br>    else{<br>        val requestBody = RequestBody(<br>            orderParams = OrderParams(<br>                order_id = &quot;1694784153561_12344&quot;,<br>                amount = 1,<br>                language = &quot;en&quot;<br>            ),<br>            keys = Keys(<br>                working_key = &quot;working_key&quot;,<br>                access_code = &quot;access_code&quot;<br>            )<br>        )<br><br>        Column(<br>            modifier = Modifier.fillMaxSize(),<br>            verticalArrangement = Arrangement.Center, <br>            horizontalAlignment = Alignment.CenterHorizontally <br>        ) {<br>            BasicTextField(<br>                value = TextFieldValue(text = &quot;Click to Send Request&quot;),<br>                <br>                modifier = Modifier.padding(16.dp)<br>            )<br>            Button(<br>                onClick = {<br>                    coroutineScope.launch {<br>                        val result = sendPhoneRequest(requestBody)<br>                        <br>                        paylink = result.payLink<br>                    }<br>                }<br>            ) {<br>                Text(&quot;Send Request&quot;)<br>            }<br>        }<br>    }<br><br>    <br>}<br><br>@Composable<br>fun WebViewScreen(url: String) {<br>    var webView: WebView? by remember { mutableStateOf(null) }<br><br>    LaunchedEffect(url) {<br>        webView?.loadUrl(url)<br>    }<br><br>    AndroidView(<br>        modifier = Modifier.fillMaxSize(),<br>        factory = { context -&gt;<br>            WebView(context).apply {<br>                webView = this<br>                settings.javaScriptEnabled = true<br>                webViewClient = WebViewClient()<br>            }<br>        }<br>    )<br>}</pre><p>So, it is simple now with the click of the button <strong>Send Request</strong> I am fetching the payment link and once I get the string I show load the URL in Webview.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FLeuL-IYCD8o&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DLeuL-IYCD8o&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/efba0690ee4c9f5c8092846016596e75/href">https://medium.com/media/efba0690ee4c9f5c8092846016596e75/href</a></iframe><p><strong>Thank You for reading this article.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88b1955f0f22" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/ccavenue-payment-integration-in-android-using-node-js-88b1955f0f22">CCAvenue Payment Integration in Android using Node.js</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server-Driven UI Implementation from Scratch in Flutter: Part 3]]></title>
            <link>https://levelup.gitconnected.com/server-driven-ui-implementation-from-scratch-in-flutter-part-3-e931cb570662?source=rss-1e41946a95c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e931cb570662</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <dc:creator><![CDATA[Sk Ahron]]></dc:creator>
            <pubDate>Sun, 23 Jul 2023 23:07:29 GMT</pubDate>
            <atom:updated>2023-07-23T23:07:29.138Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rFmMjkBKcXB2eEJ_0ZWC-Q.png" /><figcaption>serve-dynamic-ui part-3</figcaption></figure><p><strong>In this article, we will continue server-driven ui implementation in Flutter where we will discuss state management, updating dynamic widget ui and invoking methods in dynamic widgets.</strong></p><blockquote><strong><em>Pre-requisite:</em></strong><em> Please read </em><strong><em>Part-1 </em></strong><em>and </em><strong><em>Part-2</em></strong><em> of server-driven UI otherwise you will not understand the context of this article.</em></blockquote><p><strong>I have published a package based on server-driven-ui development on pub.dev </strong><a href="https://pub.dev/packages/serve_dynamic_ui"><strong>serve_dynamic_ui</strong></a><strong>.</strong></p><p><strong>You can find the Part-3 code </strong><a href="https://github.com/Arunshaik2001/demo_server_driven_ui/tree/part-3"><strong>here</strong></a><strong>.</strong></p><h3>In this article we will continue and solve 3 major challenges :</h3><ol><li><strong>State Management in Dynamic Screens.</strong></li><li><strong>Invoking methods in dynamic widgets.</strong></li><li><strong>Updating dynamic widget ui.</strong></li></ol><p><strong>Let us start</strong></p><p>We will start with state management, You might be aware of Provider widget by provider package. we are gonna do something similar to maintain state of a screen.</p><p>I will be creating a <strong>DynamicProvider</strong> widget that will hold state cache of a screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kuM38P5QmxwaQQGDPhFzQQ.png" /></figure><p>As you can see this special widget has <strong>stateCache</strong> and <strong>controllerCache</strong> which help to store state instances and controller instances based on widget key.</p><p>Now, we just have to wrap the root widget of a screen with <strong>DynamicProvider</strong> as it extends <strong>DynamicWidget</strong>.</p><pre>@override<br>Widget build(BuildContext context) {<br>  ActionHandlersRepo.context = context;<br>  if (jsonWidget != null) {<br>    return DynamicProvider(DynamicWidget.fromJson(jsonWidget!))<br>        .build(context);<br>  }<br>  return const SizedBox.shrink();<br>}</pre><p>so, as you can see we just wrapped <strong>root widget</strong> with DynamicProvider.</p><p>Now, in the dynamic widget where you want to manage state.</p><pre>DynamicTextState get _dynamicTextState {<br>  DynamicProvider dynamicProvider =<br>      WidgetResolver.getTopAncestorOfType&lt;DynamicProvider&gt;(this)!;<br>  if (__dynamicTextState != null) {<br>    return __dynamicTextState!;<br>  } else {<br>    if (key == null) {<br>      __dynamicTextState = DynamicTextState(text);<br>    } else {<br>      __dynamicTextState = dynamicProvider.stateCache.putIfAbsent(<br>        key,<br>        () =&gt; DynamicTextState(text),<br>      ) as DynamicTextState?;<br>    }<br>  }<br>  return __dynamicTextState!;<br>}</pre><p>so, here in <strong>dy_text</strong> widget you create a getter and using WidgetResolver.<strong>getTopAncestorOfType</strong>() find the top DynamicProvider and store the state instance and next fetch it back using key passed.</p><p>This is how you can start managing state of a page.</p><p>Next, is to invoke a method in a <strong>DynamicWidget</strong>.</p><p>In <strong>abstract class DynamicWidget{}</strong> we just have to add</p><pre>FutureOr&lt;dynamic&gt; invokeMethod(<br>  String methodName, {<br>  Map&lt;String, dynamic&gt;? params,<br>});</pre><p>it takes 2 parameters <strong>methodName</strong> the name of method you want to call and next is optional <strong>params</strong> where you can pass extra data.</p><p>so, let us say if want to invoke a method named <strong>UPDATE_TEXT</strong> in dy_text and pass <strong>newText</strong> string in params.</p><p>you find the<strong> dy_text instance</strong> in the widget tree and call <strong>invokeMethod</strong>().</p><pre>class UpdateWidgetActionHandler extends ActionHandler {<br>  @override<br>  void handleAction(<br>      BuildContext? context, Uri action, Map&lt;String, dynamic&gt;? extras) {<br>    if (extras != null) {<br>      String widgetKey = extras[&#39;widgetKey&#39;];<br>      DynamicWidget widget = extras[&#39;_instance&#39;];<br>      DynamicWidget? screenWidget = WidgetResolver.getRoot(widget);<br><br>      if (screenWidget != null) {<br>        String methodName = extras[&#39;methodName&#39;];<br>        Map&lt;String, dynamic&gt; params = extras[&#39;params&#39;];<br>        DynamicWidget? updateWidget =<br>            WidgetResolver.getWidgetWithKey(screenWidget, widgetKey);<br>        updateWidget?.invokeMethod(methodName, params: params);<br>      }<br>    }<br>  }<br>}</pre><p>In the above code snippet. I have added an Action Handler where i get the widget key and now I call <strong>invokeMethod</strong> passing necessary data.</p><p>Now, in the <strong>dy_text</strong> widget’s <strong>invokeMethod</strong> when i get the method name i will perform necessary operations.</p><pre>@override<br>FutureOr invokeMethod(String methodName, {Map&lt;String, dynamic&gt;? params}) {<br>  switch (methodName) {<br>    case UPDATE_TEXT:<br>      String newText = params?[&#39;newText&#39;];<br>      _dynamicTextState.updateTitle(newText);<br>  }<br>}</pre><p>I have a created a TextState which i saved in the stateCache.</p><pre>class DynamicTextState {<br>  final ValueNotifier&lt;String?&gt; textNotifier;<br><br>  DynamicTextState(<br>    String? title,<br>  ) : textNotifier = ValueNotifier&lt;String?&gt;(title);<br><br>  void updateTitle(String? newTitle) {<br>    textNotifier.value = newTitle;<br>  }<br>}</pre><p>In this I simply have a <strong>ValueNotifier </strong>and in the build method of <strong>dy_text</strong>. I am using <strong>ValueListenableBuilder</strong></p><pre>@override<br>Widget build(BuildContext context) {<br>  return ValueListenableBuilder(<br>    valueListenable: _dynamicTextState.textNotifier,<br>    builder: (BuildContext context, String? text, Widget? child) {<br>      return Text(<br>        text ?? &#39;&#39;,<br>        style: style,<br>        key: ValueKey(key),<br>      );<br>    },<br>  );<br>}</pre><p>which listens to text change in ValueNotifier which is present in TextState class. Once you call the <strong>updateTitle</strong> method we will get updated text on UI. This is how you can maintain state of a page and update dynamic widget.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FFYntJBIxzRs&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFYntJBIxzRs&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FFYntJBIxzRs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=google" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e834e1df3c71df252b127f550773fef/href">https://medium.com/media/4e834e1df3c71df252b127f550773fef/href</a></iframe><p>Thank You.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e931cb570662" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/server-driven-ui-implementation-from-scratch-in-flutter-part-3-e931cb570662">Server-Driven UI Implementation from Scratch in Flutter: Part 3</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server-Driven UI Implementation from scratch in Flutter: Part 2]]></title>
            <link>https://levelup.gitconnected.com/server-driven-ui-implementation-from-scratch-in-flutter-part-2-6ae7947a7c9b?source=rss-1e41946a95c7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ae7947a7c9b</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[Sk Ahron]]></dc:creator>
            <pubDate>Tue, 18 Jul 2023 19:27:28 GMT</pubDate>
            <atom:updated>2023-07-18T19:27:28.336Z</atom:updated>
            <content:encoded><![CDATA[<h3>Server-Driven UI Implementation from Scratch in Flutter: Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bE97x63Y2vPDk5rppg1U1Q.png" /></figure><p><strong>In this article, we will continue server-driven ui implementation in Flutter where we will discuss dynamic screen navigation and handling form inputs in dynamic screens.</strong></p><blockquote><strong>Pre-requisite:</strong> Please read the <strong>Part-1</strong> of server-driven UI otherwise you will not understand the context of this article.</blockquote><p><strong>I have published a package based on server-driven-ui development on pub.dev </strong><a href="https://pub.dev/packages/serve_dynamic_ui"><strong>serve_dynamic_ui</strong></a><strong>.</strong></p><p><strong>You can find the Part-2 code </strong><a href="https://github.com/Arunshaik2001/demo_server_driven_ui/tree/part-2"><strong>here</strong></a><strong>.</strong></p><p>So, I will just give a short summary of <strong>Part-1</strong>. we discussed how you can implement <strong>sever-driven ui</strong> in your Flutter apps from scratch. I showed you by creating a few dynamic widgets <strong>container, text, column, and row</strong>.</p><h4>In this article we will continue and solve 2 major challenges :</h4><ol><li><strong>Navigation between Dynamic Screens.</strong></li><li><strong>Handling Form Inputs from the user.</strong></li></ol><p>I will show you how you can solve both problems using a common solution and build some extra logic over it to handle requirement-specific cases.</p><p><strong>Let us start</strong></p><p>Before explaining the solution to both problems. I would like you to consider this example.</p><p><strong>Consider that you have a screen and in that screen, you have a dynamic button or maybe any other widget which is likely to be used for user interaction means click events and we have to handle different cases. it could be possible that on tap of that dynamic widget(Button), you perform a different task it could be navigating to any other dynamic screen or any static screen, or let us say on tap of that widget you need to take input provided by the user in a text field present in that screen and process and do your stuff based on the provided input.</strong></p><p><strong>So, I want to say is actions could be many. so we need a generic way to handle all these cases.</strong></p><p>Let us think of one such solution.</p><p>Now for this when you create the UI from JSON in the JSON structure where you have a widget that can perform an action. There in those widgets, you can add an <strong>actionDTO instance </strong>have a property <strong>actionString</strong> which is of type string.</p><pre>&quot;action&quot;: {<br>  &quot;actionString&quot;: &quot;/moveToScreen?screenName=secondScreen&quot;<br>}</pre><p>here you pass in a string URI having an actionString defined. here it is <strong>moveToScreen</strong> and <strong>screenName</strong> is secondScreen.<br>It could be possible you have many things to pass into that particular action. so you can add another property <strong>extras</strong> of type <strong>Map.</strong></p><pre>&quot;action&quot;: {<br>  &quot;actionString&quot;: &quot;/moveToScreen?screenName=secondScreen&quot;,<br>  &quot;extras&quot;: {<br>    &quot;url&quot;: &quot;sample1.json&quot;,<br>    &quot;urlType&quot;: &quot;local&quot;,<br>    &quot;navigationType&quot;: &quot;replace&quot;<br>  }<br>}</pre><p>Let us say if you want to make a network request and render the UI from JSON or load JSON from the asset you can pass key value in extras.</p><p>Now this way we can make multiple actions that handle a specific action.<br>Now we need a <strong>specific action handler</strong> that handles a <strong>specific action</strong>.</p><p>Now, we will create an abstract class <strong>ActionHandler</strong> which will have only one method <strong>handleAction.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528248%252C231%252C28%252C1%2529%26t%3Dblackboard%26wt%3Dnone%26l%3Dauto%26width%3D680%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D14px%26lh%3D152%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dabstract%252520class%252520ActionHandler%252520%25257B%25250A%252520%252520void%252520handleAction%2528%25250A%252520%252520%252520%252520BuildContext%25253F%252520context%25252C%25250A%252520%252520%252520%252520Uri%252520action%25252C%25250A%252520%252520%252520%252520Map%25253CString%25252C%252520dynamic%25253E%25253F%252520extras%25252C%25250A%252520%252520%2529%25253B%25250A%25257D&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528248%25252C231%25252C28%25252C1%252529%26t%3Dblackboard%26wt%3Dnone%26l%3Dauto%26width%3D680%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D14px%26lh%3D152%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dabstract%25252520class%25252520ActionHandler%25252520%2525257B%2525250A%25252520%25252520void%25252520handleAction%252528%2525250A%25252520%25252520%25252520%25252520BuildContext%2525253F%25252520context%2525252C%2525250A%25252520%25252520%25252520%25252520Uri%25252520action%2525252C%2525250A%25252520%25252520%25252520%25252520Map%2525253CString%2525252C%25252520dynamic%2525253E%2525253F%25252520extras%2525252C%2525250A%25252520%25252520%252529%2525253B%2525250A%2525257D&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cac6f6ddf04d3546099c553a07ed53a/href">https://medium.com/media/9cac6f6ddf04d3546099c553a07ed53a/href</a></iframe><p>handleAction has three parameters <strong>context</strong>,<strong> action</strong>,<strong> </strong>and <strong>extras</strong>.<br><strong>Context: </strong>I want context so that I can manipulate the widget structure. Let us say navigating between screens.<br><strong>action</strong>: It is the URI string that will come from JSON as actionString that will help us query info about the action to perform.<br><strong>extras</strong>: any data you want to pass with this action to be performed successfully is passed in this.</p><p>Now, here comes the solution to handle multiple solutions. At the beginning of the article, I said we will handle two things. <br>So let us start</p><h4><strong>Navigation between Dynamic Screens.</strong></h4><p>Now, I will create a specific handler that will handle navigation action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dOaty1S3Or9vsAEaJ5VlQ.png" /><figcaption><strong>MoveToScreenActionHandler</strong></figcaption></figure><p>I have named it <strong>MoveToScreenActionHandler</strong> which handles the navigation part. I have simply used the <strong>Navigator</strong> widget to navigate to a dynamic screen. the JSON could be fetched from <strong>Local Storage</strong> or maybe from <strong>Network</strong> you can define your own properties.</p><p>This is how you can <strong>navigate between screens in Server driven UI</strong>. It is that simple. You can navigate to <strong>static screens</strong> as well by just passing in the <strong>screen name.</strong></p><p><strong>Handling Form Inputs from user:</strong></p><p>To handle form inputs. we have to build upon the common solution we have to perform some extra steps along with the common solution.</p><p>I will create an abstract class <strong>FormWidget</strong> which will help me to <strong>getValues</strong> from a dynamic widget and <strong>validate</strong> the input values.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528248%252C231%252C28%252C1%2529%26t%3Dblackboard%26wt%3Dnone%26l%3Dauto%26width%3D680%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D14px%26lh%3D152%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dabstract%252520class%252520FormWidget%25257B%25250A%252520%252520Map%25253CString%25252Cdynamic%25253E%252520getValues%2528%2529%25253B%25250A%252520%252520bool%252520validate%2528%2529%25253B%25250A%25257D&amp;display_name=Carbon&amp;url=http%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528248%25252C231%25252C28%25252C1%252529%26t%3Dblackboard%26wt%3Dnone%26l%3Dauto%26width%3D680%26ds%3Dfalse%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DFira%2BCode%26fs%3D14px%26lh%3D152%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dabstract%25252520class%25252520FormWidget%2525257B%2525250A%25252520%25252520Map%2525253CString%2525252Cdynamic%2525253E%25252520getValues%252528%252529%2525253B%2525250A%25252520%25252520bool%25252520validate%252528%252529%2525253B%2525250A%2525257D&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cc64d2fa2f6358716f441a8875848d8/href">https://medium.com/media/1cc64d2fa2f6358716f441a8875848d8/href</a></iframe><p>Now, I will implement a dynamic widget that implements <strong>FormWidget </strong>which will take user inputs.</p><p>So, for that, I have to create a dynamic text field widget for demonstration purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJg4ntRjiAu7SXfPR2lpHw.png" /></figure><p>Here, I simply used a TextField. Now I will make TextField implement <strong>FormWidget</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cFvX2vV8sOFbQ4I765g9Zg.png" /></figure><p>Now, we will write the logic in <strong>getValues</strong> and <strong>validate</strong> methods</p><pre>@override<br>  Map&lt;String, dynamic&gt; getValues() {<br>    return {<br>      &quot;textFieldData&quot;: _controller?.text ?? &#39;&#39;<br>    };<br>  }</pre><p>whoever calls the text field getValues I will simply return a map having <strong>textFieldData</strong> as the key.</p><pre>@override<br>bool validate() {<br>  if(_controller?.text != null &amp;&amp; (_controller?.text.isNotEmpty??false)){<br>    return true;<br>  }<br>  return false;<br>}</pre><p>whoever calls text field validate I will just do simple validation. you can write your own validation code.</p><p>I have created a dynamic screen widget which will be the screen where we have child widgets. This widget will be the root of all widgets on a screen.</p><p><strong>I have implemented this with FormWidget so that I can get values from child FormWidgets and validate the data for that particular dynamic screen.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ol0_N3cmKZhhd88Nts-g1Q.png" /></figure><p>If you take a look at <strong>getValues()</strong> and <strong>validate()</strong>. I have written long code. I will explain both methods.</p><blockquote><strong>Note:</strong> i am using recursion. i am expecting you are aware of basic recursion concepts.</blockquote><pre>@override<br>  Map&lt;String, dynamic&gt; getValues() {<br>    return getValuesFromChild(child);<br>  }<br><br>  Map&lt;String, dynamic&gt; getValuesFromChild(DynamicWidget? widget) {<br>    if (widget != null) {<br>      if (widget is FormWidget) {<br>        return (widget as FormWidget).getValues();<br>      } else {<br>        if (widget.childWidgets?.isNotEmpty ?? false) {<br>          Map&lt;String, dynamic&gt; map = {};<br>          for (var child in widget.childWidgets!) {<br>            if (child != null) {<br>              var childMap = getValuesFromChild(child);<br>              childMap.forEach((key, value) {<br>                if (map.containsKey(key)) {<br>                  if (map[key] is List) {<br>                    map[key]?.add(value);<br>                  } else {<br>                    map[key] = [map[key], value];<br>                  }<br>                } else {<br>                  map[key] = value;<br>                }<br>              });<br>            }<br>          }<br>          return map;<br>        }<br>        return {};<br>      }<br>    } else {<br>      return {};<br>    }<br>  }</pre><p>So, the logic I have written in <strong>getValues()</strong> is as follows:</p><pre>if(widget implements FormWidget):<br>  return the widget&#39;s getValues() method<br>else:<br>  emptyMap= {}<br>  if(widget childWidgets list is not empty):<br>    for loop on childWidgets(childElement -&gt;<br>      map = do recursion on the childElement<br>      emptyMap.addAll(map)<br>    return emptyMap<br>  else<br>   return emptyMap</pre><p>The above snippet should give you an idea.</p><p>And</p><pre>@override<br>bool validate() {<br>  return validateFormWidgets(child);<br>}<br><br>bool validateFormWidgets(DynamicWidget? widget) {<br>  if (widget != null) {<br>    if (widget is FormWidget) {<br>      return (widget as FormWidget).validate();<br>    } else {<br>      if (widget.childWidgets?.isNotEmpty ?? false) {<br>        bool validate = true;<br>        for (var child in widget.childWidgets!) {<br>          if (child != null) {<br>            validate = validate &amp;&amp; validateFormWidgets(child);<br>          }<br>        }<br>        return validate;<br>      }<br>      return true;<br>    }<br>  } else {<br>    return true;<br>  }<br>}</pre><p>In the <strong>validate()</strong>, the logic is as follows:</p><pre>if(widget implements FormWidget):<br>  return widget validate<br>else:<br>  validate = true<br>  if(widget childWidgets list is not empty):<br>    for loop on childWidgets(childElement -&gt;<br>      validate &amp;= do recursion on the childElement<br>    return validate<br>  else<br>   return true</pre><p>Now, we will create a form action handler that will handle the user input data and process it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cgy7Nsgo0wP0dZV63BZzVg.png" /></figure><p>in extras, I will pass the instance of the widget that called the action.</p><p>If you have noticed <strong>ActionHandlersRepo</strong> class the <strong>handle</strong> method</p><pre>static void handle(ActionDTO actionDTO, DynamicWidget widget) {<br>  bool hasMatched = false;<br>  if (actionDTO.actionString != null) {<br>    Uri action = Uri.parse(actionDTO.actionString!);<br>    handlers.forEach((key, handler) {<br>      if (!hasMatched) {<br>        print(key.hasMatch(action.path));<br>        if (key.hasMatch(action.path)) {<br>          Map&lt;String, dynamic&gt; extras = {<br>            &quot;_instance&quot;: widget<br>          };<br>          if(actionDTO.extras != null) {<br>            extras.addAll(actionDTO.extras!);<br>          }<br>          handler.handleAction(context, action, extras);<br>          hasMatched = true;<br>        }<br>      }<br>    });<br>  }<br>}</pre><p>I am taking the widget as input and putting it in the extras map.</p><p>In the <strong>FormActionHandler</strong> <strong>handleAction</strong> method, you see this line.</p><pre>FormWidget? formWidget =<br>    WidgetResolver.getTopAncestorOfType&lt;FormWidget&gt;(widget);</pre><p><strong>So, basically what I am trying to do is get the top-level widget that extends FormWidget which is the root widget DynamicScreen using the passed instance of Dynamic Widget.</strong></p><pre>static T? getTopAncestorOfType&lt;T&gt;(DynamicWidget widget) {<br>  DynamicWidget? child = widget.parent;<br>  T? topAncestor;<br>  while (child != null) {<br>    if (child is T) {<br>      topAncestor = child as T?;<br>    }<br>    child = child.parent;<br>  }<br>  return topAncestor;<br>}</pre><p>then we call the <strong>getValues()</strong> and <strong>validate()</strong> method on that widget and it should work.</p><p>Handling user input took some more steps. you can have some other implementation and logic.</p><p>Now, it&#39;s time to show output. I have updated the JSONS of the part 1 article.<br><strong>please make sure you also have updated JSON.</strong></p><p>I have added buttons with actions <strong>/form</strong> and <strong>/moveToScreen</strong></p><pre>{<br>  &quot;type&quot;: &quot;dy_button&quot;,<br>  &quot;data&quot;: {<br>    &quot;key&quot;: &quot;22375672355&quot;,<br>    &quot;child&quot;: {<br>      &quot;type&quot;: &quot;dy_text&quot;,<br>      &quot;data&quot;: {<br>        &quot;key&quot;: &quot;2237567235&quot;,<br>        &quot;style&quot;: &quot;header1&quot;,<br>        &quot;text&quot;: &quot;submit inputs&quot;<br>      }<br>    },<br>    &quot;event&quot;: {<br>      &quot;actionString&quot;: &quot;/form&quot;<br>    }<br>  }<br>}</pre><pre>{<br>  &quot;type&quot;: &quot;dy_button&quot;,<br>  &quot;data&quot;: {<br>    &quot;key&quot;: &quot;22375672355&quot;,<br>    &quot;child&quot;: {<br>      &quot;type&quot;: &quot;dy_text&quot;,<br>      &quot;data&quot;: {<br>        &quot;key&quot;: &quot;2237567235&quot;,<br>        &quot;style&quot;: &quot;header1&quot;,<br>        &quot;text&quot;: &quot;go to second screen&quot;<br>      }<br>    },<br>    &quot;event&quot;: {<br>      &quot;actionString&quot;: &quot;/moveToScreen&quot;,<br>      &quot;extras&quot;: {<br>        &quot;url&quot;: &quot;assets/json/sample.json&quot;,<br>        &quot;urlType&quot;: &quot;local&quot;,<br>        &quot;navigationType&quot;: &quot;replace&quot;<br>      }<br>    }<br>  }<br>}</pre><p>Now, the last thing to do is to <strong>register</strong> action handlers for a <strong>regex</strong>.</p><pre>ActionHandlersRepo.init();</pre><h4>Now, run the app.</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSynrMwa5XsQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSynrMwa5XsQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSynrMwa5XsQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c0791cde4f438ba55c97e3ddbbcf044/href">https://medium.com/media/5c0791cde4f438ba55c97e3ddbbcf044/href</a></iframe><p><strong>for the second screen on <em>submit inputs</em> button click you will find the values map in the console.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qpb4h-pdfPukyLTd6DzcEg.png" /></figure><h4>This is how you can solve the problem of handling screen navigations and handling form input in Server Driven UI. You might have some other way of handling it.</h4><h4>I will try to cover other problems faced in building server-driven UI in the next part.</h4><h4>Thank You</h4><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🧠 AI Tools ⇒ <a href="https://www.aimind.so/">View Now</a></li></ul><p>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></p><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ae7947a7c9b" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/server-driven-ui-implementation-from-scratch-in-flutter-part-2-6ae7947a7c9b">Server-Driven UI Implementation from scratch in Flutter: Part 2</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>