RenderFlex在底部溢出了99729像素

时间:2020-08-06 17:10:14

标签: flutter flutter-test

谁能告诉我为什么我收到此错误?我正在构建一个聊天应用程序,可以在其中显示消息时间和消息文本。但是,当我发送一条消息时,它会向我显示错误:

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building StreamBuilder<QuerySnapshot>(dirty, state: _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>>#63fa3):
The getter 'seconds' was called on null.
Receiver: null
Tried calling: seconds

The relevant error-causing widget was: 
  StreamBuilder<QuerySnapshot> file:///J:/My%20Documents/flutter/flash-chat-flutter/lib/screens/chat_screen.dart:107:12
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      MessageStream.build.<anonymous closure> (package:flash_chat/screens/chat_screen.dart:127:28)
#2      StreamBuilder.build (package:flutter/src/widgets/async.dart:514:81)
#3      _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:129:48)
#4      StatefulElement.build (package:flutter/src/widgets/framework.dart:4681:28)
...
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════════════════════════
A RenderFlex overflowed by 99729 pixels on the bottom.
The relevant error-causing widget was: 
  Column file:///J:/My%20Documents/flutter/flash-chat-flutter/lib/screens/chat_screen.dart:57:16
════════════════════════════════════════════════════════════════════════════════════════════════════

这是我的代码

import 'package:flutter/material.dart';
import 'package:flash_chat/constants.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:intl/intl.dart';

final _fireStore = Firestore.instance;
final _auth = FirebaseAuth.instance;
FirebaseUser loggedInUser;

class ChatScreen extends StatefulWidget {
  static String id = 'chat_screen';

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

class _ChatScreenState extends State<ChatScreen> {
  final messageTextController = TextEditingController();
  String messageText;
  @override
  void initState() {
    super.initState();
    getCurrentUser();
  }

  void getCurrentUser() async {
    try {
      final user = await _auth.currentUser();
      if (user != null) {
        loggedInUser = user;
        print(loggedInUser.email);
      }
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        leading: null,
        actions: <Widget>[
          IconButton(
              icon: Icon(Icons.close),
              onPressed: () {
                _auth.signOut();
                Navigator.pop(context);
              }),
        ],
        title: Text('⚡️Chat'),
        backgroundColor: Colors.lightBlueAccent,
      ),
      body: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            MessageStream(),
            Container(
              decoration: kMessageContainerDecoration,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Expanded(
                    child: TextField(
                      controller: messageTextController,
                      style: TextStyle(
                        color: Colors.black,
                      ),
                      onChanged: (value) {
                        messageText = value;
                      },
                      decoration: kMessageTextFieldDecoration,
                    ),
                  ),
                  FlatButton(
                    onPressed: () async {
                      messageTextController.clear();
                      final fieldValue = FieldValue.serverTimestamp();
                      await _fireStore.collection('messages').add({
                        "sender": loggedInUser.email,
                        "text": messageText,
                        "messageTime": fieldValue,
                      });
                    },
                    child: Text(
                      'Send',
                      style: kSendButtonTextStyle,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class MessageStream extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: _fireStore
          .collection('messages')
          .orderBy('messageTime', descending: false)
          .snapshots(),
      builder: (context, snapshot) {
        var timeDate;
        if (!snapshot.hasData) {
          return Center(
            child: CircularProgressIndicator(
              backgroundColor: Colors.lightBlueAccent,
            ),
          );
        } else {
          final messages = snapshot.data.documents.reversed;
          List<MessageBubble> messageBubbles = [];
          for (var message in messages) {
            final messageText = message.data['text'];
            final sender = message.data['sender'];
            Timestamp serverTime = message.data['messageTime'];
            if (serverTime.seconds != null && serverTime.nanoseconds != null) {
              timeDate = Timestamp(serverTime.seconds, serverTime.nanoseconds)
                  .toDate();
            }
            var time = DateFormat.jm().format(timeDate);
            final currentUser = loggedInUser.email;
            final messageBubble = MessageBubble(
              message: messageText,
              sender: sender,
              isMe: currentUser == sender,
              messageTime: time.toString(),
            );
            messageBubbles.add(messageBubble);
          }
          return Expanded(
            child: ListView(
              reverse: true,
              children: messageBubbles,
            ),
          );
        }
      },
    );
  }
}

class MessageBubble extends StatelessWidget {
  MessageBubble({this.sender, this.message, this.isMe, this.messageTime});
  String message;
  String sender;
  bool isMe;
  String messageTime;
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment:
          isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
      children: <Widget>[
        Padding(
          padding: isMe
              ? EdgeInsets.only(
                  right: 20,
                )
              : EdgeInsets.only(
                  left: 20,
                ),
          child: Text(
            sender,
            style: TextStyle(color: Colors.black45),
          ),
        ),
        Padding(
          padding: EdgeInsets.symmetric(
            horizontal: 10,
            vertical: 5,
          ),
          child: Material(
            borderRadius: isMe
                ? BorderRadius.only(
                    topLeft: Radius.circular(20),
                    bottomLeft: Radius.circular(20),
                    bottomRight: Radius.circular(20),
                  )
                : BorderRadius.only(
                    topRight: Radius.circular(20),
                    bottomLeft: Radius.circular(20),
                    bottomRight: Radius.circular(20),
                  ),
            elevation: 5,
            color: isMe ? Colors.lightBlueAccent : Colors.white,
            child: Padding(
              padding: EdgeInsets.symmetric(
                horizontal: 15,
                vertical: 15,
              ),
              child: Column(
                children: <Widget>[
                  Text(
                    message,
                    style: TextStyle(
                      fontSize: 15,
                    ),
                  ),
                  Text(
                    messageTime,
                    style: TextStyle(
                      fontSize: 10,
                      color: Colors.black54,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        SizedBox(
          height: 10,
        ),
      ],
    );
  }
}

1 个答案:

答案 0 :(得分:1)

问题是有很多消息,但是在聊天屏幕中包含它们的Column无法滚动,请在Column中将SingleChildScrollView包装在聊天屏幕中:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        leading: null,
        actions: <Widget>[
          IconButton(
              icon: Icon(Icons.close),
              onPressed: () {
                _auth.signOut();
                Navigator.pop(context);
              }),
        ],
        title: Text('⚡️Chat'),
        backgroundColor: Colors.lightBlueAccent,
      ),
      body: SafeArea(
        child: SingleChildScrollView( // this is new
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              MessageStream(),
...