Home

Archives

Bio

Github

Whatsapp

Flutter Push Notifikasi

3:09 PM

Push notifikasi ke detail screen yang dituju

Pasang plugin firebase_messaging dan services


import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:patent_indonesia/services/services.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:io';
Backgroud message dan kirim token ke server
import 'package:patent_indonesia/pages/tab_one.dart';
import 'package:patent_indonesia/pages/tab_two.dart';
import 'package:patent_indonesia/utils/constants.dart';
import 'package:patent_indonesia/pages/webview.dart';
import 'package:patent_indonesia/utils/colors.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:patent_indonesia/models/User.dart';
import 'package:patent_indonesia/services/services.dart';
import 'package:patent_indonesia/utils/app_shared_preferences.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:io';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State {
  int _currentIndex = 0;
  User user;
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  final List _childrenWidgets = [
    TabOne(),
    TabTwo(),
    //ChatHome(),
    //ShoppingHomePageTwo(),
    //ShoppingHomePageOne(),
  ];


  final scaffoldState = GlobalKey();
  final firebaseMessaging = FirebaseMessaging();
  final controllerTopic = TextEditingController();
  bool isSubscribed = false;
  String token = '';
  static String dataUrl ='';


  static Future onBackgroundMessage(Map message) {
    debugPrint('onBackgroundMessage: $message');
    if (message.containsKey('data')) {
      String url = '';
      if (Platform.isIOS) {
        url = message['url'];
      } else if (Platform.isAndroid) {
        var data = message['data'];
        url = data['url'];
      }
      dataUrl = url;
      debugPrint('onBackgroundMessage: name: $url');
    }
    return null;
  }

  @override
  void initState() {
    _updateToken();
    firebaseMessaging.configure(
      onMessage: (Map message) async {
        debugPrint('onMessage: $message');
        getDataFcm(message);
      },
      onBackgroundMessage: onBackgroundMessage,
      onResume: (Map message) async {
        debugPrint('onResume: $message');
        getDataFcm(message);
      },
      onLaunch: (Map message) async {
        debugPrint('onLaunch: $message');
        getDataFcm(message);
      },
    );
    firebaseMessaging.requestNotificationPermissions(
      const IosNotificationSettings(sound: true, badge: true, alert: true, provisional: true),
    );
    firebaseMessaging.onIosSettingsRegistered.listen((settings) {
      debugPrint('Settings registered: $settings');
    });
    firebaseMessaging.getToken().then((token) => setState(() {
          this.token = token;
        }));
    super.initState();
  }
 
  _updateToken() async {
      User up = await AppSharedPreferences.getUserProfile();
      user = up;
      String tokenfb;
    _firebaseMessaging.getToken().then((String token) {
      assert(token != null);
        tokenfb = token;
        
        API.updateToken(user.email.toString(), tokenfb.toString()).then((response) {
          setState(() {
            json.decode(response.body);
          });
        });
        print(tokenfb);
    });
    
  }


  void _onItemTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: white,
      appBar: AppBar(
        /*
          leading: Image.asset(
            'assets/images/icon_settings.png',
            color: Color.fromRGBO(18, 106, 175, 1),
          ),*/
          title: Image.asset('assets/images/logo-acceler.png', height: 25),
          centerTitle: true,
          actions: [
            Icon(Icons.offline_bolt),
          ],
          backgroundColor: Colors.transparent,
          elevation: 0.0,
          
      ),
      body: Center(
        child: _childrenWidgets.elementAt(_currentIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.home), title: Text("Home")),
          BottomNavigationBarItem(
              icon: Icon(Icons.bookmark), title: Text("News")),
              /*
          BottomNavigationBarItem(
              icon: Icon(Icons.chat_bubble), title: Text("Chat")),
          BottomNavigationBarItem(icon: Icon(Icons.info), title: Text("About")),*/
        ],
        currentIndex: _currentIndex,
        onTap: _onItemTapped,
        selectedItemColor: wood_smoke,
        unselectedItemColor: trout,
        showSelectedLabels: true,
        showUnselectedLabels: true,
        selectedIconTheme: IconThemeData(color: wood_smoke, opacity: 1),
        unselectedIconTheme: IconThemeData(color: trout, opacity: 0.6),
        selectedLabelStyle: TextStyle(
            color: wood_smoke, fontSize: 12, fontWeight: FontWeight.w800),
        unselectedLabelStyle:
            TextStyle(color: trout, fontSize: 12, fontWeight: FontWeight.w800),
      ),
    );
  }

  void getDataFcm(Map message) {
    String url = '';
    if (Platform.isIOS) {
      url = message['url'];
    } else if (Platform.isAndroid) {
      var data = message['data'];
      url = data['url'];
    }
    if (url.isNotEmpty) {
      setState(() {
        url = url;
         Navigator.of(context).push(MaterialPageRoute(
        builder: (BuildContext context) => MyWebView(
        selectedUrl: APIConstants.API_BASE_URL+url,
                                    )));
      });
    }
    debugPrint('getDataFcm: name: $url');
  }

}

tambahkan ke manifest.xml


/*
intent-filter>
  action android:name="FLUTTER_NOTIFICATION_CLICK">
  category android:name="android.intent.category.DEFAULT">
/intent-filter>
*/

CUrl push notifikasi ke target



    $url = "https://fcm.googleapis.com/fcm/send";
    $token = "token target";
    $serverKey = 'server key dari firebase(FCM)';
    $title = "Notification title";
    $body = "Hello I am from Your php server";
    $click_action = "FLUTTER_NOTIFICATION_CLICK";
    $sound = "default";
    $status = "done";
    $page = "";
    $urlzz = "test.php?q=DID2019022360&type=1";
    $data = array('click_action'=> $click_action, 'status'=>$status, 'page'=>$page, 'url'=>$urlzz);
    $notification = array('title' =>$title , 'body' => $body, 'sound' => 'default', 'badge' => '1');
    $arrayToSend = array('to' => $token, 'notification' => $notification, 'data'=> $data, 'priority'=>'high');
    $json = json_encode($arrayToSend);
    //echo $json;exit;
    $headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Authorization: key='. $serverKey;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
    //Send the request
    $response = curl_exec($ch);
    //Close request
    if ($response === FALSE) {
    die('FCM Send Error: ' . curl_error($ch));
    }
    curl_close($ch);
© 2014 Hendra All Right Reserved