<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Abubaker alhomidy</title>
    <description>The latest articles on Forem by Abubaker alhomidy (@coderaray5).</description>
    <link>https://forem.com/coderaray5</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2933268%2F14f1ab78-256b-4bbe-9c20-396d8cb3b1cb.jpg</url>
      <title>Forem: Abubaker alhomidy</title>
      <link>https://forem.com/coderaray5</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/coderaray5"/>
    <language>en</language>
    <item>
      <title>Stop Laravel API chaos: Standardize your responses like a pro</title>
      <dc:creator>Abubaker alhomidy</dc:creator>
      <pubDate>Mon, 08 Sep 2025 20:31:46 +0000</pubDate>
      <link>https://forem.com/coderaray5/stop-laravel-api-chaos-standardize-your-responses-like-a-pro-4oa7</link>
      <guid>https://forem.com/coderaray5/stop-laravel-api-chaos-standardize-your-responses-like-a-pro-4oa7</guid>
      <description>&lt;h2&gt;
  
  
  Have you ever struggled with inconsistent API responses across different endpoints in a Laravel project? 🤯
&lt;/h2&gt;

&lt;p&gt;One controller returns plain JSON, another uses a custom message, and yet another responds with a completely different format. The result? Chaos.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;🚩 The Problem&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In large projects with multiple developers, this inconsistency makes the code harder to maintain, debug, and extend.&lt;/p&gt;




&lt;p&gt;💡 &lt;strong&gt;The Solution&lt;/strong&gt;: A Unified API Response Structure&lt;/p&gt;

&lt;p&gt;The idea is simple: define one standard structure for all API responses.&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
{
  "status": "success",
  "code": 200,
  "message": "Users fetched successfully",
  "data": [],
  "errors": [],
  "meta": []
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;🛠️ How to Implement It&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Create a helper class ApiResponse to return standardized responses.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Define all status codes in one place (no more magic numbers in your code).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use these consistently across your controllers and services.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;✅ &lt;strong&gt;Benefits&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Clear and predictable responses.&lt;/p&gt;

&lt;p&gt;Less repetitive code.&lt;/p&gt;

&lt;p&gt;Easier debugging and maintenance.&lt;/p&gt;

&lt;p&gt;A more professional API structure overall.&lt;/p&gt;




&lt;p&gt;📌 &lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;By unifying your Laravel API responses, you transform them from chaos to clarity.&lt;br&gt;
New developers on your team will onboard faster, debugging will be simpler, and your API will look far more professional.&lt;/p&gt;




&lt;p&gt;👉 Full article on Medium:&lt;br&gt;
&lt;a href="https://medium.com/@abobakralhomidy/standardizing-api-responses-in-laravel-from-chaos-to-clarity-14878854fd30" rel="noopener noreferrer"&gt;Stop Laravel API chaos: Standardize your responses like a pro&lt;/a&gt;&lt;/p&gt;

</description>
      <category>api</category>
      <category>laravel</category>
      <category>development</category>
      <category>backend</category>
    </item>
    <item>
      <title>🚀 Secure Your Flutter Apps Like a Pro! 🔐</title>
      <dc:creator>Abubaker alhomidy</dc:creator>
      <pubDate>Wed, 27 Aug 2025 19:05:51 +0000</pubDate>
      <link>https://forem.com/coderaray5/secure-your-flutter-apps-like-a-pro-4jo2</link>
      <guid>https://forem.com/coderaray5/secure-your-flutter-apps-like-a-pro-4jo2</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzll4ekcet30er256p503.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzll4ekcet30er256p503.png" alt=" " width="800" height="1200"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hardcoding API keys and secrets in your Flutter project is a huge security risk — and unfortunately,__ many developers still do it. 😱&lt;/p&gt;

&lt;p&gt;In my latest article, I dive into how you can protect your environment variables in Flutter using the powerful Envied package. You'll learn:&lt;br&gt;
✅ Why storing secrets safely matters&lt;br&gt;
✅ How to manage multiple environments (dev, staging, prod)&lt;br&gt;
✅ Step-by-step setup of Envied with code examples&lt;/p&gt;

&lt;p&gt;If you’re building serious Flutter apps, this is a must-read!&lt;br&gt;
👉 Check out the full article here: &lt;a href="https://medium.com/@abobakralhomidy/secure-environment-variables-in-flutter-with-envied-5aa2fa60d2df" rel="noopener noreferrer"&gt;Secure Environment Variables in Flutter with Envied&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let’s build safer and more scalable apps together! 💙&lt;/p&gt;

</description>
      <category>security</category>
      <category>mobile</category>
      <category>development</category>
      <category>flutter</category>
    </item>
    <item>
      <title>Reusable components in Flutter</title>
      <dc:creator>Abubaker alhomidy</dc:creator>
      <pubDate>Wed, 12 Mar 2025 21:14:52 +0000</pubDate>
      <link>https://forem.com/coderaray5/reusable-components-in-flutter-41gd</link>
      <guid>https://forem.com/coderaray5/reusable-components-in-flutter-41gd</guid>
      <description>&lt;div class="ltag__link"&gt;
  &lt;a href="/coderaray5" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__pic"&gt;
      &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2933268%2F14f1ab78-256b-4bbe-9c20-396d8cb3b1cb.jpg" alt="coderaray5"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;a href="https://dev.to/coderaray5/reusable-components-in-flutter-write-once-use-everywhere-9oa" class="ltag__link__link"&gt;
    &lt;div class="ltag__link__content"&gt;
      &lt;h2&gt;Reusable Components in Flutter: Write Once, Use Everywhere! 🚀&lt;/h2&gt;
      &lt;h3&gt;Abubaker alhomidy ・ Mar 12&lt;/h3&gt;
      &lt;div class="ltag__link__taglist"&gt;
        &lt;span class="ltag__link__tag"&gt;#flutter&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#ui&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#ux&lt;/span&gt;
        &lt;span class="ltag__link__tag"&gt;#reusablecomponent&lt;/span&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/a&gt;
&lt;/div&gt;


</description>
      <category>flutter</category>
      <category>ui</category>
      <category>ux</category>
      <category>reusablecomponent</category>
    </item>
    <item>
      <title>Reusable Components in Flutter: Write Once, Use Everywhere! 🚀</title>
      <dc:creator>Abubaker alhomidy</dc:creator>
      <pubDate>Wed, 12 Mar 2025 00:37:36 +0000</pubDate>
      <link>https://forem.com/coderaray5/reusable-components-in-flutter-write-once-use-everywhere-9oa</link>
      <guid>https://forem.com/coderaray5/reusable-components-in-flutter-write-once-use-everywhere-9oa</guid>
      <description>&lt;p&gt;Have you ever found yourself writing the same UI code repeatedly in Flutter? If so, it's time to embrace Reusable Components—one of the best ways to write &lt;strong&gt;clean&lt;/strong&gt;, &lt;strong&gt;maintainable&lt;/strong&gt;, and &lt;strong&gt;scalable&lt;/strong&gt; code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Use Reusable Components?
&lt;/h2&gt;

&lt;p&gt;In Flutter, &lt;strong&gt;Widgets&lt;/strong&gt; are the foundation of everything, and they can be designed to be &lt;strong&gt;reusable&lt;/strong&gt;. Instead of duplicating code, you can create &lt;strong&gt;custom widgets&lt;/strong&gt; and &lt;strong&gt;service classes&lt;/strong&gt;that can be used across different parts of your app.&lt;/p&gt;

&lt;h2&gt;
  
  
  Benefits of Reusable Components
&lt;/h2&gt;

&lt;p&gt;✅ &lt;strong&gt;Less Code Duplication&lt;/strong&gt; – Define once, use anywhere.&lt;br&gt;
✅ &lt;strong&gt;Easier Maintenance&lt;/strong&gt;– Fix or update in one place, and it's reflected everywhere.&lt;br&gt;
✅ &lt;strong&gt;Better Scalability&lt;/strong&gt; – Your app grows without turning into a mess of repeated code.&lt;/p&gt;
&lt;h2&gt;
  
  
  Beyond UI: Where Else Can You Apply This?
&lt;/h2&gt;

&lt;p&gt;✔️ &lt;strong&gt;API Services&lt;/strong&gt; – Centralizing API calls for better management.&lt;br&gt;
✔️&lt;strong&gt;State Management&lt;/strong&gt; – Using solutions like &lt;strong&gt;Provider&lt;/strong&gt; or &lt;strong&gt;Bloc&lt;/strong&gt; to avoid unnecessary logic repetition.&lt;br&gt;
✔️ &lt;strong&gt;Form Inputs &amp;amp; Custom Buttons&lt;/strong&gt; – Standardizing UI components for consistency.&lt;/p&gt;
&lt;h2&gt;
  
  
  Example 1: A Reusable API Client (Centralized API Calls) 🌐
&lt;/h2&gt;

&lt;p&gt;Instead of writing*&lt;em&gt;API calls multiple times&lt;/em&gt;* in different parts of your app, you can create a &lt;strong&gt;generic API client&lt;/strong&gt; to handle all requests in a structured way.&lt;br&gt;
*&lt;em&gt;📌 Step 1: Create a Reusable API Client&lt;br&gt;
*&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'package:dio/dio.dart';

class ApiClient {
  final Dio _dio = Dio(BaseOptions(baseUrl: "https://jsonplaceholder.typicode.com"));

  Future&amp;lt;T&amp;gt; get&amp;lt;T&amp;gt;(String endpoint) async {
    final response = await _dio.get(endpoint);
    return response.data as T;
  }

  Future&amp;lt;T&amp;gt; post&amp;lt;T&amp;gt;(String endpoint, dynamic data) async {
    final response = await _dio.post(endpoint, data: data);
    return response.data as T;
  }

  Future&amp;lt;T&amp;gt; put&amp;lt;T&amp;gt;(String endpoint, dynamic data) async {
    final response = await _dio.put(endpoint, data: data);
    return response.data as T;
  }

  Future&amp;lt;T&amp;gt; delete&amp;lt;T&amp;gt;(String endpoint) async {
    final response = await _dio.delete(endpoint);
    return response.data as T;
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;📌 Step 2: Use the API Client in Your App&lt;/strong&gt;&lt;br&gt;
Instead of manually writing API calls everywhere, you now call the methods with a &lt;strong&gt;single line:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void fetchUsers() async {
  List&amp;lt;dynamic&amp;gt; users = await ApiClient().get&amp;lt;List&amp;lt;dynamic&amp;gt;&amp;gt;("/users");
  print(users);
}

void createUser() async {
  Map&amp;lt;String, dynamic&amp;gt; user = await ApiClient().post&amp;lt;Map&amp;lt;String, dynamic&amp;gt;&amp;gt;(
    "/users",
    {"name": "Coder Coder", "email": "coder@example.com"},
  );
  print(user);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;🚀 Benefits of This Approach&lt;br&gt;
**&lt;br&gt;
✅ **Reusability&lt;/strong&gt; – One class handles all API requests.&lt;br&gt;
✅ &lt;strong&gt;Flexibility&lt;/strong&gt; – Supports multiple request types &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;(&lt;em&gt;GET&lt;/em&gt;, &lt;em&gt;POST&lt;/em&gt;, &lt;em&gt;PUT&lt;/em&gt;, &lt;em&gt;DELETE&lt;/em&gt;).&lt;br&gt;
✅ &lt;strong&gt;Maintainability&lt;/strong&gt;– If you need to modify API logic (e.g., add headers, interceptors), update one file instead of multiple places.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Example 2: A Reusable Button Widget 🖱️&lt;/strong&gt;&lt;br&gt;
Instead of styling and defining buttons &lt;strong&gt;repeatedly&lt;/strong&gt;, create a &lt;strong&gt;custom widget&lt;/strong&gt; that can be reused anywhere in your app.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;📌 Step 1: Create a Reusable Button Component&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'package:flutter/material.dart';

class CustomButton extends StatelessWidget {
  final String text;
  final VoidCallback onPressed;
  final Color color;

  const CustomButton({
    Key? key,
    required this.text,
    required this.onPressed,
    this.color = Colors.blue,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(backgroundColor: color),
      onPressed: onPressed,
      child: Text(text, style: const TextStyle(color: Colors.white)),
    );
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;📌 Step 2: Use the Reusable Button in Your UI&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CustomButton(
  text: "Click Me",
  onPressed: () {
    print("Button Clicked!");
  },
),
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;You can customize the component as you want add any property the previous code is just a *&lt;em&gt;simple code *&lt;/em&gt; .&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;🚀 Benefits of This Approach&lt;/strong&gt;&lt;br&gt;
✅ &lt;strong&gt;Consistency&lt;/strong&gt;– Ensures buttons look the same across the app.&lt;br&gt;
✅ &lt;strong&gt;Ease of Maintenance&lt;/strong&gt; – Update button styles in one place.&lt;br&gt;
✅ &lt;strong&gt;Less Repeated Code&lt;/strong&gt; – Just pass text, color, and function when needed.&lt;/p&gt;
&lt;h2&gt;
  
  
  Final Thoughts 💡
&lt;/h2&gt;

&lt;p&gt;By making your &lt;strong&gt;UI components&lt;/strong&gt; and &lt;strong&gt;API services&lt;/strong&gt; &lt;em&gt;&lt;strong&gt;reusable&lt;/strong&gt;&lt;/em&gt;, you:&lt;br&gt;
✅ &lt;strong&gt;Write less code while maintaining better structure.&lt;/strong&gt;&lt;br&gt;
✅ &lt;strong&gt;Ensure consistency across your app.&lt;/strong&gt;&lt;br&gt;
✅ &lt;strong&gt;Make future updates easier, as changes happen in one place.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I will show some photos of &lt;strong&gt;UI **with **reusable component&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fv4rdwc0ejcb566ca035s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fv4rdwc0ejcb566ca035s.png" alt="A list of users using the Mock API and use a **reusable component** like **buttons**and **cards**" width="616" height="873"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkkope7eb30vebqxchwq6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fkkope7eb30vebqxchwq6.png" alt="A list of users using the Mock API and use a **reusable component** like **buttons** and **cards**" width="618" height="872"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here is the codes usage in the photos example&lt;br&gt;
&lt;strong&gt;&lt;em&gt;Custom Button Code&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'package:flutter/material.dart';

class CustomButton extends StatelessWidget {
  final String text;
  final VoidCallback onPressed;
  final Color color;
  final double borderRadius;
  final EdgeInsetsGeometry padding;
  final TextStyle? textStyle;

  const CustomButton({
    Key? key,
    required this.text,
    required this.onPressed,
    this.color = Colors.blue,
    this.borderRadius = 8.0,
    this.padding = const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
    this.textStyle,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        backgroundColor: color,
        padding: padding,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(borderRadius),
        ),
      ),
      onPressed: onPressed,
      child: Text(
        text,
        style: textStyle ?? const TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
      ),
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;_Custom User Card Code&lt;br&gt;
_&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'package:flutter/material.dart';

class UserCard extends StatelessWidget {
  final Map&amp;lt;String, dynamic&amp;gt; user;
  final VoidCallback? onTap;
  final Color cardColor;
  final double elevation;
  final double borderRadius;

  const UserCard({
    Key? key,
    required this.user,
    this.onTap,
    this.cardColor = Colors.white,
    this.elevation = 2.0,
    this.borderRadius = 8.0,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: elevation,
      color: cardColor,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(borderRadius),
      ),
      margin: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(borderRadius),
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  CircleAvatar(
                    backgroundColor: Colors.blue.shade100,
                    child: Text(
                      user['name'][0].toUpperCase(),
                      style: const TextStyle(color: Colors.blue, fontWeight: FontWeight.bold),
                    ),
                  ),
                  const SizedBox(width: 16.0),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          user['name'],
                          style: const TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
                        ),
                        const SizedBox(height: 4.0),
                        Text(
                          user['email'],
                          style: TextStyle(fontSize: 14.0, color: Colors.grey.shade700),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              if (user['company'] != null) ...[  
                const SizedBox(height: 12.0),
                Text(
                  'Company: ${user['company']['name']}',
                  style: TextStyle(fontSize: 14.0, color: Colors.grey.shade800),
                ),
              ],
              if (user['phone'] != null) ...[  
                const SizedBox(height: 8.0),
                Text(
                  'Phone: ${user['phone']}',
                  style: TextStyle(fontSize: 14.0, color: Colors.grey.shade800),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;&lt;em&gt;Custom API Client Class Code&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'package:dio/dio.dart';

class ApiClient {
  final Dio _dio = Dio(BaseOptions(baseUrl: "https://jsonplaceholder.typicode.com"));

  Future&amp;lt;T&amp;gt; get&amp;lt;T&amp;gt;(String endpoint) async {
    try {
      final response = await _dio.get(endpoint);
      return response.data as T;
    } catch (e) {
      throw Exception("Failed to load data");
    }
  }

  Future&amp;lt;T&amp;gt; post&amp;lt;T&amp;gt;(String endpoint, dynamic data) async {
    try {
      final response = await _dio.post(endpoint, data: data);
      return response.data as T;
    } catch (e) {
      throw Exception("Failed to create data");
    }
  }

  Future&amp;lt;T&amp;gt; put&amp;lt;T&amp;gt;(String endpoint, dynamic data) async {
    try {
      final response = await _dio.put(endpoint, data: data);
      return response.data as T;
    } catch (e) {
      throw Exception("Failed to update data");
    }
  }

  Future&amp;lt;T&amp;gt; delete&amp;lt;T&amp;gt;(String endpoint) async {
    try {
      final response = await _dio.delete(endpoint);
      return response.data as T;
    } catch (e) {
      throw Exception("Failed to delete data");
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;_Code of UI _&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'package:flutter/material.dart';
import 'package:test_sentry/api_client.dart';
import 'package:test_sentry/widgets/user_card.dart';
import 'package:test_sentry/widgets/custom_button.dart';

class UserListScreen extends StatefulWidget {
  @override
  _UserListScreenState createState() =&amp;gt; _UserListScreenState();
}

class _UserListScreenState extends State&amp;lt;UserListScreen&amp;gt; {
  late Future&amp;lt;List&amp;lt;dynamic&amp;gt;&amp;gt; _users;
  bool _isGridView = false;

  @override
  void initState() {
    super.initState();
    _users = ApiClient().get&amp;lt;List&amp;lt;dynamic&amp;gt;&amp;gt;("/users");
  }

  void _refreshUsers() {
    setState(() {
      _users = ApiClient().get&amp;lt;List&amp;lt;dynamic&amp;gt;&amp;gt;("/users");
    });
  }

  void _toggleViewMode() {
    setState(() {
      _isGridView = !_isGridView;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Users List'),
        actions: [
          IconButton(
            icon: Icon(_isGridView ? Icons.list : Icons.grid_view),
            onPressed: _toggleViewMode,
          ),
        ],
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                CustomButton(
                  text: 'Refresh Data',
                  onPressed: _refreshUsers,
                  color: Colors.green,
                ),
                CustomButton(
                  text: 'Create User',
                  onPressed: () {
                    // Demonstrate API client post method
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('Creating user...')),
                    );

                    ApiClient().post&amp;lt;Map&amp;lt;String, dynamic&amp;gt;&amp;gt;(
                      "/users",
                      {"name": "New User", "email": "newuser@example.com"},
                    ).then((response) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(content: Text('User created with ID: ${response["id"]}')),
                      );
                    }).catchError((error) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(content: Text('Error: $error')),
                      );
                    });
                  },
                  color: Colors.blue,
                ),
              ],
            ),
          ),
          Expanded(
            child: FutureBuilder&amp;lt;List&amp;lt;dynamic&amp;gt;&amp;gt;(
              future: _users,
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Center(child: CircularProgressIndicator());
                } else if (snapshot.hasError) {
                  return Center(child: Text('Error: ${snapshot.error}'));
                } else if (!snapshot.hasData || snapshot.data!.isEmpty) {
                  return Center(child: Text('No data available.'));
                } else {
                  var users = snapshot.data!;

                  if (_isGridView) {
                    return GridView.builder(
                      padding: const EdgeInsets.all(8.0),
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 2,
                        childAspectRatio: 0.8,
                        crossAxisSpacing: 10,
                        mainAxisSpacing: 10,
                      ),
                      itemCount: users.length,
                      itemBuilder: (context, index) {
                        return UserCard(
                          user: users[index],
                          onTap: () {
                            ScaffoldMessenger.of(context).showSnackBar(
                              SnackBar(content: Text('Selected: ${users[index]["name"]}')),
                            );
                          },
                        );
                      },
                    );
                  } else {
                    return ListView.builder(
                      itemCount: users.length,
                      itemBuilder: (context, index) {
                        return UserCard(
                          user: users[index],
                          onTap: () {
                            ScaffoldMessenger.of(context).showSnackBar(
                              SnackBar(content: Text('Selected: ${users[index]["name"]}')),
                            );
                          },
                        );
                      },
                    );
                  }
                }
              },
            ),
          ),
        ],
      ),
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;💬** How do you manage reusability in your Flutter projects? Let’s discuss in the comments! 🚀**&lt;br&gt;
Want more Flutter tips?&lt;br&gt;
🔹 Join my Telegram channel for more Flutter guides: &lt;a href="https://t.me/coderaray5" rel="noopener noreferrer"&gt;Telegram Link&lt;/a&gt; &lt;br&gt;
🔹 Follow my Facebook page for daily coding insights: &lt;a href="https://www.facebook.com/profile.php?id=61565984498069" rel="noopener noreferrer"&gt;Facebook Link&lt;/a&gt; &lt;/p&gt;

</description>
      <category>flutter</category>
      <category>ui</category>
      <category>ux</category>
      <category>reusablecomponent</category>
    </item>
  </channel>
</rss>
