[Flutter]Push Notification

by doanquyet
781 views

0. Thêm dependency

Thêm flutter_local_notifications: ^9.1.2 vào pubspec.yaml.

Đừng quên sử dụng Pub get để tải về.

1. Thiết lập hình ảnh biểu tượng của bạn

Thêm hình ảnh vào đường dẫn này:

icon path: PROJECT_NAME\android\app\src\main\res\drawable\icon.png

2. Tạo một class NotificationService

Bạn sẽ nhập lớp này vào main.dart.(Chúng tôi sẽ thực hiện việc này ở bước sau 3.) Mã của lớp này ở cuối bài viết này.

3. Thực hiện một số thao tác khởi tạo

trong main()

4. Chức năng hiển thị cuộc gọi trực tiếp ở bất cứ đâu khi bạn muốn

showNotification()là một hàm của lớp NotificationService mà chúng ta vừa tạo trong tệp notification_service.dart.

Ví dụ: tôi muốn thông báo đẩy khi tôi nhấp vào một nút, sau đó tôi có thể gọi chức năng này trong _onPressed()nút. Mã ở dưới đây, hãy kiểm tra nó.

main.dart

import 'package:flutter/material.dart';
import 'service/notification_service.dart';

Future<void> main() async{
  // Step 3. Initialization
  WidgetsFlutterBinding.ensureInitialized();
  NotificationService notificationService = NotificationService();
  await notificationService.init();

  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MyHomePage(),
    );
  }
}

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  /// Step 4. For pusing notification.
  NotificationService notificationService = NotificationService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("My Main Page"),
      ),
      body: const Text('hello world'),
      floatingActionButton: FloatingActionButton(
        onPressed: () async{
          /// When I click the button, the notification will be pushed.
          /// Step 4. just call this function anywhere you want.
          await notificationService.showNotification(0, 'This is title...', "Tis is body...",);
        },
        child: const Icon(Icons.radio_button_on),
      ),
    );
  }
}

notification_service.dart

import 'package:flutter_local_notifications/flutter_local_notifications.dart';
/// Step 2. Create a NotificationService class
class NotificationService {
  // Singleton pattern, https://en.wikipedia.org/wiki/Singleton_pattern
  // 1.The _internal() construction is just a name often given to constructors
  // that are private to the class
  // 2.Use the factory keyword when implementing a constructor
  // that does not create a new instance of its class.
  NotificationService._internal();
  static final NotificationService _notificationService = NotificationService._internal();
  factory NotificationService() {
    return _notificationService;
  }

  // Configuration for platform-specific initialization settings.
  Future<void> init() async {
    // Specifies the default icon for notifications.
    // icon path: PROJECT_NAME\android\app\src\main\res\drawable\icon.png
    const AndroidInitializationSettings androidInitializationSettings =
      AndroidInitializationSettings("icon");
    const InitializationSettings initializationSettings =
      InitializationSettings(android: androidInitializationSettings);
    await flutterLocalNotificationsPlugin.initialize(initializationSettings);
  }

  // Some configurations for platform-specific notification's details.
  static const AndroidNotificationDetails _androidNotificationDetails =
    AndroidNotificationDetails(
      'ChannelId',
      'ChannelName',
      channelDescription: "Responsible for all local notifications",
      playSound: true,
      priority: Priority.high,
      importance: Importance.high,
    );
  final NotificationDetails notificationDetails =
    const NotificationDetails(android: _androidNotificationDetails);

  // Now we need to call the show() method of FlutterLocalNotificationsPlugin.
  // Show() is responsible for showing the local notification.
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
  FlutterLocalNotificationsPlugin();

  Future<void> showNotification(int id, String title, String body) async {
    await flutterLocalNotificationsPlugin.show(id, title, body, notificationDetails);
  }
}

1 comment

Không Biết Luôn July 15, 2022 - 9:15 AM

Đang ở trong chương trình thì thường sẽ không hay bắn notif mà t thấy trong trường hợp local notif hay được ứng dụng khi app đang tắt và bấm vào sẽ là dynamic link dẫn vào app, có thể là theo lịch có sẵn (lập lịch nhắc nhở vào app chẳng hạn). Bạn có thể hướng dẫn trong trường hợp app tắt được không ạ?

Reply

Leave a Reply to Không Biết Luôn Cancel Reply

* By using this form you agree with the storage and handling of your data by this website.

You may also like

%d bloggers like this: