manan36chauhan / Topics-For-Flutter

only informative
0 stars 0 forks source link

Notifications generated #1

Open manan36chauhan opened 1 year ago

manan36chauhan commented 1 year ago

step 1 -> Create a flutter app

step 2 -> create views folder inside -> lib folder after that -> go inside views folder and create a stateful widget like -> home_screen.dart (it must be stateful widget) -> because we need initState() method to work with PushNotification

step 3 -> Render home_screen.dart from main.dart as first screen from home: (Named Argument)

Now all setup is done to work with Pushnotification

step 4 -> add these 3 Dependencies in pubspec.yaml 1.firebase_core: ^1.12.0 2.firebase_messaging: ^11.2.6 3.flutter_local_notifications: ^9.2.0

Step 5 -> Setup firebase project at https://console.firebase.google.com/

NOTE : -> After setup firebase project you can receive simple pushnotification from firebase cloud messaging

Step 6.Add this lines to main() method

1. WidgetsFlutterBinding.ensureInitialized();
2. await Firebase.initializeApp();

Step 7. Now write some code in main.dart to start firebase background services

  1. add this method after import statement in main.dart

    Future backgroundHandler(RemoteMessage message) async { print(message.data.toString()); print(message.notification!.title); }

  2. call this method from main method after await Firebase.initializeApp();

    FirebaseMessaging.onBackgroundMessage(backgroundHandler);

Step 8. Go to the home_screen.dart and start work inside initState() Method

@override void initState() { super.initState();

// 1. This method call when app in terminated state and you get a notification
// when you click on notification app open from terminated state and you can get notification data in this method

FirebaseMessaging.instance.getInitialMessage().then(
  (message) {
    print("FirebaseMessaging.instance.getInitialMessage");
    if (message != null) {
      print("New Notification");
      // if (message.data['_id'] != null) {
      //   Navigator.of(context).push(
      //     MaterialPageRoute(
      //       builder: (context) => DemoScreen(
      //         id: message.data['_id'],
      //       ),
      //     ),
      //   );
      // }
    }
  },
);

// 2. This method only call when App in forground it mean app must be opened
FirebaseMessaging.onMessage.listen(
  (message) {
    print("FirebaseMessaging.onMessage.listen");
    if (message.notification != null) {
      print(message.notification!.title);
      print(message.notification!.body);
      print("message.data11 ${message.data}");
      // LocalNotificationService.display(message);

    }
  },
);

// 3. This method only call when App in background and not terminated(not closed)
FirebaseMessaging.onMessageOpenedApp.listen(
  (message) {
    print("FirebaseMessaging.onMessageOpenedApp.listen");
    if (message.notification != null) {
      print(message.notification!.title);
      print(message.notification!.body);
      print("message.data22 ${message.data['_id']}");
    }
  },
);

}

Step 9. after all these you send a notification when your app in background then you see some warning in console when you tap on notification like this Missing Default Notification Channel metadata in AndroidManifest. Default value will be used. (Because of this warning you are not getting notification like we get in youtube and other app) to solve this add below line in AndroidManifest.xml <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="pushnotificationapp"/>

Step 10 After donign this you get another warning (this warning will show when you send notification with channel name pushnotificationapp Notification Channel requested (pushnotificationapp) has not been created by the app. Manifest configuration, or default, value will be used so now we need to create a channel with name pushnotificationapp we do it with the help of flutter local notification

step 11 go inside lib -> create folder -> notificationservice -> create file inside notificationservice -> local_notification_service.dart go inside the local_notification_service.dart and create a class

class LocalNotificationService{

}

inside class create instance of FlutterLocalNotificationsPlugin see below

static final FlutterLocalNotificationsPlugin _notificationsPlugin = FlutterLocalNotificationsPlugin();

after this create a method initialize to initialize localnotification

static void initialize(BuildContext context) { // initializationSettings for Android const InitializationSettings initializationSettings = InitializationSettings( android: AndroidInitializationSettings("@mipmap/ic_launcher"), );

_notificationsPlugin.initialize(
  initializationSettings,
  onSelectNotification: (String? id) async {
    print("onSelectNotification");
    if (id!.isNotEmpty) {
      print("Router Value1234 $id");

      // Navigator.of(context).push(
      //   MaterialPageRoute(
      //     builder: (context) => DemoScreen(
      //       id: id,
      //     ),
      //   ),
      // );

    }
  },
);

}

after initialize we create channel in createanddisplaynotification method

static void createanddisplaynotification(RemoteMessage message) async { try { final id = DateTime.now().millisecondsSinceEpoch ~/ 1000; const NotificationDetails notificationDetails = NotificationDetails( android: AndroidNotificationDetails( "pushnotificationapp", "pushnotificationappchannel", importance: Importance.max, priority: Priority.high, ), );

  await _notificationsPlugin.show(
    id,
    message.notification!.title,
    message.notification!.body,
    notificationDetails,
    payload: message.data['_id'],
  );
} on Exception catch (e) {
  print(e);
}

}

Step 12 . call initialize method from main method LocalNotificationService.initialize();

and uncomment last line from FirebaseMessaging.onMessage method in homescreen

Manan-dynamic commented 1 year ago

home_screen.dart


import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

import '../notificationservice/local_notification_service.dart';
import 'Demo_Screen.dart';

class Homepg extends StatefulWidget {
  const Homepg({Key key}) : super(key: key);

  @override
  State<Homepg> createState() => _HomepgState();
}

class _HomepgState extends State<Homepg> {

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    FirebaseMessaging.instance.getInitialMessage().then(
          (message) {
        print("FirebaseMessaging.instance.getInitialMessage");
       // print(message.notification.title.toString());
        if (message != null) {
          print("New Notification");
          if (message.data['_id'] != null) {
            Navigator.of(context).push(
              MaterialPageRoute(
                builder: (context) => DemoScreen(
                  id: message.data['_id'],
                ),
              ),
            );
          }

        }
      },
    );

    FirebaseMessaging.onMessage.listen(
          (message) {
        print("FirebaseMessaging.onMessage.listen");
        if (message.notification != null) {
          print(message.notification.title);
          print(message.notification.body);
          print("message.data11 ${message.data}");
          LocalNotificationService.createanddisplaynotification(message);

        }
      },
    );

    FirebaseMessaging.onMessageOpenedApp.listen(
          (message) {
        print("FirebaseMessaging.onMessageOpenedApp.listen");
        if (message.notification != null) {
          print(message.notification.title);
          print(message.notification.body);
          print("message.data22 ${message.data['_id']}");
        }
      },
    );

  }

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      appBar: AppBar(
        title: Text('push notification'),
      ),
      body: Center(
        child: Container(
          child: Text('hi',style: TextStyle(fontSize: 25),),
        ),
      ),
    );
  }
}
Manan-dynamic commented 1 year ago

local_notificatio_service.dart

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

import '../view/Demo_Screen.dart';

class LocalNotificationService {
  static final FlutterLocalNotificationsPlugin _notificationsPlugin = FlutterLocalNotificationsPlugin();

  static void initialize() {
// initializationSettings for Android
    const InitializationSettings initializationSettings = InitializationSettings(
      android: AndroidInitializationSettings("@mipmap/ic_launcher"),
    );

    _notificationsPlugin.initialize(
      initializationSettings,
      onDidReceiveNotificationResponse: (String ) {
        print("onSelectNotification");

      },
    );
  }

  static void createanddisplaynotification(RemoteMessage message) async {
    try {
      final id = DateTime.now().millisecondsSinceEpoch ~/ 1000;
      const NotificationDetails notificationDetails = NotificationDetails(
        android: AndroidNotificationDetails(
          "pushnotificationapp",
          "pushnotificationappchannel",
          importance: Importance.max,
          priority: Priority.high,
        ),
      );

      await _notificationsPlugin.show(
        id,
        message.notification.title,
        message.notification.body,
        notificationDetails,
        payload: message.data['_id'],
      );
    } on Exception catch (e) {
      print(e);
    }
  }
}
Manan-dynamic commented 1 year ago

main.dart


import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutterpushdemo/services/PushNotificationService.dart';
import 'package:flutterpushdemo/view/home_screen.dart';
import 'package:permission_handler/permission_handler.dart';
import 'homescreen.dart';
import 'notificationservice/local_notification_service.dart';

Future<void> backgroundHandler(RemoteMessage message) async {
  print(message.data.toString());
  print(message.notification.title);
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(backgroundHandler);
  LocalNotificationService.initialize();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home:  Homepg(),
    );
  }
}

for ios 2021 https://medium.com/@alaa07996/firebase-push-notifications-with-flutter-6848892a1c15

manan36chauhan commented 1 year ago

Listview separate onclick listtile new page navigation with data

https://github.com/manan36chauhan/rest_api_app

Manan-dynamic commented 1 year ago

flutter webview plugins depricated

https://stackoverflow.com/questions/73412640/errorcannotfindymbolsettings-setappcachepathoptions-appcachepathsymbolmetho