Onesignal уведомление, когда приложение закрывается флаттер

#flutter #dart #onesignal

#флаттер #dart #onesignal

Вопрос:

Как мне отправить уведомление onesignal при закрытии приложения в flutter? Когда приложение открыто, проблем нет. Приложение полностью закрывается пользователем, а не приложением, работающим в фоновом режиме.

Я предоставил свой код для проверки: я новичок в flutter, поэтому не уверен, как это работает, особенно push-уведомление

 import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:connectivity/connectivity.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:onesignal_flutter/onesignal_flutter.dart';

Future main() async {
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _outputText = "";
  @override
  void initState() {
    super.initState();
    initOneSignal();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: IndexedStack(
      index: 0,
      children: <Widget>[
        InAppWebViewPage(),
        Container(
          child: Text(_outputText),
        )
      ],
    ));
  }

  Future<void> initOneSignal() async {
    await OneSignal.shared
        .init("xxxxxxxx-xxxxxxxxxx", iOSSettings: null);
    OneSignal.shared
        .setInFocusDisplayType(OSNotificationDisplayType.notification);
    OneSignal.shared
        .setNotificationReceivedHandler((OSNotification notification) {
      this.setState(() {
        _outputText =
            "Received notification: n${notification.jsonRepresentation().replaceAll("\n", "n")}";
      });
    });
  }
}

class InAppWebViewPage extends StatefulWidget {
  @override
  _InAppWebViewPageState createState() => new _InAppWebViewPageState();
}

class _InAppWebViewPageState extends State<InAppWebViewPage> {
  InAppWebViewController webView;
  int _page = 2;
  bool _loadError = false;
  StreamSubscription<ConnectivityResult> subscription;

  @override
  initState() {
    super.initState();
    subscription = Connectivity()
        .onConnectivityChanged
        .listen((ConnectivityResult result) {
      if (result != ConnectivityResult.none amp;amp; webView != null) {
        print("reload");
        _loadError = false;
        webView.reload();
      }
    });
  }

  @override
  dispose() {
    super.dispose();
    subscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: IndexedStack(
        index: _page,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(top: 20.0),
            child: InAppWebView(
              initialUrl: "https://flutter.dev/",
              initialHeaders: {},
              initialOptions: InAppWebViewGroupOptions(
                crossPlatform: InAppWebViewOptions(
                  clearCache: true,
                  debuggingEnabled: true,
                ),
              ),
              onWebViewCreated: (InAppWebViewController controller) {
                webView = controller;
              },
              onLoadStart: (InAppWebViewController controller, String url) {},
              onLoadStop: (InAppWebViewController controller, String url) {
                print(url);
                setState(() {
                  if (!_loadError) {
                    _page = 0;
                  } else {
                    _page = 1;
                  }
                });
              },
              onLoadError: (InAppWebViewController controller, String url,
                  int code, String message) async {
                print("error $url: $code, $message");
                _loadError = true;
              },
              onLoadHttpError: (InAppWebViewController controller, String url,
                  int statusCode, String description) async {
                print("HTTP error $url: $statusCode, $description");
              },
            ),
          ),
          (Platform.isAndroid)
              ? Container(
                  child: Text("My custom error message"),
                )
              : Container(
                  decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('assets/images/splash.png'),
                    fit: BoxFit.fill,
                  ),
                )),
          Container(
              color: Colors.transparent,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: ExactAssetImage('assets/images/splash.png'),
                  fit: BoxFit.fill,
                ),
              )),
        ],
      ),
    );
  }
}
 

Любая помощь приветствуется. Заранее спасибо

Ответ №1:

убедитесь, что вы правильно выполняете настройку Flutter SDK https://documentation.onesignal.com/docs/flutter-sdk-setup

Комментарии:

1. Какая это была часть? Я уже следую всей документации, и она работает отлично. Только не приложение close / force kill, которое вообще не запускается.

2. @Ezekiel если вы уже следуете ему, возможно, создать новый проект и настроить снова будет работать. потому что я это сделал, и это работает для меня, так что попробуйте!

3. Включает ли это, когда приложение закрывается / принудительно уничтожается?

4. да, после этого уведомление моего приложения работает отлично.