如何正确使用streamSubscription cancel方法?

How to correctly use streamSubscription cancel method?

我有一个简单的应用程序页面,当用户点击按钮时,分数会上升 1。我使用流向用户显示页面上的更新分数。我怎样才能取消这个steam。我问是因为当我尝试注销时,使用 firebase,我收到一个错误,这是由于流仍然打开造成的。

如何在用户单击注销按钮时关闭流而不导致错误?

clickerPage.dart

// ignore_for_file: file_names

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:poop_alert/model/user_model.dart';
import 'package:flutter/material.dart';
import 'package:poop_alert/navDraw.dart';

class poopClicker extends StatefulWidget {
  @override
  State<poopClicker> createState() => _poopClickerState();
}

class _poopClickerState extends State<poopClicker> {
  User? user = FirebaseAuth.instance.currentUser;
  UserModel loggedInUser = UserModel();

  String userID = '';

  var count = 0;

  @override
  void initState() {
    super.initState();
    FirebaseFirestore.instance
        .collection("users")
        .doc(user!.uid)
        .get()
        .then((value) {
      loggedInUser = UserModel.fromMap(value.data());
      setState(() {});
      //int poopClick = loggedInUser.score;
    });
  }

  getuserData() async {
    User? getuserID = FirebaseAuth.instance.currentUser;
    userID = getuserID!.uid;
    print(userID);
  }

  CollectionReference note = FirebaseFirestore.instance.collection('user');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[200],
      drawer: NavigationDrawerWidget(),
      appBar: AppBar(
        title: const Text('PoopAlert'),
        centerTitle: true,
        backgroundColor: Color(0xff839ae3),
        elevation: 0.0,
      ),
      body: Column(
        children: [
          SizedBox(height: 100),
          Center(
            child: StreamBuilder(
              stream: showScore(),
              builder: (context, snapshot) {
                if (snapshot.data != null) {
                  return  Center(
              child: Text(
                'Score: '+ snapshot.data.toString(),
                style: TextStyle( 
                  color: Color(0xff516395),
                  fontSize: 30.0,
                  letterSpacing: 2.0,
                  fontWeight: FontWeight.bold,
                ),
                
              ),
            );
                } else {
                  return Text(
                'Score: 0',
                style: TextStyle( 
                  color: Color(0xff516395),
                  fontSize: 30.0,
                  letterSpacing: 2.0,
                  fontWeight: FontWeight.bold,
                )
                  );
                }
              },
            ),
          ),
          Center(
            child: ElevatedButton(
              onPressed: () {
                print("clicked");
              },
              child: IconButton(
                icon: Image.asset('assets/poop.png'),
                iconSize: 300,
                onPressed: () {
                  getuserData();
                  setState(() {
                    print('Clicked: ' "${loggedInUser.score}");
                    FirebaseFirestore.instance
                        .collection('users')
                        .doc(loggedInUser.uid)
                        .update({"score": FieldValue.increment(1)});
                  });
                },
              ),
              style: ElevatedButton.styleFrom(
                  primary: Colors.grey[200], elevation: 0.0),
            ),
          ),
        ],
      ),
    );
  }

  Stream<int?> showScore() async* {
    FirebaseFirestore.instance
        .collection("users")
        .doc(user!.uid)
        .get()
        .then((value) {
      loggedInUser = UserModel.fromMap(value.data());
      setState(() {});
    });
    yield loggedInUser.score;
  }
}

``  

您应该直接从 StreamBuilder.

中收听乐谱
StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
  stream: FirebaseFirestore.instance
      .collection("users")
      .doc(user!.uid)
      .snapshots(),
  builder: ((context, snapshot) {
    loggedInUser = UserModel.fromMap(snapshot.data!.data()!);
    // some code omitted
    return Center(
      child: Text(
        'Score: ' + loggedInUser.score.toString(),
        // rest of your code
      ),
    );
  }),
)

谢谢大家的帮助,但过了一段时间我终于让它工作了。我没有将所有值映射到我的 class,而是只是从 snapshop.data

中调用了我的特定值
                                 StreamBuilder<
                                    DocumentSnapshot<Map<String, dynamic>>>(
                                  stream: FirebaseFirestore.instance
                                      .collection("users")
                                      .doc(user!.uid)
                                      .snapshots(),
                                  builder: ((context, snapshot) {
                                    print(snapshot.data);
                                    var userDocument = snapshot.data;
                                    if (snapshot.data != null) {
                                      return Center(
                                        child: Text(
                                          snapshot.data!["timeActive"].toString(),
                                          style: TextStyle(
                                            color: Color(0xff516395),
                                            fontSize: 30.0,
                                            letterSpacing: 2.0,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      );
                                    } else {
                                      return Text('0',
                                          style: TextStyle(
                                            color: Color(0xff516395),
                                            fontSize: 30.0,
                                            letterSpacing: 2.0,
                                            fontWeight: FontWeight.bold,
                                          ));
                                    }
                                  }),
                                )