firebase 使用StreamBuilder实时更改appBar图标- flutter

f87krz0w  于 2023-02-09  发布在  Flutter
关注(0)|答案(2)|浏览(124)

我想用StreamBuilder结果实时更改应用栏图标(操作),
我用这个方法

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

class _MyAppState extends State<MyApp> {
  bool isOk = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          IconButton(
              onPressed: () {},
              icon: isOk ? Icon(Icons.edit) : Icon(Icons.edit_off))
        ],
      ),
      body: StreamBuilder(
        stream: FirebaseFirestore.instance
            .collection("users")
            .doc(FirebaseAuth.instance.currentUser!.uid)
            .snapshots(),
        builder: (context, streamSnapshot) {
           // set this -------------------------------------------------------
           if (streamSnapshot.data!['newRequests'].length != 0) {
             setState(() {
               isOk = true;
             });
           }
           //---------------------------------------------------------------------
          return Center(
              child: CustomText(
            size: 60,
            text: streamSnapshot.data!['newRequests'].length != 0 ? "Have" : "0",
            textColor: darkblueColor,
          ));
        },
      ),
    );
  }
}

它不起作用。它显示如下错误:

════════ Exception caught by widgets library ═══════════════════════════════════
setState() or markNeedsBuild() called during build.
The relevant error-causing widget was
StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>
xdnvmnnf

xdnvmnnf1#

创建StreamBuilder内appBar像这样,它解决了我的问题. @rahulVFlutterAndroid的答案帮助我做到了这一点.

AppBar(
        actions: [
          StreamBuilder(
            stream: stream,
            builder: (context, snapshot) {
              return  IconButton(
              onPressed: () {},
              icon: snapshot.data!['newRequests'].length != 0 ? Icon(Icons.edit) : Icon(Icons.edit_off))]),
            },
          )
        ],
      ),
4smxwvx5

4smxwvx52#

您可以使用如下

AppBar(
    actions: [
      StreamBuilder(
        stream: stream,
        builder: (context, snapshot) {
          return  IconButton(
          onPressed: () {},
          icon: snapshot.data!['newRequests'].length != 0 ? Icon(Icons.edit) : Icon(Icons.edit_off))]),
        },
      )
    ],
  ),

相关问题