簡體   English   中英

錯誤:正文可能正常完成,導致返回“null”,但返回類型是不可為空的類型

[英]error: The body might complete normally, causing 'null' to be returned, but the return type is a non-nullable type

我正在使用 FireBase 構建一個 flashChat 應用程序。它基本上是一個可用於發送消息的聊天應用程序。消息存儲在 FireBase 集合中。我們必須檢索消息並將其顯示在屏幕上。

要顯示內容(快照),我正在使用 Streams。 我收到以下錯誤

錯誤:正文可能正常完成,導致返回“null”,但返回類型可能是不可為空的類型。 (body_might_complete_normally 在 [flashchat1] lib\screens\chat_screen.dart:80)

這是我的代碼:-

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flashchat1/constants.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class ChatScreen extends StatefulWidget {
  static String id='Chat_Screen';
  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  final _fireStore = FirebaseFirestore.instance;//an instance of fireBase store that stored data created
  final _auth = FirebaseAuth.instance;//instance/object of fireBase auth that authorizes users is created
  late User loggedInUser;//LoggedInUser is of type FireBase user(now changed to user)
  late String messageText;
  @override
  void initState()
  {
    super.initState();
    getCurrentUser();//calling the getCurrentUser
  }
  void getCurrentUser()
  async{
    try
    {
      final user= await _auth.currentUser;//get the current user id/name.Also currentUser return a future so make it async by adding await and async keywords
      if(user!=null)
      {
        loggedInUser=user ;//LoggedInUser = user contains email of the users
        print(loggedInUser.email);
      }

    }
    catch(e)
    {
      print(e);
    }
  }// Under collection there is documents.Inside documents there are fields like type ,values etc.These fields contain our information
    Future<void> messageStream()//Using a stream it becomes very easy .U just need to click once after you run the app .Then u will be done.
    async {//The snapShot here is FireBase's Query SnapShot
      await for(var snapshot in _fireStore.collection('messages').snapshots()){//make a variable snapshot to store the entire items of the collection in fireBase (Look at the fireBase console there is a collection called messages).This collection takes the snapshot of all the iteams (not literal snapshot .Think it like a snapShot)
        for(var message in snapshot.docs)//make a variable message to access the snapShot.docs .(docs stands for Documentation.Look at the fireBase console)
        print(message.data());
      }
    }
  void getMessages()//(The problem with this is that we need to keep clicking on the onPressed button every single time the new message is sent .So it is not convinient
  async {
    final messages = await _fireStore.collection('messages').get();//to retrieve the data from fire base we are creating a variable message
   messages.docs;//retreive the data from document section under the collection in firestore
    for(var message in messages.docs)//since it is a messages.docs is a list we need to loop through it
       {
        print(message.data());//print the data its messge.data()
     }
  }
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: null,
        actions: <Widget>[
          IconButton(
              icon: Icon(Icons.close),
              onPressed: () {
                messageStream();
                //_auth.signOut();
                //Navigator.pop(context);
                //Implement logout functionality
              }),
        ],
        title: Text('⚡️Chat'),
        backgroundColor: Colors.lightBlueAccent,
      ),
      body: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            StreamBuilder(
              stream:_fireStore.collection('messages').snapshots(),
              builder: (context, AsyncSnapshot snapshot) {//This is Flutter's Async snapShot
                if(snapshot.hasData){//flutters async snapshot contains a query snapshot
                  final messages = snapshot.data.docs;
                  List<Text> messageWidgets = [];
                  for(var  message in messages)//Loop through the messages
                    {
                      final messageText = message.data['text'];//retrieve the data under the text field in message collection
                      final messageSender = message.data['Sender'];//retrieve the data under the Sender field in message collection
                      final messageWidget = Text('$messageText from $messageSender');
                      messageWidgets.add(messageWidget);
                      }
                      return Column(
                        children: messageWidgets,
                      );
                    }
                },
            ),
            Container(
              decoration: kMessageContainerDecoration,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Expanded(
                    child: TextField(
                      onChanged: (value) {
                        messageText=value;//Whatever you chat will be stored in the variable String variable messageText
                      },
                      decoration: kMessageTextFieldDecoration,
                    ),
                  ),
                  FlatButton(
                    onPressed: () {
                      _fireStore.collection('messages').add({
                        'text': messageText,//add the messages sent to fireStore under the messages object that we created manually
                        'Sender': loggedInUser.email,//add the current users email to the sender field
                      },);
                    },//goal is to send the data that we type here to the fireStore cloud
                    child: Text(
                      'Send',
                      style: kSendButtonTextStyle,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
} 

當 if 條件未解決時,您不會在 StreamBuilder 中返回任何內容...

只需添加一個其他的,比如... SizedBox.shrink()或任何你需要的

或者返回一個空Column

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM