Closed4

Flutterの通知パッケージを使ってみる

薄田達哉 / tatsuyasusukida薄田達哉 / tatsuyasusukida

flutter_local_notifications

準備

flutter create hello_notification
cd hello_notification
flutter pub add flutter_local_notifications
flutter pub add timezone

コード

hello_notification/lib/main.dart
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/data/latest_10y.dart';
import 'package:timezone/timezone.dart';

void main() {
  initializeTimeZones();
  runApp(const MyApp());
}

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

  
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(),
    );
  }
}

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

  Future<void> _scheduleNotification() async {
    final plugin = FlutterLocalNotificationsPlugin();
    const settings = InitializationSettings(
      android: AndroidInitializationSettings('@mipmap/ic_launcher'),
    );

    await plugin.initialize(settings);

    const id = 0;
    const title = 'title';
    const body = 'body';
    final scheduledDate = TZDateTime.now(local).add(const Duration(seconds: 5));

    const channelId = 'channel_id';
    const channelName = 'channel_name';
    const details = NotificationDetails(
      android: AndroidNotificationDetails(channelId, channelName),
    );

    const dateInterpretation =
        UILocalNotificationDateInterpretation.absoluteTime;

    await plugin.zonedSchedule(
      id,
      title,
      body,
      scheduledDate,
      details,
      androidAllowWhileIdle: true,
      uiLocalNotificationDateInterpretation: dateInterpretation,
    );
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('AppBar Title'),
      ),
      body: Center(
        child: Text(
          'zonedSchedule',
          style: Theme.of(context).textTheme.headline4,
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _scheduleNotification,
        tooltip: 'Increment',
        child: const Icon(Icons.notifications),
      ),
    );
  }
}

Androidの場合はcompileSdkVersionを33に指定した方が良さそう(しなくても動くが)

実行コマンド

iOSまたはAndroid実機を使用する

flutter run

実行結果

右下の通知アイコンのボタンを押して5秒後に通知が表示されることを確認する

薄田達哉 / tatsuyasusukida薄田達哉 / tatsuyasusukida

すぐに通知を表示する場合

準備コマンド

flutter create hello_notification
cd hello_notification
flutter pub add flutter_local_notifications

コード

hello_notification/lib/main.dart
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

void main() {
  runApp(const MyApp());
}

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

  
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(),
    );
  }
}

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

  Future<void> _showNotification() async {
    final plugin = FlutterLocalNotificationsPlugin();
    const settings = InitializationSettings(
      android: AndroidInitializationSettings('@mipmap/ic_launcher'),
    );

    await plugin.initialize(settings);

    const id = 0;
    const title = 'title';
    const body = 'body';

    const channelId = 'channelId';
    const channelName = 'channelName';
    const details = NotificationDetails(
      android: AndroidNotificationDetails(channelId, channelName),
    );

    await plugin.show(id, title, body, details);
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('AppBar Title'),
      ),
      body: Center(
        child: Text('show', style: Theme.of(context).textTheme.headline4),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _showNotification,
        tooltip: 'Show Notification',
        child: const Icon(Icons.notifications),
      ),
    );
  }
}

Androidの場合はcompileSdkVersionを33に指定した方が良さそう(しなくても動くが)

実行コマンド

AndroidまたはiOS実機で実行する

flutter run

実行結果

右下の通知アイコンのボタンを押すとただちに通知が表示されることを確認する

メモ

hello_notification/android/app/build.gradle
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
$ which flutter
/Users/susukida/development/flutter/bin/flutter
/Users/susukida/development/flutter/packages/flutter_tools/gradle/flutter.gradle
    /** Sets the compileSdkVersion used by default in Flutter app projects. */
    static int compileSdkVersion = 31

    /** Sets the minSdkVersion used by default in Flutter app projects. */
    static int minSdkVersion = 16

    /** Sets the targetSdkVersion used by default in Flutter app projects. */
    static int targetSdkVersion = 31

compileSdkVersionなどのデフォルト値と定義されているファイルのパスがわかった

このスクラップは2023/01/10にクローズされました