Flutter: отображение всех пользователей из firestore

#flutter #dart #google-cloud-firestore

#трепетание #dart #google-облако-firestore

Вопрос:

Я хочу отобразить всех пользователей моей базы данных firestore в виде списка (пытаюсь разработать функцию интерфейса чата), отображая статус устройства Есть ли в flutter какой-либо пакет, который можно вызвать для создания интерфейса чата?

ниже я пробовал до сих пор:

chat_interface.dart

 import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttershare/models/user.dart';
import 'package:fluttershare/widgets/header.dart';
import 'package:fluttershare/widgets/progress.dart';
import 'home.dart';

class Chats extends StatefulWidget {
  final String chatUserId;
  Chats({this.chatUserId});
  @override
  _ChatState createState() => _ChatState(
    chatUserId:this.chatUserId,
  );
}

class _ChatState extends State<Chats> {

  TextEditingController chatController = TextEditingController();

  Future<QuerySnapshot> chatUsers = usersRef.getDocuments();

  final String chatUserId;
  _ChatState({this.chatUserId});
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    userDisplay();
  }
  @override
  Widget build(BuildContext context) {
  }
  userDisplay(){
    return FutureBuilder(
      future: chatUsers,
      builder: (context,snapshot){
        if(!snapshot.hasData){
          return circularProgress();
        }
        List<ChatResult> results = [];
        snapshot.data.documents.forEach((doc){
        User user = User.fromDocument(doc);
        ChatResult result = ChatResult(user);
        results.add(result);
        });
        return ListView(
            children: results,
        );
      }
    );
  }
}

class ChatResult extends StatelessWidget {
  final User user;
  ChatResult(this.user);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: header(context, titleText: 'GupShup'),
      body: Container(
      color:Colors.white,
      child: Column(
        children: <Widget>[
            ListTile(
              leading: CircleAvatar(
                backgroundColor: Colors.grey,
                backgroundImage: CachedNetworkImageProvider(user.photoUrl),
              ),
              title: Text(user.displayName,style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),),
              subtitle: Text('Message'),
              ),
          Divider(
            height: 2.0,
            color: Colors.white54,
          ),
        ],
      ),
    ),
    );
  }
}
  

Я получаю эту ошибку

 ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following assertion was thrown building Chats(dirty, dependencies: [_InheritedTheme,
_LocalizationsScope-[GlobalKey#4c382]], state: _ChatState#e9c68):
A build function returned null.
The offending widget is:
  Chats
Build functions must never return null.
To return an empty space that causes the building widget to fill available room, return
"Container()". To return an empty space that takes as little room as possible, return
"Container(width: 0.0, height: 0.0)".
The relevant error-causing widget was:
  Chats
[38;5;248m  [39;49m
 libwidgetsheader.dart
When the exception was thrown, this was the stack:
[38;5;244m#0      debugWidgetBuilderValue.<anonymous closure>[39;49m 
 package:flutter/…/widgets/debug.dart
[38;5;244m#1      debugWidgetBuilderValue[39;49m 
 package:flutter/…/widgets/debug.dart
[38;5;244m#2      ComponentElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#3      StatefulElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#4      Element.rebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#5      StatefulElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#6      Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#7      SingleChildRenderObjectElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#8      Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#9      ComponentElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#10     Element.rebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#11     StatelessElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#12     Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#13     SingleChildRenderObjectElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#14     Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#15     SingleChildRenderObjectElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#16     Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#17     ComponentElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#18     StatefulElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#19     Element.rebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#20     StatefulElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#21     Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#22     SingleChildRenderObjectElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#23     Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#24     SingleChildRenderObjectElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#25     Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#26     ComponentElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#27     StatefulElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#28     Element.rebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#29     StatefulElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#30     Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#31     ComponentElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#32     Element.rebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#33     StatelessElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#34     Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#35     ComponentElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#36     StatefulElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#37     Element.rebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#38     StatefulElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#39     Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#40     SingleChildRenderObjectElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#41     Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#42     ComponentElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#43     Element.rebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#44     ProxyElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#45     _InheritedNotifierElement.update[39;49m 
 package:flutter/…/widgets/inherited_notifier.dart
[38;5;244m#46     Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#47     SingleChildRenderObjectElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#48     Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#49     ComponentElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#50     StatefulElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#51     Element.rebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#52     StatefulElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#53     Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#54     ComponentElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#55     Element.rebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#56     ProxyElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#57     Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#58     ComponentElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#59     StatefulElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#60     Element.rebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#61     StatefulElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#62     Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#63     ComponentElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#64     Element.rebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#65     StatelessElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#66     Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#67     SingleChildRenderObjectElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#68     Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#69     ComponentElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#70     Element.rebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#71     ProxyElement.update[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#72     Element.updateChild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#73     ComponentElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#74     StatefulElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#75     Element.rebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#76     BuildOwner.buildScope[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#77     WidgetsBinding.drawFrame[39;49m 
 package:flutter/…/widgets/binding.dart
[38;5;244m#78     RendererBinding._handlePersistentFrameCallback[39;49m 
 package:flutter/…/rendering/binding.dart
[38;5;244m#79     SchedulerBinding._invokeFrameCallback[39;49m 
 package:flutter/…/scheduler/binding.dart
[38;5;244m#80     SchedulerBinding.handleDrawFrame[39;49m 
 package:flutter/…/scheduler/binding.dart
[38;5;244m#81     SchedulerBinding.scheduleWarmUpFrame.<anonymous closure>[39;49m 
 package:flutter/…/scheduler/binding.dart
(elided 4 frames from class _RawReceivePortImpl, class _Timer, and dart:async-patch)
════════════════════════════════════════════════════════════════════════════════════════════════════

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
[38;5;244mThe following assertion was thrown building Chats(dirty, dependencies: [_InheritedTheme, _LocalizationsScope-[GlobalKey#4c382]], state: _ChatState#e9c68):[39;49m
A build function returned null.

[38;5;244mThe offending widget is: Chats[39;49m
[38;5;244mBuild functions must never return null.[39;49m

[38;5;248mTo return an empty space that causes the building widget to fill available room, return "Container()". To return an empty space that takes as little room as possible, return "Container(width: 0.0, height: 0.0)".[39;49m

[38;5;244mThe relevant error-causing widget was[39;49m
    [38;5;248mChats[39;49m 
 libwidgetsheader.dart
[38;5;244mWhen the exception was thrown, this was the stack[39;49m
[38;5;244m#0      debugWidgetBuilderValue.<anonymous closure>[39;49m 
 package:flutter/…/widgets/debug.dart
[38;5;244m#1      debugWidgetBuilderValue[39;49m 
 package:flutter/…/widgets/debug.dart
[38;5;244m#2      ComponentElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#3      StatefulElement.performRebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m#4      Element.rebuild[39;49m 
 package:flutter/…/widgets/framework.dart
[38;5;244m...[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m
Reloaded 0 of 1172 libraries in 197ms.
  

Кто-нибудь может мне помочь с этим? Я думаю, что я не могу правильно вызывать методы.

Редактировать: я немного изменил свой код

 import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttershare/models/user.dart';
import 'package:fluttershare/widgets/header.dart';
import 'package:fluttershare/widgets/progress.dart';
import 'home.dart';

class Chats extends StatefulWidget {
  final String chatUserId;
  Chats({this.chatUserId});
  @override
  _ChatState createState() => _ChatState(
    chatUserId:this.chatUserId,
  );
}

class _ChatState extends State<Chats> {

  TextEditingController chatController = TextEditingController();

  Future<QuerySnapshot> chatUsers = usersRef.document(currentUser.id).collection('users').limit(100).getDocuments();

  final String chatUserId;
  _ChatState({this.chatUserId});
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    userDisplay();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: header(context,titleText: 'GupShup'),
      body: chatUsers != null ?  userDisplay() : Text('Users'),
    );
  }
  userDisplay(){
    return StreamBuilder(
      stream: usersRef.document(widget.chatUserId).collection('users').snapshots(),
      builder: (context,snapshot){
        if(!snapshot.hasData){
          return circularProgress();
        }
        List<ChatResult> results = [];
        snapshot.data.documents.forEach((doc){
        User user = User.fromDocument(doc);
        ChatResult result = ChatResult(user);
        results.add(result);
        });
        return ListView(
            children: results,
        );
      }
    );
  }
}

class ChatResult extends StatelessWidget {
  final User user;
  ChatResult(this.user);
  @override
  Widget build(BuildContext context) {
    return Container(
      color:Colors.white,
      child: Column(
        children: <Widget>[
           GestureDetector(
            onTap: () => print('show message'),
            child:
            ListTile(
              leading: CircleAvatar(
                backgroundColor: Colors.grey,
                backgroundImage: CachedNetworkImageProvider(user.photoUrl),
              ),
              title: Text(user.displayName,style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),),
              subtitle: Text('Message'),
              ),
           ),
          Divider(
            height: 2.0,
            color: Colors.white54,
          ),
        ],
      ),
    );
  }
}
  

Теперь я получаю пустой экран с панелью приложений

После редактирования эмулятор показывает это

Кто-нибудь может мне сейчас помочь?

Ответ №1:

Попробуйте вернуть виджет из метода сборки

   @override
  Widget build(BuildContext context) {
     return FutureBuilder(...);
  }
  

Комментарии:

1. Я немного изменил свой код, можете посмотреть?