Flutter 处置不';不要完全处理

Flutter 处置不';不要完全处理,flutter,dispose,Flutter,Dispose,我注意到一些奇怪的事情,很可能是因为我不理解这个概念 我正在收听来自firebase的云消息。我有两个省道文件A和B A看起来像: import 'package:flutter/material.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; void

我注意到一些奇怪的事情,很可能是因为我不理解这个概念

我正在收听来自firebase的云消息。我有两个省道文件A和B

A看起来像:

import 'package:flutter/material.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {

    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

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

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }
  FirebaseMessaging firebaseMessaging = new FirebaseMessaging();
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
  @override
  void initState() {

    super.initState();
    firebaseMessaging.configure(
      onLaunch: (Map<String, dynamic> msg) {
        print(" onLaunch called $msg");
      },
      onResume: (Map<String, dynamic> msg) {
        print(" onResume called ${(msg)}");
      },
      onMessage: (Map<String, dynamic> msg) {
        //showNotification(msg);
        print(" onMessage called in Activity A ${(msg)}");//--!!!!!-------!!!!->notice this
      },
    );
    firebaseMessaging.requestNotificationPermissions(
        const IosNotificationSettings(sound: true, alert: true, badge: true));
    firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings setting) {
      print('IOS Setting Registered');
    });
    firebaseMessaging.getToken().then((token) {
      print("token: "+token);
    });
    flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
    var android = new AndroidInitializationSettings('@mipmap/ic_launcher');
    var iOS = new IOSInitializationSettings();
    var initSetttings = new InitializationSettings(android, iOS);
    flutterLocalNotificationsPlugin.initialize(initSetttings);
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.add),
            onPressed: (){
              Navigator.push(context, MaterialPageRoute(builder: (context)=>Sample() ));// calling screen B from action of app bar
            },
          )
        ],
      ),
      body: new Container(),
    );
  }
}
导入“包装:颤振/材料.省道”;
导入“package:firebase_messaging/firebase_messaging.dart”;
导入“package:flatter_local_notifications/flatter_local_notifications.dart”;
void main()=>runApp(新的MyApp());
类MyApp扩展了无状态小部件{
//此小部件是应用程序的根。
@凌驾
小部件构建(构建上下文){
返回新材料PP(
标题:“颤振演示”,
主题:新主题数据(
主样本:颜色。蓝色,
),
主页:新MyHomePage(标题:“颤振演示主页”),
);
}
}
类MyHomePage扩展StatefulWidget{
MyHomePage({Key,this.title}):超级(Key:Key);
最后的字符串标题;
@凌驾
_MyHomePageState createState()=>new_MyHomePageState();
}
类_MyHomePageState扩展状态{
int _计数器=0;
void _incrementCounter(){
设置状态(){
_计数器++;
});
}
FirebaseMessaging FirebaseMessaging=新建FirebaseMessaging();
flatterlocalnotificationsplugin flatterlocalnotificationsplugin;
@凌驾
void initState(){
super.initState();
firebaseMessaging.configure(
onLaunch:(地图消息){
打印(“onLaunch称为$msg”);
},
onResume:(映射消息){
打印(“名为${(msg)}的简历”);
},
onMessage:(映射消息){
//显示通知(msg);
打印(“在活动A${(msg)}中调用的消息”);//--!!!!!!!!!!!!!!!!->注意这一点
},
);
firebaseMessaging.requestNotificationPermissions(
const IosNotificationSettings(声音:真、警报:真、徽章:真);
firebaseMessaging.onissettings已注册
.listen((IONotificationSettings设置){
打印(“IOS设置已注册”);
});
firebaseMessaging.getToken().then((令牌){
打印(“令牌:+令牌”);
});
FlatterLocalNotificationsPlugin=新的FlatterLocalNotificationsPlugin();
var android=新的AndroidInitializationSettings(“@mipmap/ic_launcher”);
var iOS=新的IOSInitializationSettings();
var initSetttings=新的初始化设置(android、iOS);
flatterLocalNotificationsPlugin.initialize(初始化设置);
}
@凌驾
小部件构建(构建上下文){
归还新脚手架(
appBar:新的appBar(
标题:新文本(widget.title),
行动:[
图标按钮(
图标:图标(Icons.add),
已按下:(){
Navigator.push(context,MaterialPageRoute(builder:(context)=>Sample());//从应用程序栏的操作调用屏幕B
},
)
],
),
正文:新容器(),
);
}
}
请注意,如果在“活动a”中调用了新消息,我将在控制台中打印该行

现在B看起来像:

import 'package:flutter/material.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';


class Sample extends StatefulWidget {

  @override
  _SampleState createState() => _SampleState();
}

class _SampleState extends State<Sample> {

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




  FirebaseMessaging firebaseMessaging1 = new FirebaseMessaging();
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin1;
  @override
  void initState() {

    super.initState();
    firebaseMessaging1.configure(
      onLaunch: (Map<String, dynamic> msg) {
        print(" onLaunch called $msg");
      },
      onResume: (Map<String, dynamic> msg) {
        print(" onResume called ${(msg)}");
      },
      onMessage: (Map<String, dynamic> msg) {
        //showNotification(msg);
        print(" onMessage called in Activity B ${(msg)}");//----!!!---!!!!---Notice this
      },
    );
    firebaseMessaging1.requestNotificationPermissions(
        const IosNotificationSettings(sound: true, alert: true, badge: true));
    firebaseMessaging1.onIosSettingsRegistered
        .listen((IosNotificationSettings setting) {
      print('IOS Setting Registered');
    });
    firebaseMessaging1.getToken().then((token) {
      print("token: "+token);
    });
    flutterLocalNotificationsPlugin1 = new FlutterLocalNotificationsPlugin();
    var android = new AndroidInitializationSettings('@mipmap/ic_launcher');
    var iOS = new IOSInitializationSettings();
    var initSetttings = new InitializationSettings(android, iOS);
    flutterLocalNotificationsPlugin1.initialize(initSetttings);
    print(firebaseMessaging1.toString());

  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(),
    );
  }
}
导入“包装:颤振/材料.省道”;
导入“package:firebase_messaging/firebase_messaging.dart”;
导入“package:flatter_local_notifications/flatter_local_notifications.dart”;
类示例扩展StatefulWidget{
@凌驾
_SampleState createState()=>_SampleState();
}
类_SampleState扩展状态{
@凌驾
无效处置(){
super.dispose();
}
FirebaseMessaging firebaseMessaging1=新的FirebaseMessaging();
flatterLocalNotificationsPlugin flatterLocalNotificationsPlugin1;
@凌驾
void initState(){
super.initState();
firebaseMessaging1.configure(
onLaunch:(地图消息){
打印(“onLaunch称为$msg”);
},
onResume:(映射消息){
打印(“名为${(msg)}的简历”);
},
onMessage:(映射消息){
//显示通知(msg);
打印(“在活动B${(msg)}中调用的消息”);//----注意这一点
},
);
firebaseMessaging1.requestNotificationPermissions(
const IosNotificationSettings(声音:真、警报:真、徽章:真);
FirebaseMessaging 1.1已注册安装
.listen((IONotificationSettings设置){
打印(“IOS设置已注册”);
});
firebaseMessaging1.getToken().then((令牌){
打印(“令牌:+令牌”);
});
FlatterLocalNotificationsPlugin1=新的FlatterLocalNotificationsPlugin();
var android=新的AndroidInitializationSettings(“@mipmap/ic_launcher”);
var iOS=新的IOSInitializationSettings();
var initSetttings=新的初始化设置(android、iOS);
flatterLocalNotificationsPlugin1.initialize(初始化设置);
打印(firebaseMessaging1.toString());
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
主体:容器(),
);
}
}
所以目标很简单。根据我们所处的活动,当通知到达时,它应该执行不同的操作

如果在中,则打印通知以

如果在B中,则打印通知到达B

但问题是,当我从B切换回A时(B是使用Navigator push从A调用的),它仍然打印到达B的通知

不是dispose没有完全处理,就是我缺少了一些东西

dispose没有做任何花哨的事情。处理自定义处置行为是您的工作

更具体地说,你必须明确地清理所有你可能造成的混乱。在您的情况下,这将转化为取消订阅firebase的流

这可转化为以下内容:

StreamSubscription streamSubscription;
Stream myStream;

@override
void initState() {
  super.initState();
  streamSubscription = myStream.listen((foo) {
    print(foo);
  });
}

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

您必须对所有侦听的流和类似对象执行相同的操作(例如
Listenable

我预期会出现类似的情况。你能具体谈谈我的情况吗?我已经告诉你需要做什么了。您正在收听流,但不要取消订阅HMMM…将对此进行更多探索。谢谢