flutter 来自dart:html的通知没有显示,

3ks5zfa0  于 4个月前  发布在  Flutter
关注(0)|答案(6)|浏览(49)

重现步骤

Notification 从 dart:html 中无法正常工作。这段代码是用来显示通知的吗?
html.Notification('Hello, World!');
请查看完整的应用程序示例,其中没有显示通知。

预期结果

它会在谷歌浏览器中显示通知。

实际结果

在谷歌浏览器中没有显示通知。

代码示例

代码示例

import 'package:flutter/material.dart';
import 'dart:html' as html;

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

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

  void _incrementCounter() {
    html.Notification('Hello, World!');
    setState(() {
      _counter++;
    });
  }

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

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

    html.window.console.log('Hello, World!');
    html.Notification.requestPermission().then((userPermission) {
      if (userPermission != 'granted') {
        return;
      }
      
      html.Notification('Hello, World!');
      html.Notification.new('Hello, World!');
    });
  }
}

Flutter Doctor 输出

Doctor 输出

[✓] Flutter (Channel stable, 3.22.2, on macOS 14.5 23F79 darwin-arm64, locale en-GB)
• Flutter version 3.22.2 on channel stable at /Users/benjaminfarquhar/development/flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision 761747bfc5 (11 days ago), 2024-06-05 22:15:13 +0200
• Engine revision edd8546116
• Dart version 3.4.3
• DevTools version 2.34.3

[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
• Android SDK at /Users/benjaminfarquhar/Library/Android/sdk
• Platform android-34, build-tools 34.0.0
• ANDROID_HOME = /Users/benjaminfarquhar/Library/Android/sdk
• Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b829.9-10027231)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 15.4)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Build 15F31d
• CocoaPods version 1.15.2

[✓] Chrome - develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2022.3)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b829.9-10027231)

[✓] IntelliJ IDEA Community Edition (version 2023.2.2)
• IntelliJ at /Applications/IntelliJ IDEA CE.app
• Flutter plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/6351-dart

[✓] VS Code (version 1.90.0)
• VS Code at /Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.90.0

[✓] Connected device (4 available)
• Benji’s iPhone 13 mini (mobile) • 00008110-001119123C7B801E • ios            • iOS 17.5.1 21F90
• macOS (desktop)                 • macos                     • darwin-arm64   • macOS 14.5 23F79 darwin-arm64
• Mac Designed for iPad (desktop) • mac-designed-for-ipad     • darwin         • macOS 14.5 23F79 darwin-arm64
• Chrome (web)                    • chrome                    • web-javascript • Google Chrome 125.0.6422.176

[✓] Network resources
• All expected network resources are available.

• No issues found!```

</details>
oymdgrw7

oymdgrw71#

@BenjiFarquhar
Notification from dart:html 不起作用。这段代码是用来显示通知的吗?
这段代码确实可以工作。你需要允许显示通知,如下所示:

然后在运行给定的代码后,它会显示通知并在控制台中打印出来:

A Dart VM Service on Chrome is available at: http://127.0.0.1:52353/_CeaKEIrgOQ=
Hello, World!
cedebl8k

cedebl8k2#

感谢。当我点击弹出的“允许”时,我会点击“允许”。但是然后没有通知显示给我。

我希望每次点击FAB时都能看到一个新的通知,但实际上并没有:

你能请展示一个带有显示“Hello World!”的通知的完整页面截图吗?你是像我一样在本地调试模式下运行flutter run -d chrome吗?

我的Chrome版本是125.0.6422.176(官方构建)(arm64)。我刚刚更新到126.0.6478.62(官方构建)(arm64),但它并没有解决问题。

hgb9j2n6

hgb9j2n63#

请展示一个带有显示 "Hello World!" 通知的完整页面截图。您是否像我一样在本地以调试模式运行 flutter run -d chrome?
是的,我用相同的命令在本地运行。有趣的是,当我第一次运行代码时,我在屏幕右上角确实看到了通知,但我没有截图或录制视频,现在当我再次尝试时,我看不到它发生,所以我错过了记录它的时机:(
我会将此问题保持开放,以便团队关注/跟踪。
稳定版,主分支 flutter doctor -v

[!] Flutter (Channel stable, 3.22.2, on macOS 12.2.1 21D62 darwin-x64, locale
    en-GB)
    • Flutter version 3.22.2 on channel stable at
      /Users/dhs/documents/fluttersdk/flutter
    ! Warning: `flutter` on your path resolves to
      /Users/dhs/Documents/Fluttersdk/flutter/bin/flutter, which is not inside
      your current Flutter SDK checkout at
      /Users/dhs/documents/fluttersdk/flutter. Consider adding
      /Users/dhs/documents/fluttersdk/flutter/bin to the front of your path.
    ! Warning: `dart` on your path resolves to
      /Users/dhs/Documents/Fluttersdk/flutter/bin/dart, which is not inside your
      current Flutter SDK checkout at /Users/dhs/documents/fluttersdk/flutter.
      Consider adding /Users/dhs/documents/fluttersdk/flutter/bin to the front
      of your path.
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 761747bfc5 (33 hours ago), 2024-06-05 22:15:13 +0200
    • Engine revision edd8546116
    • Dart version 3.4.3
    • DevTools version 2.34.3
    • If those were intentional, you can disregard the above warnings; however
      it is recommended to use "git" directly to perform update checks and
      upgrades.

[!] Xcode - develop for iOS and macOS (Xcode 12.3)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    ! Flutter recommends a minimum Xcode version of 13.
      Download the latest version or update via the Mac App Store.
    • CocoaPods version 1.11.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] VS Code (version 1.62.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.21.0

[✓] Connected device (5 available)
    • SM G975F (mobile)       • RZ8M802WY0X • android-arm64   • Android 11 (API 30)
    • Darshan's iphone (mobile)  • 21150b119064aecc249dfcfe05e259197461ce23 •
      ios            • iOS 14.4.1 18D61
    • iPhone 12 Pro Max (mobile) • A5473606-0213-4FD8-BA16-553433949729     •
      ios            • com.apple.CoreSimulator.SimRuntime.iOS-14-3 (simulator)
    • macOS (desktop)            • macos                                    •
      darwin-x64     • Mac OS X 10.15.4 19E2269 darwin-x64
    • Chrome (web)               • chrome                                   •
      web-javascript • Google Chrome 98.0.4758.80

[✓] HTTP Host Availability
    • All required HTTP hosts are available

! Doctor found issues in 1 category.

[!] Flutter (Channel master, 3.23.0-13.0.pre.262, on macOS 12.2.1 21D62
    darwin-x64, locale en-GB)
    • Flutter version 3.23.0-13.0.pre.262 on channel master at
      /Users/dhs/documents/fluttersdk/flutter
    ! Warning: `flutter` on your path resolves to
      /Users/dhs/Documents/Fluttersdk/flutter/bin/flutter, which is not inside
      your current Flutter SDK checkout at
      /Users/dhs/documents/fluttersdk/flutter. Consider adding
      /Users/dhs/documents/fluttersdk/flutter/bin to the front of your path.
    ! Warning: `dart` on your path resolves to
      /Users/dhs/Documents/Fluttersdk/flutter/bin/dart, which is not inside your
      current Flutter SDK checkout at /Users/dhs/documents/fluttersdk/flutter.
      Consider adding /Users/dhs/documents/fluttersdk/flutter/bin to the front
      of your path.
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 6a8f70f11e (2 hours ago), 2024-06-18 00:12:10 -0400
    • Engine revision 78fdd06af5
    • Dart version 3.5.0 (build 3.5.0-272.0.dev)
    • DevTools version 2.36.0
    • If those were intentional, you can disregard the above warnings; however
      it is recommended to use "git" directly to perform update checks and
      upgrades.

[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/dhs/Library/Android/sdk
    ✗ cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/macos#android-setup for
      more details.

[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 13C100
    • CocoaPods version 1.11.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] IntelliJ IDEA Ultimate Edition (version 2021.3.2)
    • IntelliJ at /Applications/IntelliJ IDEA.app
    • Flutter plugin version 65.1.4
    • Dart plugin version 213.7228

[✓] VS Code (version 1.62.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.29.0

[✓] Connected device (3 available)
    • Darshan's iphone (mobile) • 21150b119064aecc249dfcfe05e259197461ce23 • ios
      • iOS 15.3.1 19D52
    • macOS (desktop)           • macos                                    •
      darwin-x64     • macOS 12.2.1 21D62 darwin-x64
    • Chrome (web)              • chrome                                   •
      web-javascript • Google Chrome 109.0.5414.119

[✓] Network resources
    • All expected network resources are available.

! Doctor found issues in 1 category.
      
[!] Xcode - develop for iOS and macOS (Xcode 12.3)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    ! Flutter recommends a minimum Xcode version of 13.
      Download the latest version or update via the Mac App Store.
    • CocoaPods version 1.11.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] VS Code (version 1.62.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.21.0

[✓] Connected device (5 available)
    • SM G975F (mobile)       • RZ8M802WY0X • android-arm64   • Android 11 (API 30)
    • Darshan's iphone (mobile)  • 21150b119064aecc249dfcfe05e259197461ce23 •
      ios            • iOS 14.4.1 18D61
    • iPhone 12 Pro Max (mobile) • A5473606-0213-4FD8-BA16-553433949729     •
      ios            • com.apple.CoreSimulator.SimRuntime.iOS-14-3 (simulator)
    • macOS (desktop)            • macos                                    •
      darwin-x64     • Mac OS X 10.15.4 19E2269 darwin-x64
    • Chrome (web)               • chrome                                   •
      web-javascript • Google Chrome 98.0.4758.80

[✓] HTTP Host Availability
    • All required HTTP hosts are available

! Doctor found issues in 1 category.
m1m5dgzv

m1m5dgzv4#

感谢创建这个问题; dart:html 是一个非常薄的 js-interop 层,使 Flutter Web 应用能够使用标准的 JS API,在这个例子中是 "Notifications API"。这里是它的文档:

这里是文档中的一些重点,导致了这个问题(以及它的复现):

用户需要授予显示通知的权限,这通常在应用程序或网站初始化时完成,使用 Notification.requestPermission() 方法。这应该在用户手势的响应中完成,例如点击按钮

...
这不仅是最佳实践,而且在未来 浏览器将明确禁止未响应用户手势触发的通知。 💔
提供的复现代码试图 requestPermission 并显示通知而无需用户交互**(在其 initState 方法中)**

建议的解决方案

我建议修改复现中的 _MyHomePageState 类,如下所示:

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

  /// onPressed, display a notification and increase the counter.
  void _incrementCounter() async {
    await displayNotification();
    setState(() {
      _counter++;
    });
  }

  /// Always request for permissions, and if 'granted', display a notification.
  Future<void> displayNotification() async {
    final permission = await html.Notification.requestPermission();
    if (permission == 'granted') {
      html.Notification('About to update counter to: ${_counter + 1}');
    }
  }

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

  // Removed `initState`
}

一些不请自来的忠告:

  • 请记住在设置或“来源设置”按钮中重置允许/拒绝通知:

  • 我建议将此代码从 dart:html 迁移到 package:web ,这是一个更现代(且与 Wasm 兼容)的 js-interop 层。参见 migration instructions

请告知 @BenjiFarquhar,如果这有帮助,我们可以关闭此问题。谢谢!

e4eetjau

e4eetjau5#

由于缺乏额外信息,我们很遗憾地不确定如何解决这个问题。因此,我们暂时不情愿地关闭这个bug。
如果您发现此问题,请使用相同的描述、发生的情况、日志和'flutter doctor -v'的输出文件新的问题。所有系统设置可能略有不同,因此始终最好打开新的问题并参考相关问题。
感谢您的贡献。

vcirk6k6

vcirk6k66#

你好,@ditman,抱歉回复较慢,我被其他任务分心了。感谢分享一些修订后的代码。我刚刚尝试运行你提出的解决方案。它仍然对我不起作用,确实存在同样的问题,它显示请求权限对话框,但不显示通知。你试过运行它来确认它是否有效吗?我们能重新打开这个问题吗?
抄送:@darshankawar

相关问题