Flutter消息提示插件ntoaster的使用

Flutter消息提示插件ntoaster的使用

NToaster

Toasts是一种轻量级的通知,旨在模仿移动和桌面操作系统广泛使用的推送通知。

特性

  • 可以通过单例或继承小部件(InheritedWidget)访问通知中心。
  • 完全灵活的动画和小部件UI。
  • 可以通过编程方式移除通知。
  • 当用户长按通知时,其计时器将暂停,直到通知释放。

使用方法

步骤1:手动附加通知中心

你可以通过NToasterController.attach方法手动附加通知中心,或者构建一个NToasterCenter,它会自动处理通知中心的附加和分离,并为你提供一个NToaster继承小部件。

// 手动附加
final ntoaster = NToasterController.getInstance();
ntoaster.attach(context, configuration: NToasterConfiguration(
)); // 传递你的中心级别配置

步骤2:构建应用

MaterialApp中包含NToasterCenter,并设置应用的基本配置。

// Widget附加
Widget build(BuildContext context) {
  return MaterialApp(
    title: 'Flutter Demo',
    theme: ThemeData(
      primarySwatch: Colors.blue,
    ),
    home: const NToasterCenter(
        child: MyHomePage(title: 'Flutter Demo Home Page')),
  );
}

步骤3:入队通知

创建一个NotificationMetaData对象,并将其添加到通知队列中。这可以包含你希望显示的通知内容。

// 入队通知
final ntoaster = NToaster.of(context);
NotificationMetaData? notification;
notification = NotificationMetaData(
  showFor: Duration(milliseconds: 5000), // 显示时长
  item: GestureDetector(
    onTap: () {
      notification?.remove(); // 点击通知时移除
    },
    child: SizedBox(
      height: 100,
      width: 300,
      child: Card(
        elevation: 8.0,
        color: Colors.green,
        child: Text("$_counter Cool title", 
          style: Theme.of(context).textTheme.subtitle1?.copyWith(color: Colors.white),
        ),
      ),
    ),
  ),
);
ntoaster.enqueue(notification);

步骤4:立即移除通知

如果你持有NotificationMetaData的引用,可以在定时结束前立即移除该通知。

// 立即移除通知
final notificationX = NotificationMetaData(...);
final ntoaster = NToaster.of(context);
ntoaster.dequeue(notificationX);

示例代码

以下是完整的示例代码,演示了如何使用ntoaster插件来显示动态生成的通知。

import 'dart:math';

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

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

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  [@override](/user/override)
  void initState() {
    super.initState();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const NToasterCenter(
          child: MyHomePage(title: 'Flutter Demo Home Page')),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    _counter++;
    setState(() {});

    final ntoaster = NToaster.of(context);
    NotificationMetaData? notification;
    notification = NotificationMetaData(
      insertionAnimationBuilder: (context, child, animation) => ScaleTransition(
        scale: animation,
        child: child,
      ),
      removalAnimationBuilder: (context, child, animation) => SlideTransition(
        position: Tween(begin: const Offset(1, 0), end: const Offset(0.5, 0))
            .animate(animation),
        child: child,
      ),
      showFor: Duration(
          milliseconds:
              (Random(DateTime.now().millisecondsSinceEpoch).nextDouble() *
                      5000)
                  .toInt()),
      item: GestureDetector(
        onTap: () {
          notification?.remove();
        },
        child: SizedBox(
          height:
              Random(DateTime.now().millisecondsSinceEpoch).nextDouble() * 100 +
                  50,
          width: 300,
          child: Card(
            elevation: 8.0,
            color: Colors.red.withGreen(
                Random(DateTime.now().millisecondsSinceEpoch).nextInt(255)),
            child: Center(
              child: Text(
                "$_counter Cool title",
                style: Theme.of(context)
                    .textTheme
                    .subtitle1
                    ?.copyWith(color: Colors.white),
              ),
            ),
          ),
        ),
      ),
    );
    ntoaster.enqueue(
      notification,
    );
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

更多关于Flutter消息提示插件ntoaster的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter消息提示插件ntoaster的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


ntoaster 是一个用于在 Flutter 应用中显示消息提示的插件。它可以帮助你轻松地在应用中显示 Toast 消息,类似于 Android 中的 Toast。以下是如何使用 ntoaster 插件的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 ntoaster 依赖:

dependencies:
  flutter:
    sdk: flutter
  ntoaster: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来获取依赖。

2. 导入包

在你的 Dart 文件中导入 ntoaster 包:

import 'package:ntoaster/ntoaster.dart';

3. 显示 Toast 消息

你可以使用 NToaster.showToast 方法来显示 Toast 消息。以下是一个简单的示例:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('NToaster Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () {
              // 显示 Toast 消息
              NToaster.showToast(
                context: context,
                message: 'Hello, NToaster!',
                duration: Duration(seconds: 2),
                position: ToastPosition.bottom,
              );
            },
            child: Text('Show Toast'),
          ),
        ),
      ),
    );
  }
}

4. 参数说明

NToaster.showToast 方法支持以下参数:

  • context: BuildContext,用于显示 Toast 的上下文。
  • message: 要显示的文本消息。
  • duration: Toast 显示的持续时间,默认为 Duration(seconds: 2)
  • position: Toast 显示的位置,可以是 ToastPosition.topToastPosition.centerToastPosition.bottom,默认为 ToastPosition.bottom

5. 自定义 Toast

你还可以通过传递 backgroundColortextColortextStyle 等参数来自定义 Toast 的外观:

NToaster.showToast(
  context: context,
  message: 'Custom Toast',
  duration: Duration(seconds: 3),
  position: ToastPosition.center,
  backgroundColor: Colors.blue,
  textColor: Colors.white,
  textStyle: TextStyle(fontSize: 16.0),
);

6. 关闭 Toast

如果你需要在某些情况下手动关闭 Toast,可以使用 NToaster.hideToast 方法:

NToaster.hideToast();
回到顶部