<?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>DEV Community: TAIO Sylvain</title>
    <description>The latest articles on DEV Community by TAIO Sylvain (@sylvaintaio).</description>
    <link>https://dev.to/sylvaintaio</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%2F1230784%2F29667c58-e369-4301-be99-94964a264c6a.jpg</url>
      <title>DEV Community: TAIO Sylvain</title>
      <link>https://dev.to/sylvaintaio</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/sylvaintaio"/>
    <language>en</language>
    <item>
      <title>Implementing Push Notifications in Flutter with Firebase</title>
      <dc:creator>TAIO Sylvain</dc:creator>
      <pubDate>Mon, 24 Mar 2025 09:47:56 +0000</pubDate>
      <link>https://dev.to/sylvaintaio/implementing-push-notifications-in-flutter-with-firebase-66o</link>
      <guid>https://dev.to/sylvaintaio/implementing-push-notifications-in-flutter-with-firebase-66o</guid>
      <description>&lt;p&gt;&lt;strong&gt;Step 1: Create a Flutter project&lt;/strong&gt;&lt;br&gt;
If you haven't installed Flutter yet, follow the instructions on the &lt;a href="https://docs.flutter.dev/get-started/install" rel="noopener noreferrer"&gt;official Flutter website&lt;/a&gt; to do so. After that, create a new Flutter project using the following command:&lt;br&gt;
&lt;code&gt;flutter create push_notification&lt;br&gt;
cd push_notification&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Set Up dependencies&lt;/strong&gt;&lt;br&gt;
Add the plugins to your &lt;strong&gt;pubspec.yaml&lt;/strong&gt; file and run &lt;code&gt;flutter pub get&lt;/code&gt; to install the dependencies as shown below.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;dependencies:&lt;br&gt;
  firebase_core: ^3.12.0&lt;br&gt;
  flutter_local_notifications: ^19.0.0&lt;br&gt;
  firebase_messaging: ^15.2.2&lt;br&gt;
  googleapis_auth: ^1.6.0&lt;br&gt;
  http: ^1.2.1&lt;br&gt;
&lt;/code&gt;&lt;br&gt;
&lt;strong&gt;Step 3: Create your Firebase project&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Create a Firebase Project&lt;/strong&gt;&lt;br&gt;
Go to the  &lt;a href="https://console.firebase.google.com" rel="noopener noreferrer"&gt;Firebase Console&lt;/a&gt;and log in with your Google account.&lt;/p&gt;

&lt;p&gt;Click on &lt;strong&gt;Create a project&lt;/strong&gt;, enter the project name, and follow the setup instructions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Add Your Flutter App to Firebase&lt;/strong&gt;&lt;br&gt;
In the Firebase console, select your project and click &lt;strong&gt;Add app&lt;/strong&gt;.&lt;br&gt;
Choose the platform: Android or iOS.&lt;br&gt;
For &lt;strong&gt;Android&lt;/strong&gt;, provide the package name (found in &lt;code&gt;android/app/build.gradle&lt;/code&gt;).&lt;br&gt;
For &lt;strong&gt;iOS&lt;/strong&gt;, provide the Bundle ID (found in &lt;code&gt;ios/Runner.xcodeproj&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Download the Configuration File&lt;/strong&gt;&lt;br&gt;
For Android, download the &lt;strong&gt;google-services.json&lt;/strong&gt; file and place it inside &lt;strong&gt;android/app/&lt;/strong&gt;.&lt;br&gt;
For &lt;strong&gt;iOS&lt;/strong&gt;, download the &lt;strong&gt;GoogleService-Info.plist&lt;/strong&gt; file and place it inside &lt;strong&gt;ios/Runner/&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Configure Firebase in the Flutter Project&lt;/strong&gt;&lt;br&gt;
Update the Android configuration:&lt;/p&gt;

&lt;p&gt;Modify &lt;strong&gt;android/build.gradle&lt;/strong&gt; and &lt;strong&gt;android/app/build.gradle&lt;/strong&gt; to include Firebase dependencies.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Initialize Firebase in Flutter&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:firebase_core/firebase_core.dart';
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 4: Create a file named&lt;/strong&gt; &lt;code&gt;notification_service.dart&lt;/code&gt;&lt;br&gt;
in your project. Then, copy and paste the following content into the file.&lt;br&gt;
&lt;/p&gt;

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


class AppNotification {
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
  AndroidNotificationChannel channel = const AndroidNotificationChannel(
    'high_app_notif_channel', // id
    'High Importance Notifications', // title
    description: 'This channel is used for important notifications', // description
    importance: Importance.max,
    showBadge: true
  );

  initializeFcmNotification() async {
    await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation&amp;lt;
        AndroidFlutterLocalNotificationsPlugin&amp;gt;()
        ?.createNotificationChannel(channel);

    const AndroidInitializationSettings initializationSettingsAndroid =
    AndroidInitializationSettings('@mipmap/ic_launcher');
    final DarwinInitializationSettings initializationSettingsIOS =
    DarwinInitializationSettings(
        requestSoundPermission: true,
        requestBadgePermission: true,
        requestAlertPermission: true,
        defaultPresentAlert: true,
        defaultPresentSound: true,
        defaultPresentBadge: true,
        );
    final InitializationSettings initializationSettings =
    InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
    );
    await flutterLocalNotificationsPlugin.initialize(
      initializationSettings,
      onDidReceiveNotificationResponse: (payload) async{

      },
    );

    await flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation&amp;lt;
        IOSFlutterLocalNotificationsPlugin&amp;gt;()
        ?.requestPermissions(
      alert: true,
      badge: true,
      sound: true,
    );

    await FirebaseMessaging.instance
        .setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );

    FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;
      if (notification != null &amp;amp;&amp;amp; android != null) {
        flutterLocalNotificationsPlugin.show(
          notification.hashCode,
          notification.title,
          notification.body,
          NotificationDetails(
            ///android platform specific
            android: AndroidNotificationDetails(channel.id, channel.name,
                channelDescription: channel.description,
                importance: Importance.max,
                priority: Priority.high,
                channelShowBadge: true,
                enableVibration: true,
                enableLights: true,
                icon: android.smallIcon
            ),
            iOS: const DarwinNotificationDetails(
                presentSound: true, presentBadge: true, presentAlert: true),
          ),
          payload: jsonEncode(message.data),
        );
      }
    },
    );

    FirebaseMessaging.onMessageOpenedApp.listen(
          (RemoteMessage message) {
        //log('Message Opened CallBack $message');
        //log('Message Opened CallBack');
      },
    );
  }


}


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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 5: Go to your Firebase project&lt;/strong&gt;&lt;br&gt;
Select the project, click on the settings icon, and navigate to &lt;strong&gt;Project settings&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%2Fatzv7jadyv1qr56hks7o.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%2Fatzv7jadyv1qr56hks7o.png" alt="Image description" width="800" height="438"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 6: Create a file named&lt;/strong&gt; &lt;code&gt;constant.dart&lt;/code&gt;&lt;br&gt;
in your project. Then, copy and paste the following content into the file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class AppConstant{
  static final fcmUrl = "https://fcm.googleapis.com/v1/projects";
  static final googleApi = "https://www.googleapis.com/auth/cloud-platform";
  static final api = '${AppConstant.fcmUrl}/students-app-4b35f/messages:send';
}


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

&lt;/div&gt;



&lt;p&gt;In the following line:&lt;br&gt;
&lt;code&gt;static final api = '${AppConstant.fcmUrl}/students-app-4b35f/messages:send';&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;students-app-4b35f&lt;/strong&gt; is the &lt;strong&gt;project ID&lt;/strong&gt;. Copy it and replace it with the correct value from your Firebase project.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 7: Navigate through the menu bar and click on Service accounts&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Then, click on &lt;strong&gt;Firebase Admin SDK&lt;/strong&gt; with the key icon. Next, click on the &lt;strong&gt;Generate a new private key&lt;/strong&gt; button. Save the file securely in a safe location.&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%2Fyvevw4p8cb4ai35ki1ow.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%2Fyvevw4p8cb4ai35ki1ow.png" alt="Image description" width="800" height="439"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Open the downloaded file and copy its content. It is in JSON format.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 8: Create a file named&lt;/strong&gt; &lt;code&gt;notification_network.dart&lt;/code&gt;&lt;br&gt;
in your project. Then, copy and paste the following content into the file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:googleapis_auth/auth_io.dart';
import 'package:http/http.dart' as http;
import 'package:push_notification/constant.dart';

class SendNotificationAccess{
  static final List&amp;lt;String&amp;gt; scopes = [
    AppConstant.googleApi
  ];
  static Future&amp;lt;String&amp;gt; getAccessToken() async {
    final serviceAccountCredentials = ServiceAccountCredentials.fromJson({
      "type": "service_account",
      "project_id": "students-app-4b35f",
      "private_key_id": "2fa48b2f70407670e0c15998be363fb0ed399f82",
      "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDVHiDLCJDkNJhc\naA6v3Be7cu3bnfZc3E8reHl0c+lxZl2ygN1dWOpdM8ErhlF8aOHdsgYrGJ3txLhU\nPwHf3WpEiHsm2+dXBoEUPDm4kQkZRy0+HYr0jD2MuMeCiC9Sua62of/gp9tQp6m2\nwpKTle4ZPRpYv5AdTqTitl8EJKGj1JP0+mw19K3o7gTMyoY65T/Aw0RGkjBUBDVm\nZSz6nZYYW4H8M93KjO8jCeCWxUYfUe1qKlkJGLaKbxEOQJ6PiD+Vp6Jk4TOkmHht\n8IKmrm7PFt5Dul2D8aT/CorpMmWopjLp2ZhQOArhzByPpMpUyPPlAsleoYXdbSkX\nD29dBJabAgMBAAECggEAB6m8KyDFOPdtLRFuycMDtXFF/ToaVC91x03fLCFI2ROB\ntfvtOcCLOMu2G+8J+gu5Z2PR1fXeI+EJcboMQrTu78TqjLSmhloNBSG/P5QzfA2z\nokKkrvNl+SvhvJ9R+EsF7bo4fab7e1R0BUbMx3LCK3Unf95ve6ZKxn4hP4BjsYTP\n7otywZn3g4H2B47EPJfEL0VJK87hM85Z+f4679m0kcVgYqbcrGUCi6iNy0fLZ0Fu\nQtT4DvoSTqbsVD6zhakpFbtgJdMCslZYAjI02/qptTB/6RrbYJmOr3LLfM6kNJiL\n3/V1rLRb9WGrucfGGh2f25huEm1oBFPCoMRulMSUwQKBgQD8At1X8a6ZTrBKS1wH\nNc3sXb5e8y/DSv5xHU3gObgrTsNDlo6mNpsZrbFXkjaKdANZkB1JNgjknhgHVRQ/\njzkenYbDj8qSDYjV90EBJJSXhFv9QSbU0IiUci+N4vaX3hl+fMbCSYJZ5GtlzAPu\nRAZuJa0GCEkxeR6oCyc4y1bfWwKBgQDYfatODjQI0XwwpRYWzJmojZuGh+eA5Tih\nwZmPxeDBJ8mn7v0Dg3dobJcBg0V+HyFwBxweqLvsImpgjy6tgWccT0IuK0YMZT9J\nwhwUzEv0v4uOpyFcHE4ldkLnxmVo85YoxjolzSEPXjZjgA6YLh8HU22y8uQ0Q716\n9b0n08QJwQKBgHScCrmn3keYDqDCEBpR/jASDIW492/hYq0Khz9q1dpMPrQmlWk5\nuTj/kyDXSh90oRwvQC3hL+pBcRLrfkwOxLpy36nb/jrowllnaI/T0mHt3/bmz8YH\nnDs8Pt7jl4EcRyWtLPc3tnZL6JoY9fSpS2RqUI6LBPs8dUACsSpphJAjAoGAY/FI\nFyXJcdS7330nAGl9+mk9RlMRVdj8VviYWt5ADwu+Na/H0Ept4qBW6hTfDQV0G1K8\n8Y52CuIsd91B8EmP/2q7o7LIiMpo+DULX7Kc0iVnWPjhFrPeg77fzj4x7MyfIr24\ndGEJhR26QB8LHcgU/P3P48/r+BDZtZ0isPM7SkECgYEAgyAR1hG0rfrd9ajbGLpx\nXGJ7fo6vQW2OG96jGXpg12N70JwKtoAYw2ZaRn7ajSXXh8JFlyw5334uOO97+65D\n6dVG2T0KNh5FsrVptNZgZuc/PJXf4mEkYWVRHzE3VFfc0y4RBgVsN8cHpH9nIe3K\nhCfESjU6fePEAo1dFIUfTco=\n-----END PRIVATE KEY-----\n",
      "client_email": "firebase-adminsdk-fbsvc@students-app-4b35f.iam.gserviceaccount.com",
      "client_id": "110426202408684217122",
      "auth_uri": "https://accounts.google.com/o/oauth2/auth",
      "token_uri": "https://oauth2.googleapis.com/token",
      "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
      "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-fbsvc%40students-app-4b35f.iam.gserviceaccount.com",
      "universe_domain": "googleapis.com"
    }
    );
    var client = http.Client();
    AuthClient authClient = await clientViaServiceAccount(serviceAccountCredentials, scopes);
    final accessTokenData = authClient.credentials.accessToken.data;
    client.close();
    return accessTokenData;
  }

  static sendNotificationWithHttp({required String token,required String title,required String body}) async {
    String accessToken = await getAccessToken();

    Map&amp;lt;String, dynamic&amp;gt; payload = {
      "message": {
        "token": token,
        "notification": {
          "body": body,
          "title": title
        }
      }
    };
    final response = await http.post(Uri.parse(AppConstant.api),
        headers: {
          'Authorization': 'Bearer $accessToken',
          'Content-Type': 'application/json',
        },
        body: jsonEncode(payload));

    if (response.statusCode == 200) {
      if (kDebugMode) {
        print('Notification send');
      }
    } else {
      if (kDebugMode) {
        print('Notification Not send');
      }
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replace this part of the code (the JSON) with the content of the JSON file you downloaded.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
      "type": "service_account",
      "project_id": "students-app-4b35f",
      "private_key_id": "2fa48b2f70407670e0c15998be363fb0ed399f82",
      "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDVHiDLCJDkNJhc\naA6v3Be7cu3bnfZc3E8reHl0c+lxZl2ygN1dWOpdM8ErhlF8aOHdsgYrGJ3txLhU\nPwHf3WpEiHsm2+dXBoEUPDm4kQkZRy0+HYr0jD2MuMeCiC9Sua62of/gp9tQp6m2\nwpKTle4ZPRpYv5AdTqTitl8EJKGj1JP0+mw19K3o7gTMyoY65T/Aw0RGkjBUBDVm\nZSz6nZYYW4H8M93KjO8jCeCWxUYfUe1qKlkJGLaKbxEOQJ6PiD+Vp6Jk4TOkmHht\n8IKmrm7PFt5Dul2D8aT/CorpMmWopjLp2ZhQOArhzByPpMpUyPPlAsleoYXdbSkX\nD29dBJabAgMBAAECggEAB6m8KyDFOPdtLRFuycMDtXFF/ToaVC91x03fLCFI2ROB\ntfvtOcCLOMu2G+8J+gu5Z2PR1fXeI+EJcboMQrTu78TqjLSmhloNBSG/P5QzfA2z\nokKkrvNl+SvhvJ9R+EsF7bo4fab7e1R0BUbMx3LCK3Unf95ve6ZKxn4hP4BjsYTP\n7otywZn3g4H2B47EPJfEL0VJK87hM85Z+f4679m0kcVgYqbcrGUCi6iNy0fLZ0Fu\nQtT4DvoSTqbsVD6zhakpFbtgJdMCslZYAjI02/qptTB/6RrbYJmOr3LLfM6kNJiL\n3/V1rLRb9WGrucfGGh2f25huEm1oBFPCoMRulMSUwQKBgQD8At1X8a6ZTrBKS1wH\nNc3sXb5e8y/DSv5xHU3gObgrTsNDlo6mNpsZrbFXkjaKdANZkB1JNgjknhgHVRQ/\njzkenYbDj8qSDYjV90EBJJSXhFv9QSbU0IiUci+N4vaX3hl+fMbCSYJZ5GtlzAPu\nRAZuJa0GCEkxeR6oCyc4y1bfWwKBgQDYfatODjQI0XwwpRYWzJmojZuGh+eA5Tih\nwZmPxeDBJ8mn7v0Dg3dobJcBg0V+HyFwBxweqLvsImpgjy6tgWccT0IuK0YMZT9J\nwhwUzEv0v4uOpyFcHE4ldkLnxmVo85YoxjolzSEPXjZjgA6YLh8HU22y8uQ0Q716\n9b0n08QJwQKBgHScCrmn3keYDqDCEBpR/jASDIW492/hYq0Khz9q1dpMPrQmlWk5\nuTj/kyDXSh90oRwvQC3hL+pBcRLrfkwOxLpy36nb/jrowllnaI/T0mHt3/bmz8YH\nnDs8Pt7jl4EcRyWtLPc3tnZL6JoY9fSpS2RqUI6LBPs8dUACsSpphJAjAoGAY/FI\nFyXJcdS7330nAGl9+mk9RlMRVdj8VviYWt5ADwu+Na/H0Ept4qBW6hTfDQV0G1K8\n8Y52CuIsd91B8EmP/2q7o7LIiMpo+DULX7Kc0iVnWPjhFrPeg77fzj4x7MyfIr24\ndGEJhR26QB8LHcgU/P3P48/r+BDZtZ0isPM7SkECgYEAgyAR1hG0rfrd9ajbGLpx\nXGJ7fo6vQW2OG96jGXpg12N70JwKtoAYw2ZaRn7ajSXXh8JFlyw5334uOO97+65D\n6dVG2T0KNh5FsrVptNZgZuc/PJXf4mEkYWVRHzE3VFfc0y4RBgVsN8cHpH9nIe3K\nhCfESjU6fePEAo1dFIUfTco=\n-----END PRIVATE KEY-----\n",
      "client_email": "firebase-adminsdk-fbsvc@students-app-4b35f.iam.gserviceaccount.com",
      "client_id": "110426202408684217122",
      "auth_uri": "https://accounts.google.com/o/oauth2/auth",
      "token_uri": "https://oauth2.googleapis.com/token",
      "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
      "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-fbsvc%40students-app-4b35f.iam.gserviceaccount.com",
      "universe_domain": "googleapis.com"
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 9: Create a file named&lt;/strong&gt; &lt;code&gt;form_screen.dart&lt;/code&gt;&lt;br&gt;
in your project. Then, copy and paste the following content into the file.&lt;br&gt;
&lt;/p&gt;

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


class FormScreen extends StatefulWidget {
  const FormScreen({super.key, required this.title});
  final String title;

  @override
  State&amp;lt;FormScreen&amp;gt; createState() =&amp;gt; _FormScreenState();
}

class _FormScreenState extends State&amp;lt;FormScreen&amp;gt; {
  TextEditingController titleCtr = TextEditingController();
  TextEditingController descriptionCtr = TextEditingController();

  void _incrementCounter() async{
    String? fcmToken = await FirebaseMessaging.instance.getToken();

    log("fcmToken fcmToken $fcmToken");

    SendNotificationAccess.sendNotificationWithHttp(
        token: fcmToken!,body: descriptionCtr.text.trim(),title: titleCtr.text.trim());

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.only(left: 15,right: 15),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: &amp;lt;Widget&amp;gt;[
              TextFormField(
                controller: titleCtr,
                decoration: InputDecoration(
                  hintText: "Title"
                ),
              ),
              SizedBox(height: 50),
              TextFormField(
                controller: descriptionCtr,
                decoration: InputDecoration(
                    hintText: "Descripton"
                ),
              )
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If everything is set up correctly, call your view in the &lt;code&gt;main.dart&lt;/code&gt; file and run the project.&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:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:push_notification/form_screen.dart';
import 'package:push_notification/notification_service.dart';

void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  final AppNotification appNotification = AppNotification();
  appNotification.initializeFcmNotification();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Push Notifications',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const FormScreen(title: 'Push Notifications'),
    );
  }
}


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

&lt;/div&gt;



</description>
      <category>flutter</category>
      <category>firebase</category>
      <category>pushnotifications</category>
      <category>push</category>
    </item>
    <item>
      <title>How to Generate Pdf in PHP CodeIgniter 4 using *dompdf*</title>
      <dc:creator>TAIO Sylvain</dc:creator>
      <pubDate>Mon, 04 Nov 2024 10:23:34 +0000</pubDate>
      <link>https://dev.to/sylvaintaio/how-to-generate-pdf-in-php-codeigniter-4-using-dompdf-p9</link>
      <guid>https://dev.to/sylvaintaio/how-to-generate-pdf-in-php-codeigniter-4-using-dompdf-p9</guid>
      <description>&lt;p&gt;Step 1: Create the Database Table&lt;br&gt;
Create a &lt;code&gt;users&lt;/code&gt; table in your MySQL database:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    surname VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    university VARCHAR(100),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INSERT INTO users (name, surname, email, university, created_at) VALUES
('John', 'Doe', 'john.doe@example.com', 'University A', NOW()),
('Jane', 'Smith', 'jane.smith@example.com', 'University B', NOW()),
('Alice', 'Johnson', 'alice.johnson@example.com', 'University C', NOW()),
('Bob', 'Brown', 'bob.brown@example.com', 'University D', NOW()),
('Charlie', 'Davis', 'charlie.davis@example.com', 'University E', NOW());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Step 2: Create the User Model&lt;br&gt;
In your CodeIgniter project, create a model named &lt;code&gt;UserModel.php&lt;/code&gt; in &lt;code&gt;app/Models/&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';

    protected $allowedFields = ['name', 'surname', 'email', 'university'];
    protected $useTimestamps = true;
    protected $createdField = 'created_at';
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Step 3: Install DOMPDF&lt;br&gt;
Run the following command in your project directory to install DOMPDF:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;composer require dompdf/dompdf
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Step 4: Create the PDF Generation Controller&lt;br&gt;
Create a controller named &lt;code&gt;PdfController.php&lt;/code&gt; in &lt;code&gt;app/Controllers/&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Controllers;
use App\Models\UserModel;
use Dompdf\Dompdf;
use Dompdf\Options;

class PdfController extends BaseController
{

    public function generateUserListPdf(){
        $userModel = new UserModel();

        // Retrieve all users from the database
        $users = $userModel-&amp;gt;findAll();
        $options = new Options();
        $options-&amp;gt;set('isRemoteEnable',true);

        $dompdf = new Dompdf($options);

        $html = view('user_list_pdf',['users' =&amp;gt; $users]);

        $dompdf-&amp;gt;loadHtml($html);

        $dompdf-&amp;gt;render();

        $filename = 'user_list_'.date('YmdHis').'pdf';

        $dompdf-&amp;gt;stream($filename,['Attachment'=&amp;gt;false]);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Step 5: Create the HTML View for the PDF&lt;br&gt;
In &lt;code&gt;app/Views/&lt;/code&gt;, create a new file named &lt;code&gt;user_list_pdf.php&lt;/code&gt; with the following content:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
    &amp;lt;style&amp;gt;
        table {
            border-collapse: collapse;
            width: 100%;
        }
        th, td {
            border: 1px solid black;
            padding: 8px;
        }
        th {
            background-color: lightgray;
        }
    &amp;lt;/style&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
    &amp;lt;h1&amp;gt;List of Users&amp;lt;/h1&amp;gt;
    &amp;lt;table&amp;gt;
        &amp;lt;tr&amp;gt;
            &amp;lt;th&amp;gt;No&amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;Name and Surname&amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;Email&amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;University&amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;Created Date&amp;lt;/th&amp;gt;
        &amp;lt;/tr&amp;gt;
        &amp;lt;?php foreach ($users as $index =&amp;gt; $user) : ?&amp;gt;
            &amp;lt;tr&amp;gt;
                &amp;lt;td&amp;gt;&amp;lt;?= $index + 1; ?&amp;gt;&amp;lt;/td&amp;gt;
                &amp;lt;td&amp;gt;&amp;lt;?= esc($user['name']); ?&amp;gt; &amp;lt;?= esc($user['surname']); ?&amp;gt;&amp;lt;/td&amp;gt;
                &amp;lt;td&amp;gt;&amp;lt;?= esc($user['email']); ?&amp;gt;&amp;lt;/td&amp;gt;
                &amp;lt;td&amp;gt;&amp;lt;?= esc($user['university']); ?&amp;gt;&amp;lt;/td&amp;gt;
                &amp;lt;td&amp;gt;&amp;lt;?= esc($user['created_at']); ?&amp;gt;&amp;lt;/td&amp;gt;
            &amp;lt;/tr&amp;gt;
        &amp;lt;?php endforeach; ?&amp;gt;
    &amp;lt;/table&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Step 6: Define the Route&lt;br&gt;
In &lt;code&gt;app/Config/Routes.php&lt;/code&gt;, add a route to access the PDF generation function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$routes-&amp;gt;get('generate-user-list-pdf', 'PdfController::generateUserListPdf');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Step 7: Test the Setup&lt;br&gt;
Visit &lt;code&gt;http://yourdomain.com/generate-user-list-pdf&lt;/code&gt; in your browser. This should:&lt;/p&gt;

&lt;p&gt;Retrieve all users from the database.&lt;br&gt;
Render the user_list_pdf view with user data.&lt;br&gt;
Generate a PDF with the user list and display it in the browser.&lt;/p&gt;

</description>
      <category>codeigniter4</category>
      <category>ci4</category>
      <category>php</category>
      <category>dompdf</category>
    </item>
    <item>
      <title>Flutter : [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException</title>
      <dc:creator>TAIO Sylvain</dc:creator>
      <pubDate>Thu, 14 Dec 2023 08:53:20 +0000</pubDate>
      <link>https://dev.to/sylvaintaio/flutter-errorflutterruntimedartvminitializercc41-unhandled-exception-platformexception-9ai</link>
      <guid>https://dev.to/sylvaintaio/flutter-errorflutterruntimedartvminitializercc41-unhandled-exception-platformexception-9ai</guid>
      <description>&lt;p&gt;&lt;strong&gt;Flutter : How to solve [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(null-error, Host platform returned null value for non-null return value., null, null)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Go to &lt;strong&gt;android/build.gradle&lt;/strong&gt; &lt;br&gt;
and replace&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;classpath 'com.google.gms:google-services:4.4.0'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;to&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;classpath 'com.google.gms:google-services:4.3.15'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;**&lt;br&gt;
Don't forget to leave a comment if you enjoyed**&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Flutter: Data synchronization from sqflite to firebase and from firebase to sqflite</title>
      <dc:creator>TAIO Sylvain</dc:creator>
      <pubDate>Thu, 14 Dec 2023 08:33:01 +0000</pubDate>
      <link>https://dev.to/sylvaintaio/flutter-data-synchronization-from-sqflite-to-firebase-and-from-firebase-to-sqflite-3ipi</link>
      <guid>https://dev.to/sylvaintaio/flutter-data-synchronization-from-sqflite-to-firebase-and-from-firebase-to-sqflite-3ipi</guid>
      <description>&lt;p&gt;&lt;strong&gt;Step 1: Create a Flutter project&lt;/strong&gt;&lt;br&gt;
If you haven't installed Flutter yet, follow the instructions on the &lt;a href="https://docs.flutter.dev/get-started/install" rel="noopener noreferrer"&gt;official Flutter website&lt;/a&gt; to do so. After that, create a new Flutter project using the following command:&lt;br&gt;
&lt;code&gt;flutter create data_synchronization&lt;br&gt;
cd data_synchronization&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Set Up dependencies&lt;/strong&gt;&lt;br&gt;
Add the plugins to your &lt;strong&gt;pubspec.yaml&lt;/strong&gt; file and run &lt;code&gt;flutter pub get&lt;/code&gt; to install the dependencies as shown below.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;dependencies:&lt;br&gt;
  path_provider: ^2.0.9&lt;br&gt;
  sqflite: ^2.0.2&lt;br&gt;
  firebase_core: ^2.8.0&lt;br&gt;
  cloud_firestore:&lt;br&gt;
  firebase_storage: ^11.0.0&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Create a Model&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.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%2Ftmqu88zf3t37wifsuxc3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Ftmqu88zf3t37wifsuxc3.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4: Create your sqflite database management file&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 'dart:io';
import 'package:data_synchronization/person.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class DatabaseHelper {
  static const _databaseName = 'MyDatabase.db';
  // ignore: constant_identifier_names
  static const int DB_VERSION = 1;

  //singleton class
  DatabaseHelper._();

  static final DatabaseHelper instance = DatabaseHelper._();

  Database? _database;

  Future&amp;lt;Database&amp;gt; get database async {
    if (_database != null) return _database!;
    _database = await _initDatabase();
    return _database!;
  }
  //init database
  _initDatabase() async {
    Directory dataDirectory = await getApplicationDocumentsDirectory();
    String dbPath = join(dataDirectory.path, _databaseName);
    return await openDatabase(dbPath,
        version: DB_VERSION, onCreate: _onCreateDB);
  }

  Future _onCreateDB(Database db, int version) async {
    //create tables
    await db.execute('''
          CREATE TABLE ${Person.tblTable}(
            ${Person.colId} INTEGER PRIMARY KEY AUTOINCREMENT,
            ${Person.colName} TEXT,
            ${Person.colAge} INTEGER
          )
          ''');
  }
  //Data - insert
  Future&amp;lt;int&amp;gt; insertData(Person blog) async {
    Database db = await database;
    return await db.insert(Person.tblTable, blog.toMap());
  }
  //Data - update
  Future&amp;lt;int&amp;gt; updateDatag(Person blog) async {
    final db = await database;
    var result = await db.update(Person.tblTable, blog.toMap(),
        where: "${Person.colId} = ?", whereArgs: [blog.id]);
    return result;
  }

  //Data - retrieve all
  Future&amp;lt;List&amp;lt;Person&amp;gt;&amp;gt; fetchDatas() async {
    Database db = await database;
    List blogs = await db.query(Person.tblTable);
    return blogs.isEmpty
        ? []
        : blogs.map((x) =&amp;gt; Person.fromMap(x)).toList();
  }

  // ignore: body_might_complete_normally_nullable
  Future&amp;lt;int?&amp;gt; closeDb() async {
    var dbClient = await database;
    await dbClient.close();
  }

  deleteAll() async {
    final dbClient = await database;
    dbClient.rawDelete("Delete from ${Person.tblTable}");
  }

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 5: Create a AddUser Widget&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Nous configurons ici nos bases de données sqflite et mettons en place des requêtes pour ajouter, afficher, modifier et supprimer des données sqflite.&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:data_synchronization/db_helper.dart';
import 'package:data_synchronization/person.dart';
import 'package:flutter/material.dart';

// Widget de formulaire pour saisir les données
class AddPersonForm extends StatefulWidget {
  @override
  _AddPersonFormState createState() =&amp;gt; _AddPersonFormState();
}

class _AddPersonFormState extends State&amp;lt;AddPersonForm&amp;gt; {
  bool isLoad = false;
  final DatabaseHelper _dbHelper = DatabaseHelper.instance;
  final _formKey = GlobalKey&amp;lt;FormState&amp;gt;();
  late TextEditingController _nameController;
  late TextEditingController _ageController;

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController();
    _ageController = TextEditingController();
  }

  @override
  void dispose() {
    _nameController.dispose();
    _ageController.dispose();
    super.dispose();
  }

  // Méthode pour enregistrer les données dans SQLite
  Future&amp;lt;void&amp;gt; _saveToSqflite() async {
    if (_formKey.currentState!.validate()) {
      await  _dbHelper.insertData(
          Person(
              name:_nameController.text.trim(),
              age: int.parse(_ageController.text.trim())
          )
      );
      _nameController.clear();
      _ageController.clear();
      // ignore: use_build_context_synchronously
      Navigator.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Add User"),
        centerTitle: true,
      ),
      body: Form(
        key: _formKey,
        child: Column(
          children: [
            TextFormField(
              controller: _nameController,
              decoration: const InputDecoration(labelText: 'Name'),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter a name';
                }
                return null;
              },
            ),
            TextFormField(
              controller: _ageController,
              decoration: const InputDecoration(labelText: 'Age'),
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return 'Please enter an age';
                }
                if (int.tryParse(value) == null) {
                  return 'Please enter a valid age';
                }
                return null;
              },
            ),
            ElevatedButton(
              onPressed: _saveToSqflite,
              child: const Text('Save'),
            ),
          ],
        ),
      ),
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 5: Create a HomeScreen Widget&lt;/strong&gt;&lt;br&gt;
In this view, we'll then display the data and create two functions to synchronize data from saqflite to Firebase and from Firebase to sqflite.&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:data_synchronization/db_helper.dart';
import 'package:data_synchronization/person.dart';
import 'package:data_synchronization/add_user.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';


class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State&amp;lt;HomeScreen&amp;gt; createState() =&amp;gt; _HomeScreenState();
}

class _HomeScreenState extends State&amp;lt;HomeScreen&amp;gt; {
  DatabaseHelper? _dbHelper;
  late List&amp;lt;Person&amp;gt; _blogs;
  bool _isLoading = true;
  bool _isSynch = false;

  final GlobalKey&amp;lt;RefreshIndicatorState&amp;gt; _refreshIndicatorKey = GlobalKey&amp;lt;RefreshIndicatorState&amp;gt;();

  @override
  void initState() {
    super.initState();
    _dbHelper = DatabaseHelper.instance;
    _getBloges();
  }
  Future _getBloges() async {
    List&amp;lt;Person&amp;gt; _blog = await _dbHelper!.fetchDatas();
    setState(() {
      _blogs = _blog;
      _isLoading = false;
    });
  }

  Future&amp;lt;Null&amp;gt; _refresh() async {
    List&amp;lt;Person&amp;gt; _blog = await _dbHelper!.fetchDatas();
    setState(() {
      _blogs = _blog;
    });
    return null;
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Home Page"),
        actions: [
          GestureDetector(
            onTap: () async{
              await _dbHelper!.deleteAll();
              setState(() {
                _refresh();
              });
            },
            child: const Icon(Icons.delete_outline),
          ),
          const SizedBox(width: 10),
          myPopMenu()
        ],
      ),
      body: RefreshIndicator(
        key: _refreshIndicatorKey,
        onRefresh: _refresh,
        child: (_isLoading || _isSynch)
            ?
        const Center(
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation&amp;lt;Color&amp;gt;(Colors.pink),
          )
        )
            : _blogs.isEmpty
            ?
        Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text(
                "Aucun résultat trouvé",
              ),
              GestureDetector(
                onTap: (){
                  _refresh();
                },
                child: const Padding(
                  padding: EdgeInsets.only(top: 15),
                  child: Icon(Icons.refresh,size: 40,color: Colors.black45,),
                ),
              )
            ],
          ),
        )
            :
        ListView.builder(
          shrinkWrap: true,
          itemCount: _blogs.length,
          itemBuilder: (context, index){
            return  Padding(
                padding: const EdgeInsets.only(top: 15, left: 2, right: 2),
                child: ListTile(
                  leading: CircleAvatar(
                    radius: 35,
                    backgroundColor: Colors.pink,
                    child: Center(
                      child: Text("${_blogs[index].id}",
                          style: const TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 15
                              ,color: Colors.white
                          )
                      ),
                    ),
                  ),
                  title: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('${_blogs[index].name}',
                        style: const TextStyle(fontWeight: FontWeight.bold)
                      ),
                      const SizedBox(height: 08),
                      Text('${_blogs[index].age}')
                    ],
                  ),
                )
            );
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () =&amp;gt; _navigateToAddUser(context),
        child: const Icon(Icons.add_outlined),
      )
    );
  }

  Widget myPopMenu() {
    return PopupMenuButton(
        onSelected: (value) {
          if(value==1){
            syncSqfliteToFirebase();
          }else if(value==2){
            syncFirebaseToSqflite();
          }
        },
        itemBuilder: (context) =&amp;gt; [
          const PopupMenuItem(
              value: 1,
              child: Text('Synchronisation Sqflite =&amp;gt; Firebase',maxLines: 2)),
          const PopupMenuItem(
              value: 2,
              child: Text('Synchronisation Firebase =&amp;gt; Sqflite',maxLines: 2)),
        ]);
  }

  void _navigateToAddUser(BuildContext context){
    Navigator.push(context, MaterialPageRoute(
        builder: (contex)=&amp;gt; AddPersonForm())).then((value) {
      setState(() {
        _refresh();
      });
    });
  }

  // Method to synchronize data from SQLite to Firebase
  Future&amp;lt;void&amp;gt; syncSqfliteToFirebase() async {
    setState(() {
      _isSynch = true;
    });
    // SQLite data retrieval
    List&amp;lt;Person&amp;gt; allpersonnes = await _dbHelper!.fetchDatas();
    List&amp;lt;Person&amp;gt; newData = [];

    // Retrieve existing data from Firebase
    QuerySnapshot firebaseData =
    await FirebaseFirestore.instance.collection('firebase_tab').get();

    // Check for duplicate data
    List&amp;lt;String&amp;gt; firebaseIds = firebaseData.docs.map((doc) =&amp;gt; doc.id).toList();


    for (var data in allpersonnes) {
      if (!firebaseIds.contains(data.id)) {
        newData.add(
          Person(
            id: data.id,
            name: data.name,
            age: data.age,
          ),
        );
      }
    }

    // Send new data to Firebase
    CollectionReference collection =
    FirebaseFirestore.instance.collection('firebase_tab');
    newData.forEach((person) {
      collection.doc(person.id).set(person.toJson());
    });

    setState(() {
      _isSynch = false;
    });
  }
  // Method to sync data from Firebase to SQLite
  Future&amp;lt;void&amp;gt; syncFirebaseToSqflite() async {
    setState(() {
      _isSynch = true;
    });
    // Retrieving data from Firebase
    QuerySnapshot firebaseData =
    await FirebaseFirestore.instance.collection('firebase_tab').get();
    List&amp;lt;Person&amp;gt; firebasePeople =
    firebaseData.docs.map((doc) =&amp;gt; Person.fromSnapshot(doc)).toList();

    // Recovering existing data in SQLite
    List&amp;lt;Person&amp;gt; allpersonnes = await _dbHelper!.fetchDatas();

    // Check for duplicate data
    List sqliteIds = allpersonnes.map((data) =&amp;gt; data.id).toList();
    List&amp;lt;Person&amp;gt; newData = [];

    for (var person in firebasePeople) {
      if (!sqliteIds.contains(person.id)) {
        print("oui oui ${person.name}");
        newData.add(person);
      }else{
        print("Nononon ${person.name}");
      }
    }

    //Inserting new data in SQLite
    for (var person in newData) {
      print(person.name);
      _dbHelper!.insertData(person);
    }
    setState(() {
      _refresh();
      _isSynch = false;
    });
  }
}

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Don't forget to leave a comment if you enjoyed&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>flutter</category>
      <category>sqflite</category>
      <category>firebase</category>
      <category>synchronization</category>
    </item>
  </channel>
</rss>
