-1

class MyClass extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var _userSnapshot;
    List<dynamic> myContactsList;
    return StreamProvider<DocumentSnapshot>.value(
      value: DatabaseService("").myUser,
      builder: (context, child) => Expanded(
        child: Container(
            child: (_userSnapshot = Provider.of<DocumentSnapshot>(context)) ==
                        null ||
                    (myContactsList = _userSnapshot.data["contacts"]) == null
                ? Padding(
                    // if no contacts were found
                    padding: EdgeInsets.all(10.0),
                    child: Column(
                      children: <Widget>[
                        Text(
                          "No recent chats yet",
                        ),
                      ],
                    ),
                  )
                : ListView.builder(
                    itemCount: _userSnapshot.data["contacts"].length,
                    itemBuilder: (context, index) => FutureBuilder(
                      future: DatabaseService("").getUserById(
                        myContactsList.elementAt(index),
                      ),
                      builder: (context, snapshot) => GestureDetector(
                        onTap: () => Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (_) => ChatScreen(
                              myContactsList.elementAt(index),
                              snapshot.data["displayName"],
                            ),
                          ),
                        ),
                        child: Container(
                          margin: EdgeInsets.only(top: 5, bottom: 5, right: 20),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: <Widget>[
                              Row(
                                children: <Widget>[
                                  FutureBuilder(
                                    future: DatabaseService("").getUserById(
                                      myContactsList.elementAt(index),
                                    ),
                                    builder: (context, snapshot) =>
                                        CircleAvatar(
                                      radius: 33,
                                      backgroundImage: snapshot
                                                  .data["imageUrl"] ==
                                              null
                                          ? snapshot.data["isMale"] == true
                                              ? AssetImage(
                                                  "assets/images/male.png")
                                              : AssetImage(
                                                  "assets/images/female.png")
                                          : AssetImage(
                                              "assets/images/male.png"),
                                    ),
                                  ),
                                  SizedBox(width: 10),
                                  Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      FutureBuilder<DocumentSnapshot>(
                                        future: DatabaseService("").getUserById(
                                          myContactsList.elementAt(index),
                                        ),
                                        builder: (context, snapshot) => Text(
                                          snapshot.data["displayName"],
                                          style: TextStyle(
                                            color: Colors.grey,
                                            fontSize: 18,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ),
                                      SizedBox(height: 5),
                                      Container(
                                        width:
                                            MediaQuery.of(context).size.width *
                                                0.45,
                                        child: Text(
                                          "Something N. $index ",
                                          style: TextStyle(
                                            color: Colors.blueGrey,
                                            fontSize: 18,
                                            fontWeight: FontWeight.w600,
                                          ),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                              Column(
                                children: <Widget>[
                                  Text(
                                    "TIME"
                                  ),
                                  Container(
                                    height: 20,
                                    width: 40,
                                    decoration: BoxDecoration(
                                      color: Theme.of(context).primaryColor,
                                      borderRadius: BorderRadius.circular(30),
                                    ),
                                    alignment: Alignment.center,
                                    child: Text(
                                      "NEW",
                                      style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 11,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
          ),
        ),
      ),
    );
  }
}

每次我与我的应用程序交互并在我的云 Firestore DB 中触发更改时,我都会使用StreamProvider(). 当发生这种情况时,我会得到下面列出的一些例外情况,但半秒后屏幕是固定的,我猜可能是新快照的原因(?)。以及下面列出的问题来自FutureBuilder()'si 使用。这是错误:

The following NoSuchMethodError was thrown building FutureBuilder<DocumentSnapshot>(dirty, state: _FutureBuilderState<DocumentSnapshot>#98dd9):
The method '[]' was called on null.
Receiver: null
Tried calling: []("imageUrl")

The relevant error-causing widget was: 
  FutureBuilder<DocumentSnapshot> file:///home/pss/Desktop/android/flutter_firebase_chat_app/lib/widgets/recent_chats.dart:90:35
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      RecentChats.build.<anonymous closure>.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:flutter_firebase_chat_app/widgets/recent_chats.dart:98:56)
#2      _FutureBuilderState.build (package:flutter/src/widgets/async.dart:740:55)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4663:28)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4546:15)
...
════════════════════════════════════════════════════════════════════════════════════════════════════

Another exception was thrown: NoSuchMethodError: The method '[]' was called on null.

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The method '[]' was called on null.
Receiver: null
Tried calling: []("displayName")
The relevant error-causing widget was: 
  FutureBuilder<DocumentSnapshot> file:///home/pss/Desktop/android/flutter_firebase_chat_app/lib/widgets/recent_chats.dart:114:39

这两行中的错误点: backgroundImage: snapshot.data["imageUrl"] == null & builder: (context, snapshot) => Text(snapshot.data["displayName"]

所以我不确定要诚实。我认为这是FutureBuilder()没有他们的原因,我没有例外。我是 Flutter 的新手,因此我们将不胜感激任何建议!

4

2 回答 2

1

您正在尝试调用_userSnapshot.data[]but datais null,您必须首先确保它_userSnapshot也不为空_userSnapshot.data
同时,考虑放置一个加载器,您可以使用CircularProgressIndicator它作为简单的启动,或者您可以使用Shimmer来自 pub.dev 的库来制作一些很酷的占位符加载动画(如 Facebook)。

于 2020-10-14T07:44:13.373 回答
0

您可以将 initialData 参数设置为 StreamProvider,当流尚未发出任何内容时使用此数据。在访问其中一个键之前,您还应该检查 _userSnapshot.data != null 。

于 2020-10-10T22:29:50.183 回答