SingleChildScrollView抖动中的Streambuilder错误

时间:2020-09-03 11:08:54

标签: flutter

这是包裹在脚手架内的SingleChildScrollView下的streambuilder。将streambuilder放在SingleChildScrollView下后,滚动视图不起作用。 StreamBuilder通过Cloud Firestore从Firebase获取数据。

body: Container(
            child: SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                    Expanded(
                    child: StreamBuilder<QuerySnapshot>(
                      stream: Firestore.instance
                          .collection(
                              'blogsDatabase/${widget.blogUIDInFirebase}/comments')
                          .snapshots(),
                      builder: (context, snapshot) {
                        if (!snapshot.hasData) {
                          return Center(child: CircularProgressIndicator());
                        }
                        final _commentsFetched = snapshot.data.documents;
                        List<CommentBubble> _commentBubbleWidget = [];
    
                        for (var comment in _commentsFetched) {
                          _commentBubbleWidget.add(
                            CommentBubble(
                              name: comment.data['name'],
                              comment: comment.data['comment'],
                            ),
                          );
                        }
                        return Expanded(
                          child: ListView(
                            children: _commentBubbleWidget
                          ),
                        );
                      },
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.all(10),
                    child: Material(
                      shadowColor: Colors.orange,
                      child: TextField(
                        onChanged: (value) {
                          readerAddComment = value;
                        },
                        keyboardType: TextInputType.emailAddress,
                        decoration:
                            kRegDetailFieldDeco.copyWith(hintText: 'Add comment'),
                      ),
                    ),
                  ),
                  FlatButton(
                      onPressed: () {
                        if (_nameReader != null &&
                            widget.readerEmail != null &&
                            readerAddComment != null) {
                          Firestore.instance
                              .collection(
                                  'blogsDatabase/${widget.blogUIDInFirebase}/comments')
                              .document()
                              .setData(
                            {
                              'name': _nameReader,
                              'email': widget.readerEmail,
                              'comment': readerAddComment,
                            },
                          );
                        }
                      },
                      child: Text('Add comment')),
                ],
              ),
            ),
          ),

Comment Bubble Class,它是一个无状态的小部件,将显示注释。

class CommentBubble extends StatelessWidget {
  final String name;
  final String comment;

  CommentBubble({this.name, this.comment});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(10.0),
      child: Text('$name --- $comment'),
    );
  }
}

控制台中显示错误

RenderBox was not laid out: RenderRepaintBoundary#dd879 relayoutBoundary=up1 NEEDS-PAINT
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1694 pos 12: 'hasSize'

2 个答案:

答案 0 :(得分:0)

正在发生,因为由于错误而导致的小部件结构类似

-Container
  -SingleChildScrollView  
    -Expanded
       -Column
         -Expanded
             -Expanded
               -ListView

现在看到此错误,您正在得到它,这是关于大小的错误,将列包装在其他小部件中,而不是展开

答案 1 :(得分:-1)

似乎您需要空间将ListView放在Column()内。 删除“扩展”小部件,然后将其替换为“容器”。 例如:

容器( 高度:100, 子级:ListView( 子代:_commentBubbleWidget ),)

但是,我不建议您使用上述解决方案。这对于UI来说太糟糕了(我个人认为)。因为,您在Column中使用ListView。通过这种方式,您必须确定ListView的高度。不要忘记,手机的大小各不相同。

更好地分隔ListView,并将文本字段放置在BottomNavigationBar中。 这是我的:

Scaffold(
  appBar: AppBar(
    title: textCustom(
        'Review ${widget.destination}', Colors.black87, 20, 'Hind'),
    leading: IconButton(
        icon: Icon(
          Icons.arrow_back_ios,
        ),
        onPressed: () {
          Navigator.pop(context);
        }),
    iconTheme: IconThemeData(color: Colors.black87, size: 10),
    backgroundColor: Colors.transparent,
    elevation: 0.0,
  ),
  body: Padding(
    padding: const EdgeInsets.all(8.0),
    child: StreamBuilder<QuerySnapshot>(
        stream: kategori
            .document(widget.kategori)
            .collection(widget.subKategori)
            .document(widget.docId)
            .collection("review")
            .orderBy("timeStamp", descending: true)
            .snapshots(),
        builder:
            (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (snapshot.hasError) return new Text('${snapshot.error}');
          if (snapshot.data == null)
            return Center(
                child: textCustom(
                    'Loading...', Colors.black87, 14, 'Montserrat'));

          final review= snapshot.data.documents;
          return snapshot.data.documents.isNotEmpty
              ? ListView.builder(
                  itemCount: review.length,
                  itemBuilder: (context, index) {
                    return Comment(
                      name: review[index]['name'],
                      profilePhoto: review[index]['foto'],
                      comments: review[index]['review'],
                      date: (review[index]['timeStamp'] != null)
                          ? DateFormat.yMMMd().format(DateTime.parse(
                              review[index]['timeStamp']
                                  .toDate()
                                  .toString(),
                            ))
                          : '',
                    );
                  })
              : Center(child: Text('Empty'));
        }),
  ),
  bottomNavigationBar: Padding(
    padding: MediaQuery.of(context).viewInsets,
    child: BottomAppBar(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 8.0),
        child: Row(
          children: <Widget>[
            Expanded(
                child: TextField(
              controller: textMessageController,
              onChanged: (text) {
                input = text;
                setState(() {
                  enableButton = text.isNotEmpty;
                });
              },
              textCapitalization: TextCapitalization.sentences,
              maxLines: null,
              style: TextStyle(
                  color: Colors.black87,
                  fontSize: 16,
                  fontFamily: 'Montserrat'),
              decoration: InputDecoration(
                enabledBorder: UnderlineInputBorder(
                  borderSide: new BorderSide(color: Colors.white),
                  borderRadius: new BorderRadius.circular(8.0),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: new BorderSide(color: Colors.white),
                  borderRadius: new BorderRadius.circular(8.0),
                ),
                contentPadding:
                    EdgeInsets.only(left: 16.0, bottom: 16.0, top: 16.0),
                hintText: 'Write some review',
              ),
            )),
            SizedBox(
              width: 8.0,
            ),
            enableButton
                ? IconButton(
                    onPressed: handleSendMessage,
                    icon: Icon(
                      Icons.send,
                      color: Color(0xFFDB5C48),
                    ))
                : IconButton(
                    onPressed: () {},
                    icon: Icon(
                      Icons.send,
                      color: Colors.grey,
                    ))
          ],
        ),
      ),
    ),
  ),
);