Flutter通知管理插件notifiable的使用

发布于 1周前 作者 ionicwang 来自 Flutter

Flutter通知管理插件notifiable的使用

Notifiable 是一个简单的可通知小部件,它允许更新特定的小部件而无需更新整个小部件树。

Notifiable 使用

final _model = TitleAndSubtitle();
final _titleChangeNotifier = Notifier();

Notifiable(
  notifier: _titleChangeNotifier,
  builder: (context) => Text(
    _model.title,
    style: const TextStyle(fontSize: 20),
  ),
),
TextButton(
  child: Container(
    width: double.infinity,
    height: 30,
    color: Colors.blue,
    child: const Center(
      child: Text(
        "TAP TO CHANGE THE TITLE",
        style: TextStyle(color: Colors.white),
      ),
    ),
  ),
  onPressed: () {
    _model.title = "This is the new title";
    _titleChangeNotifier.notify();
  },
)

class TitleAndSubtitle {
  var title = "Title";
  var subtitle = "Subtitle";
}

在这个例子中,我们创建了一个 Notifiable 小部件来监听 _titleChangeNotifier。当点击按钮时,_model.title 的值被更改,并通过 _titleChangeNotifier.notify() 方法通知所有依赖它的 Notifiable 小部件重新构建。

Item Notifiable 使用

final _titleChangeNotifier = ItemNotifier<String>(defaultValue: "Default title");
final _subTitleChangeNotifier = ItemNotifier<String?>(defaultValue: null);

ItemNotifiable<String>(
  notifier: _titleChangeNotifier,
  builder: (context, title) => Text(
    title,
    style: const TextStyle(fontSize: 20),
  ),
),
TextButton(
  child: Container(
    width: double.infinity,
    height: 30,
    color: Colors.blue,
    child: const Center(
      child: Text(
        "TAP TO CHANGE THE TITLE",
        style: TextStyle(color: Colors.white),
      ),
    ),
  ),
  onPressed: () {
    _titleChangeNotifier.notify("This is the new title");
  },
),
const SizedBox(height: 60),
ItemNotifiable<String?>(
  notifier: _subTitleChangeNotifier,
  builder: (context, subTitle) => Text(
    subTitle ?? "The subtitle is null",
    style: const TextStyle(fontSize: 20),
  ),
),
TextButton(
  child: Container(
    width: double.infinity,
    height: 30,
    color: Colors.green,
    child: const Center(
      child: Text(
        "TAP TO CHANGE THE SUBTITLE",
        style: TextStyle(color: Colors.white),
      ),
    ),
  ),
  onPressed: () {
    _subTitleChangeNotifier.notify("This is the new subtitle");
  },
),

在这个例子中,我们使用了 ItemNotifierItemNotifiable 来管理特定类型的数据。点击按钮时,_titleChangeNotifier_subTitleChangeNotifier 会分别通知相关的 ItemNotifiable 小部件更新其内容。

完整示例 Demo

import 'package:flutter/material.dart';
import 'package:notifiable/notifiable.dart';

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

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Notifiable Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ItemNotifiableExample(),
    );
  }
}

class ItemNotifiableExample extends StatelessWidget {
  final _model = TitleAndSubtitle();
  final _titleChangeNotifier = Notifier();
  final _subtitleChangeNotifier = Notifier();

  ItemNotifiableExample({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const SizedBox(height: 60),
          Notifiable(
            notifier: _titleChangeNotifier,
            builder: (context) => Text(
              _model.title,
              style: const TextStyle(fontSize: 20),
            ),
          ),
          TextButton(
            child: Container(
              width: double.infinity,
              height: 30,
              color: Colors.blue,
              child: const Center(
                child: Text(
                  "TAP TO CHANGE THE TITLE",
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
            onPressed: () {
              _model.title = "This is the new title";
              _titleChangeNotifier.notify();
            },
          ),
          const SizedBox(height: 60),
          Notifiable(
            notifier: _subtitleChangeNotifier,
            builder: (context) => Text(
              _model.subtitle,
              style: const TextStyle(fontSize: 20),
            ),
          ),
          TextButton(
            child: Container(
              width: double.infinity,
              height: 30,
              color: Colors.green,
              child: const Center(
                child: Text(
                  "TAP TO CHANGE THE SUBTITLE",
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
            onPressed: () {
              _model.subtitle = "This is the new subtitle";
              _subtitleChangeNotifier.notify();
            },
          )
        ],
      ),
    );
  }
}

class TitleAndSubtitle {
  var title = "Title";
  var subtitle = "Subtitle";
}

更多关于Flutter通知管理插件notifiable的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter通知管理插件notifiable的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用notifiable插件进行通知管理的示例代码。notifiable插件允许你轻松地在Flutter应用中发送本地通知。以下是一个简单的示例,展示如何配置和使用该插件。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加notifiable依赖:

dependencies:
  flutter:
    sdk: flutter
  notifiable: ^x.y.z  # 请将 x.y.z 替换为当前最新版本号

然后运行flutter pub get来安装依赖。

2. 配置AndroidManifest.xmlInfo.plist

Android

android/app/src/main/AndroidManifest.xml中添加必要的权限:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <!-- 其他配置 -->

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

    <!-- 其他配置 -->

    <application
        android:name=".Application"
        ... >
        <!-- 其他配置 -->

        <service
            android:name="xyz.luan.notifiable.NotifiableService"
            android:permission="android.permission.BIND_JOB_SERVICE"
            android:exported="true">
            <intent-filter>
                <action android:name="xyz.luan.notifiable.NotifiableService" />
            </intent-filter>
        </service>

        <!-- 其他配置 -->

    </application>
</manifest>

iOS

ios/Runner/Info.plist中添加必要的配置(如果需要的话,iOS通常不需要额外的配置来使用本地通知):

<key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>

3. 初始化并使用Notifiable

在你的Flutter代码中,初始化并使用notifiable插件:

import 'package:flutter/material.dart';
import 'package:notifiable/notifiable.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Notifiable Demo'),
        ),
        body: NotificationDemo(),
      ),
    );
  }
}

class NotificationDemo extends StatefulWidget {
  @override
  _NotificationDemoState createState() => _NotificationDemoState();
}

class _NotificationDemoState extends State<NotificationDemo> {
  Notifiable? _notifiable;

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

  Future<void> _initializeNotifiable() async {
    // 初始化Notifiable
    _notifiable = await Notifiable.init(
      android: AndroidInitializationSettings(
        defaultChannelId: 'default_channel',
        channels: {
          'default_channel': AndroidNotificationChannel(
            channelId: 'default_channel',
            channelName: 'Default Channel',
            channelDescription: 'Channel description',
            importance: Importance.max,
            playSound: true,
          ),
        },
      ),
      iOS: IOSInitializationSettings(),
    );
  }

  void _showNotification() {
    if (_notifiable != null) {
      _notifiable!.display(
        Notification(
          title: 'Hello',
          body: 'This is a test notification!',
          payload: 'custom_data',
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ElevatedButton(
        onPressed: _showNotification,
        child: Text('Show Notification'),
      ),
    );
  }
}

4. 处理通知点击事件

为了处理用户点击通知时的事件,你可以监听Notifiable的点击事件:

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

  // 监听通知点击事件
  Notifiable.instance!.onNotificationOpened.listen((event) {
    // 处理点击事件
    print('Notification clicked with payload: ${event.payload}');
  });
}

这个示例展示了如何初始化notifiable插件,发送本地通知,并处理用户点击通知的事件。请根据你的具体需求调整代码。注意,notifiable插件的API可能会随着版本的更新而变化,因此请参考官方文档以获取最新和最准确的信息。

回到顶部