<?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 Ahmed Ghaly on Medium]]></title>
        <description><![CDATA[Stories by Ahmed Ghaly on Medium]]></description>
        <link>https://medium.com/@ahmedghaly15?source=rss-7f2874dde45f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RL8eWiTqXKmpPotcvO6YKg.jpeg</url>
            <title>Stories by Ahmed Ghaly on Medium</title>
            <link>https://medium.com/@ahmedghaly15?source=rss-7f2874dde45f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 05:17:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmedghaly15/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[Firebase Messaging in Flutter: A Comprehensive Guide to Notifications]]></title>
            <link>https://ahmedghaly15.medium.com/firebase-messaging-in-flutter-a-comprehensive-guide-to-notifications-5a819294ad93?source=rss-7f2874dde45f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a819294ad93</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[firebase-messaging]]></category>
            <category><![CDATA[firebasecloudmessaging]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Ahmed Ghaly]]></dc:creator>
            <pubDate>Tue, 28 May 2024 12:49:52 GMT</pubDate>
            <atom:updated>2024-05-28T12:49:52.134Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kkVvZ6rL4HymgjnY22W3IA.jpeg" /></figure><p>Notifications play a pivotal role in contemporary mobile applications, enriching user engagement and furnishing timely updates. This guide delves into the implementation of notifications in a Flutter app utilizing Firebase Messaging. By the end of this discourse, you will be well-versed in dispatching notifications to users, managing notifications in the foreground, and orchestrating user interactions with notifications.</p><p><strong>In this article, we’ll delve into the following topics:</strong></p><ul><li>How to send notifications to users via Firebase Messaging.</li><li>Managing notifications when the app operates in the foreground.</li><li>Facilitating user interactions with notifications.</li></ul><p><strong>Setting Up Firebase and Essential Packages</strong></p><p>To commence our journey, we first establish a Firebase project and intertwine it with our Flutter application. Subsequently, we incorporate essential packages for Firebase functionality:</p><pre>firebase_core: ^2.31.1<br>firebase_messaging: ^14.9.3<br>dio: ^5.4.3+1</pre><p>Now, let’s build our simple UI</p><pre>void main() async {<br>  WidgetsFlutterBinding.ensureInitialized();<br>  await Firebase.initializeApp(<br>    options: DefaultFirebaseOptions.currentPlatform,<br>  );<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return const MaterialApp(<br>      home: HomeScreen(),<br>    );<br>  }<br>}<br><br>class HomeScreen extends StatelessWidget {<br>  const HomeScreen({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Notification&#39;),<br>      ),<br>      body: Center(<br>        child: ElevatedButton(<br>          onPressed: () {},<br>          child: const Text(&#39;Send Notification&#39;),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*edl7i7g0cpp0Lm16YjocCA.png" /></figure><h3>How to send notifications to users via Firebase Messaging</h3><p>Notifications can be dispatched to users via Firebase Messaging using either a token or topics. We focus on token-based notification transmission. We commence by retrieving the device’s FCM token and subsequently utilize it to dispatch notifications through the Firebase Cloud Messaging (FCM) endpoint.</p><p>Note: The token is the device’s FCM token, which is unique to each mobile device. It changes only when the app is uninstalled and reinstalled, but remains constant otherwise.</p><blockquote><strong>Getting the Device FCM Token</strong></blockquote><p>To get the device FCM token, we’ll use the following function:</p><pre>  Future&lt;String?&gt; getDeviceFCMToken() async {<br>    return await FirebaseMessaging.instance.getToken();<br>  }</pre><p>Now, we can use the FCM API to send a notification. The endpoint requires some headers, including the “Authorization” header, which takes a value of “key=&lt;server_key&gt;”. We need to get the server_key for our Firebase project.</p><blockquote><strong>To Get Your Firebase Project Server Key:</strong></blockquote><ol><li>Navigate to Project Settings in Firebase.</li><li>Choose the Cloud Messaging tab.</li><li>Tap on ‘Manage API in Google Cloud Console’.</li><li>Enable ‘Cloud Messaging’.</li><li>Return to the Cloud Messaging tab in your Firebase project and refresh it. Now you have your Firebase project server_key.</li></ol><blockquote><strong>Using the Endpoint</strong></blockquote><p>We can use Postman to test our endpoint. Here’s how to set it up:</p><p><strong>Request:</strong></p><ul><li>Method: POST</li><li>URL: https://fcm.googleapis.com/fcm/send</li></ul><p><strong>Headers:</strong></p><pre>{<br>  &quot;Content-Type&quot;: &quot;application/json&quot;,<br>  &quot;Authorization&quot;: &quot;key=&lt;Server_key&gt;&quot;<br>}</pre><p><strong>Body:</strong></p><pre>{<br>  &quot;to&quot;: &quot;&lt;Device FCM token&gt;&quot;,<br>  &quot;notification&quot;: {<br>    &quot;title&quot;: &quot;Check this Mobile (title)&quot;,<br>    &quot;body&quot;: &quot;Rich Notification testing (body)&quot;<br>  }<br>}</pre><p>After sending the request, the user will receive the notification when the app is in the background or has been killed. We will discuss how to handle notifications when the app is open (foreground notifications) later.</p><blockquote><strong>Implementing the Endpoint in Your Flutter App</strong></blockquote><p>Now, let’s implement this endpoint in our Flutter app.</p><pre>class NotificationService {<br>  final Dio _dio = Dio();<br><br>  NotificationService() {<br>    _dio.options.headers = {<br>      &quot;Content-Type&quot;: &quot;application/json&quot;,<br>      &quot;Authorization&quot;: &quot;key=&lt;server_key&gt;&quot;,<br>    };<br>  }<br><br>  Future&lt;void&gt; sendNotification({<br>    required String deviceToken,<br>    required String title,<br>    required String body,<br>  }) async {<br>    const String url = &#39;https://fcm.googleapis.com/fcm/send&#39;;<br><br>    final Map&lt;String, dynamic&gt; data = {<br>      &quot;to&quot;: deviceToken,<br>      &quot;notification&quot;: {<br>        &quot;title&quot;: title,<br>        &quot;body&quot;: body,<br>      },<br>    };<br><br>    try {<br>      final response = await _dio.post(url, data: data);<br>      debugPrint(&#39;Notification sent: ${response.data}&#39;);<br>    } on DioException catch (e) {<br>      debugPrint(&#39;Error sending notification: ${e.response?.data ?? e.message}&#39;);<br>    }<br>  }<br>}</pre><p>To seamlessly incorporate notification functionality, let’s enhance the button functionality within the HomeScreen :</p><pre>ElevatedButton(<br>  onPressed: () async {<br>    // Retrieving the device&#39;s FCM token<br>    final deviceToken = await _getDeviceFCMToken();<br>    <br>    // Verifying token availability<br>    if (deviceToken != null) {<br>      debugPrint(&#39;Device Token: $deviceToken&#39;);<br>      <br>      // Initializing notification service<br>      final notificationService = NotificationService();<br>      <br>      // Sending notification<br>      notificationService.sendNotification(<br>        deviceToken: deviceToken,<br>        title: &#39;Notification Title&#39;,<br>        body: &#39;Notification Body&#39;,<br>      );<br>    }<br>  },<br>  child: const Text(&#39;Send Notification&#39;),<br>)</pre><p>It’s essential to understand the behavior of notifications within the context of our Flutter app. Due to the current state of our application — whether it’s running in the foreground or has been terminated — the notification won’t be visibly displayed to the user. However, by monitoring the console output, we can confirm the successful interaction with the Firebase Cloud Messaging (FCM) endpoint.</p><h3>Managing notifications when the app operates in the foreground</h3><p>In a Flutter app, managing notifications while the application is in the foreground requires specialized handling to ensure a seamless user experience. In this section, we’ll explore how to handle foreground notifications using the onMessage stream provided by Firebase Messaging.</p><p>In our app development journey, we’ve encountered scenarios where our app needs to react to incoming notifications, even when it’s actively being used by the user. To address this requirement, we made a significant enhancement to our HomeScreen component. Let&#39;s delve into the details:</p><p><strong>Transforming HomeScreen into a StatefulWidget</strong></p><p>In our pursuit of crafting a more responsive and dynamic user interface, we took the pivotal step of converting the HomeScreen class into a StatefulWidget. This transformation empowered us to imbue our widget with the capability to manage its internal state, a crucial aspect for handling notifications effectively.</p><pre>class HomeScreen extends StatefulWidget {<br>  const HomeScreen({Key? key}) : super(key: key);<br><br>  @override<br>  _HomeScreenState createState() =&gt; _HomeScreenState();<br>}<br><br>class _HomeScreenState extends State&lt;HomeScreen&gt; {<br>  @override<br>  void initState() {<br>    super.initState();<br>    // Initialize notification handling when the widget is initialized<br>    _handleForegroundNotification();<br>  }<br><br>  void _handleForegroundNotification() {<br>    FirebaseMessaging.onMessage.listen((RemoteMessage message) {<br>      // Extract notification data from the message<br>      final RemoteNotification? notification = message.notification;<br>      if (notification != null) {<br>        // Log notification details to the debug console<br>        debugPrint(&#39;******** Received a message while in the foreground! ********&#39;);<br>        debugPrint(&#39;******** Notification Title: ${notification.title} ********&#39;);<br>        debugPrint(&#39;******** Notification Body: ${notification.body} ********&#39;);<br><br>        // Display a snack bar to inform the user about the notification<br>        ScaffoldMessenger.of(context).showSnackBar(<br>          SnackBar(<br>            content: Text(<br>              notification.body!,<br>            ),<br>          ),<br>        );<br>      }<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    // Existing code<br>  }<br>}</pre><p>The heart of our notification handling resides within the _handleForegroundNotification() method. By tapping into the onMessage stream provided by Firebase Messaging, we intercept incoming notifications while the app is actively in use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nVHAIcY_6GKPCNwiK9eFag.gif" /></figure><h3>Facilitating user interactions with notifications</h3><p>In our Flutter app, ensuring smooth interaction between users and notifications is paramount to delivering a seamless user experience. Firebase Messaging offers powerful streams that enable us to handle user interactions with notifications effectively. By leveraging the onMessageOpenedApp stream within the initState() method, we can respond promptly to user actions and enhance the overall usability of our application.</p><pre>void _handleInteractionWithNotification() {<br>  FirebaseMessaging.onMessageOpenedApp.listen((_) {<br>    // Navigate to a designated screen upon interaction with the notification<br>    Navigator.push(<br>        context, MaterialPageRoute(builder: (context) =&gt; const HomeScreen()));<br>  });<br>}<br><br>@override<br>void initState() {<br>  super.initState();<br>  <br>  // Initialize notification handling and interaction listeners<br>  _handleForegroundNotification();<br>  _handleInteractionWithNotification();<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UhEpiQTOm-IuifymuxMpTw.gif" /></figure><h3>In Conclusion</h3><p>In this comprehensive guide, we’ve embarked on a journey through the intricate landscape of notifications in Flutter applications using Firebase Messaging. We’ve learned how to seamlessly dispatch notifications, manage them when the app operates in the foreground, and facilitate user interactions with notifications. By harnessing the power of Firebase Messaging, you’re equipped to deliver a rich and engaging user experience in your Flutter applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a819294ad93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Deep Dive: Implementing Seamless Audio Recording]]></title>
            <link>https://ahmedghaly15.medium.com/flutter-deep-dive-implementing-seamless-audio-recording-4249ecbb04bb?source=rss-7f2874dde45f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4249ecbb04bb</guid>
            <category><![CDATA[flutter-audio]]></category>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Ahmed Ghaly]]></dc:creator>
            <pubDate>Fri, 15 Mar 2024 23:09:54 GMT</pubDate>
            <atom:updated>2024-03-15T23:52:59.007Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of mobile app development, the integration of audio recording features has become increasingly crucial, especially for apps focusing on messaging, note-taking, or multimedia functionalities. Flutter, with its rich ecosystem and versatility, offers a straightforward path to embed audio recording capabilities into your app. In this article, we’ll embark on a detailed journey to implement an audio recording feature in a Flutter app from scratch. We’ll leverage a few powerful packages, craft a custom UI, and ensure users can record audio smoothly with just a few taps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QhOmcFK1qLhG3KYxYrR6Jw.png" /></figure><h4><strong>Prerequisites</strong></h4><p>Before diving into the code, it’s essential to equip our Flutter app with the necessary tools. This means adding specific dependencies to our pubspec.yaml file. Here, we&#39;re focusing on three major packages:</p><ol><li>record: Enables audio recording from the microphone to a file or stream.</li><li>permission_handler: Handles cross-platform permissions, crucial for accessing the microphone.</li><li>path_provider: Finds commonly used locations on the filesystem, such as temporary and app data directories.</li></ol><p>Include these in your pubspec.yaml like so:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  record: ^5.0.4<br>  permission_handler: ^11.3.0<br>  path_provider: ^2.1.2</pre><p>Running flutter pub get will fetch these packages and make them available in your project.</p><h3>Crafting the UI Components</h3><p>A captivating user interface is key to an engaging user experience. For our audio recording feature, we’ll design two custom widgets:</p><h3>1. CustomRecordingWaveWidget</h3><p>This widget simulates a dynamic wave effect, visually indicating that recording is in progress. It’s essentially a row of animated containers whose heights change over time to mimic sound waves.</p><pre>import &#39;dart:async&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br><br>class CustomRecordingWaveWidget extends StatefulWidget {<br>  const CustomRecordingWaveWidget({super.key});<br><br>  @override<br>  State&lt;CustomRecordingWaveWidget&gt; createState() =&gt; _RecordingWaveWidgetState();<br>}<br><br>class _RecordingWaveWidgetState extends State&lt;CustomRecordingWaveWidget&gt; {<br>  final List&lt;double&gt; _heights = [0.05, 0.07, 0.1, 0.07, 0.05];<br>  Timer? _timer;<br><br>  @override<br>  void initState() {<br>    _startAnimating();<br>    super.initState();<br>  }<br><br>  @override<br>  void dispose() {<br>    _timer?.cancel();<br>    super.dispose();<br>  }<br><br>  void _startAnimating() {<br>    _timer = Timer.periodic(const Duration(milliseconds: 150), (timer) {<br>      setState(() {<br>        // This is a simple way to rotate the list, creating a wave effect.<br>        _heights.add(_heights.removeAt(0));<br>      });<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return SizedBox(<br>      height: MediaQuery.sizeOf(context).height * 0.1,<br>      child: Row(<br>        mainAxisAlignment: MainAxisAlignment.center,<br>        children: _heights.map((height) {<br>          return AnimatedContainer(<br>            duration: const Duration(milliseconds: 300),<br>            width: 20,<br>            height: MediaQuery.sizeOf(context).height * height,<br>            margin: const EdgeInsets.only(right: 10),<br>            decoration: BoxDecoration(<br>              color: Colors.blue,<br>              borderRadius: BorderRadius.circular(50),<br>            ),<br>          );<br>        }).toList(),<br>      ),<br>    );<br>  }<br>}</pre><h3>2. CustomRecordingButton</h3><p>A button that toggles between recording and not recording states. Its design changes based on the recording status to give immediate visual feedback to the user.</p><pre>import &#39;package:flutter/material.dart&#39;;<br><br>class CustomRecordingButton extends StatelessWidget {<br>  const CustomRecordingButton({<br>    super.key,<br>    required this.isRecording,<br>    required this.onPressed,<br>  });<br><br>  final bool isRecording;<br>  final VoidCallback onPressed;<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return AnimatedContainer(<br>      height: 100,<br>      width: 100,<br>      duration: const Duration(milliseconds: 300),<br>      padding: EdgeInsets.all(<br>        isRecording ? 25 : 15,<br>      ),<br>      decoration: BoxDecoration(<br>        color: Colors.white,<br>        shape: BoxShape.circle,<br>        border: Border.all(<br>          color: Colors.blue,<br>          width: isRecording ? 8 : 3,<br>        ),<br>      ),<br>      child: AnimatedContainer(<br>        duration: const Duration(milliseconds: 300),<br>        height: 70,<br>        width: 70,<br>        decoration: BoxDecoration(<br>          color: Colors.blue,<br>          shape: isRecording ? BoxShape.rectangle : BoxShape.circle,<br>        ),<br>        child: MaterialButton(<br>          onPressed: onPressed,<br>          shape: const CircleBorder(),<br>          child: const SizedBox.shrink(),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><h3>The Heart of the Operation: RecordingScreen</h3><p>The RecordingScreen widget ties our UI components to the actual recording functionality. It handles starting and stopping the recording, managing permissions, and updating the UI based on the recording state.</p><pre>import &#39;dart:math&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:path_provider/path_provider.dart&#39;;<br>import &#39;package:permission_handler/permission_handler.dart&#39;;<br>import &#39;package:record/record.dart&#39;;<br><br>class RecordingScreen extends StatefulWidget {<br>  const RecordingScreen({super.key});<br><br>  @override<br>  State&lt;RecordingScreen&gt; createState() =&gt; _RecordingScreenState();<br>}<br><br>class _RecordingScreenState extends State&lt;RecordingScreen&gt; {<br>  bool isRecording = false;<br>  late final AudioRecorder _audioRecorder;<br>  String? _audioPath;<br><br>  @override<br>  void initState() {<br>    _audioRecorder = AudioRecorder();<br>    super.initState();<br>  }<br><br>  @override<br>  void dispose() {<br>    _audioRecorder.dispose();<br>    super.dispose();<br>  }<br><br>  String _generateRandomId() {<br>    const chars = &#39;abcdefghijklmnopqrstuvwxyz0123456789&#39;;<br>    final random = Random();<br>    return List.generate(<br>      10,<br>      (index) =&gt; chars[random.nextInt(chars.length)],<br>      growable: false,<br>    ).join();<br>  }<br><br>  Future&lt;void&gt; _startRecording() async {<br>    try {<br>      debugPrint(<br>          &#39;=========&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; RECORDING!!!!!!!!!!!!!!! &lt;&lt;&lt;&lt;&lt;&lt;===========&#39;);<br><br>      String filePath = await getApplicationDocumentsDirectory()<br>          .then((value) =&gt; &#39;${value.path}/${_generateRandomId()}.wav&#39;);<br><br>      await _audioRecorder.start(<br>        const RecordConfig(<br>          // specify the codec to be `.wav`<br>          encoder: AudioEncoder.wav,<br>        ),<br>        path: filePath,<br>      );<br>    } catch (e) {<br>      debugPrint(&#39;ERROR WHILE RECORDING: $e&#39;);<br>    }<br>  }<br><br>  Future&lt;void&gt; _stopRecording() async {<br>    try {<br>      String? path = await _audioRecorder.stop();<br><br>      setState(() {<br>        _audioPath = path!;<br>      });<br>      debugPrint(&#39;=========&gt;&gt;&gt;&gt;&gt;&gt; PATH: $_audioPath &lt;&lt;&lt;&lt;&lt;&lt;===========&#39;);<br>    } catch (e) {<br>      debugPrint(&#39;ERROR WHILE STOP RECORDING: $e&#39;);<br>    }<br>  }<br><br>  void _record() async {<br>    if (isRecording == false) {<br>      final status = await Permission.microphone.request();<br><br>      if (status == PermissionStatus.granted) {<br>        setState(() {<br>          isRecording = true;<br>        });<br>        await _startRecording();<br>      } else if (status == PermissionStatus.permanentlyDenied) {<br>        debugPrint(&#39;Permission permanently denied&#39;);<br>        // TODO: handle this case<br>      }<br>    } else {<br>      await _stopRecording();<br><br>      setState(() {<br>        isRecording = false;<br>      });<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: Column(<br>        mainAxisAlignment: MainAxisAlignment.center,<br>        children: &lt;Widget&gt;[<br>          if (isRecording) const CustomRecordingWaveWidget(),<br>          const SizedBox(height: 16),<br>          CustomRecordingButton(<br>            isRecording: isRecording,<br>            onPressed: () =&gt; _record(),<br>          ),<br>        ],<br>      ),<br>    );<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DeomMgk1Dx4Ay_dYxCoFiQ.gif" /></figure><p><strong>Key Functions:</strong></p><blockquote>_startRecording(): Initiates the recording process.</blockquote><ul><li>Requests microphone permission using Permission.microphone.request().</li><li>Configures recording settings to use the WAV format.</li><li>Starts recording with _audioRecorder.start().</li><li>Generates a unique filename for the recording and saves the recording’s file path.</li></ul><blockquote>_stopRecording(): Ends the recording session.</blockquote><ul><li>Stops the recording with _audioRecorder.stop().</li><li>Updates the _audioPath state with the path of the saved recording file.</li></ul><blockquote>_record(): Main function linked to the record button.</blockquote><ul><li>Checks the current isRecording state to determine action.</li></ul><blockquote>If not already recording:</blockquote><ul><li>Requests microphone permission.</li><li>If permission is granted, starts recording and updates isRecording to true.</li></ul><blockquote>If currently recording:</blockquote><ul><li>Stops the recording.</li><li>Updates isRecording to false.</li></ul><p><strong>Additional Resources:</strong></p><ul><li>record package documentation: <a href="https://pub.dev/packages/record">https://pub.dev/packages/record</a></li><li>permission_handler package documentation: <a href="https://pub.dev/packages/permission_handler">https://pub.dev/packages/permission_handler</a></li><li>path_provider package documentation: <a href="https://pub.dev/packages/path_provider">https://pub.dev/packages/path_provider</a></li></ul><h3>In Conclusion</h3><p>Integrating audio recording into your Flutter app doesn’t have to be a daunting task. With the right packages and a bit of custom UI magic, you can implement a seamless audio recording feature that enhances your app’s functionality and user experience. Whether for capturing voice notes, enabling in-app communication, or any other audio-related feature, the approach outlined in this article lays down a solid foundation to build upon.</p><p>Remember, while this guide gets you up and running, there’s always room to expand and customize the feature to better suit your app’s needs. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4249ecbb04bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Changing Themes in a Flutter App using Cubit State Management]]></title>
            <link>https://ahmedghaly15.medium.com/changing-themes-in-a-flutter-app-using-cubit-state-management-799a4f912ce1?source=rss-7f2874dde45f------2</link>
            <guid isPermaLink="false">https://medium.com/p/799a4f912ce1</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[cubit]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Ahmed Ghaly]]></dc:creator>
            <pubDate>Wed, 21 Feb 2024 04:14:55 GMT</pubDate>
            <atom:updated>2024-02-21T04:14:55.185Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3sA4MuawDqpVeTaeZ-vMQ.png" /></figure><p>In mobile app development, creating a visually appealing user interface plays a crucial role in enhancing the user experience. One way to achieve this is by allowing users to switch between different themes, such as light and dark modes. In Flutter, a popular cross-platform framework for building mobile applications, implementing theme switching functionality can be efficiently managed using Cubit as a state management solution. In this article, we will explore how to change themes in a Flutter app using Cubit.</p><h3>Prerequisites</h3><p>Before we dive into the implementation, let’s ensure we have the necessary dependencies installed:</p><ol><li>shared_preferences: Flutter plugin for reading and writing simple key-value pairs. It’s used for persisting the selected theme. <a href="https://pub.dev/packages/shared_preferences">shared_preferences package</a></li><li>flutter_bloc: Flutter Widgets that facilitate implementing the BLoC (Business Logic Component) design pattern. It’s utilized for managing application state. <a href="https://pub.dev/packages/flutter_bloc">flutter_bloc package</a></li></ol><p>Ensure these dependencies are added to your pubspec.yaml file:</p><pre>dependencies:<br> shared_preferences: ^2.2.2<br> flutter_bloc: ^8.1.4</pre><h3>Implementation</h3><h4>Setting Up ThemesCubit</h4><p>Let’s start by creating a Cubit named ThemesCubit, which will handle the theme switching logic:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_bloc/flutter_bloc.dart&#39;;<br>import &#39;package:shared_preferences/shared_preferences.dart&#39;;<br>import &#39;package:social_app/config/themes/app_themes.dart&#39;;<br><br>class ThemesCubit extends Cubit&lt;ThemeData&gt; {<br>  ThemesCubit() : super(AppThemes.lightTheme) {<br>    _getThemeFromPrefs();<br>  }<br><br>  Future&lt;void&gt; _saveThemeToPrefs({required Brightness brightness}) async {<br>    final themeIndex = brightness == Brightness.light ? 0 : 1;<br>    final SharedPreferences sharedPreferences = await SharedPreferences.getInstance();<br>    await sharedPreferences.setInt(&#39;theme&#39;, themeIndex);<br>  }<br><br>  Future&lt;void&gt; _getThemeFromPrefs() async {<br>    final SharedPreferences sharedPreferences = await SharedPreferences.getInstance();<br>    final savedThemeIndex = sharedPreferences.getInt(&#39;theme&#39;) ?? 0;<br>    final savedTheme = savedThemeIndex == 0 ? AppThemes.lightTheme : AppThemes.darkTheme;<br>    emit(savedTheme);<br>  }<br><br>  void toggleTheme() {<br>    emit(state.brightness == Brightness.light ? AppThemes.darkTheme : AppThemes.lightTheme);<br>    _saveThemeToPrefs(brightness: state.brightness);<br>  }<br>}</pre><p>In the ThemesCubit class:</p><ul><li>We initialize the Cubit with the default light theme and retrieve the saved theme from SharedPreferences.</li><li>The _saveThemeToPrefs method saves the selected theme to SharedPreferences.</li><li>The _getThemeFromPrefs method retrieves the saved theme from SharedPreferences.</li><li>The toggleTheme method toggles between light and dark themes, emits the new theme, and saves it to SharedPreferences.</li></ul><h3>Testing the Cubit</h3><p>Now, let’s integrate ThemesCubit into our app and test it:</p><pre>class MyApp extends StatelessWidget {<br>  const MyApp({Key? key}) : super(key: key);<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return BlocProvider(<br>      create: (context) =&gt; ThemesCubit(),<br>      child: BlocBuilder&lt;ThemesCubit, ThemeData&gt;(<br>        builder: (context, themeState) {<br>          return MaterialApp(<br>            title: &#39;Themes Demo&#39;,<br>            debugShowCheckedModeBanner: false,<br>            theme: themeState, // Set the current theme<br>            home: Scaffold(<br>              appBar: AppBar(<br>                title: const Text(&#39;Themes Demo&#39;),<br>                centerTitle: true,<br>              ),<br>              body: Center(<br>                child: ElevatedButton(<br>                  onPressed: () {<br>                    context.read&lt;ThemesCubit&gt;().toggleTheme(); // Toggle theme on button press<br>                  },<br>                  child: const Text(&#39;Change Theme&#39;),<br>                ),<br>              ),<br>            ),<br>          );<br>        },<br>      ),<br>    );<br>  }<br>}</pre><p>In the MyApp widget:</p><ul><li>We wrap the root widget with BlocProvider to provide the ThemesCubit to the widget tree.</li><li>Inside BlocBuilder, we rebuild the UI whenever the theme state changes.</li><li>The toggleTheme method is called when the button is pressed, toggling between light and dark themes.</li></ul><h3>Conclusion</h3><p>In this article, we’ve demonstrated how to implement theme switching in a Flutter app using Cubit as a state management solution. By leveraging the shared_preferences package for persistence and flutter_bloc for managing state, Flutter developers can easily provide users with the flexibility to customize their app&#39;s appearance according to their preferences. This not only enhances the user experience but also adds a layer of personalization to the app, making it more engaging and user-friendly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=799a4f912ce1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>