简体   繁体   中英

Streambuilder error in SingleChildScrollView flutter

This is the streambuilder wrapped under SingleChildScrollView inside the body of scaffold. Scroll View is not working after streambuilder is placed under SingleChildScrollView. StreamBuilder fetches data from firebase through cloud firestore.

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, it is a stateless widget which will display the comments.

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'),
    );
  }
}

Error shown in console

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

It is Happening Because your Widget Structure due to which error is there is like

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

Now See This Error Which you are getting , it is saying that it is error regarding the size , Wrap your Column in Some other widget rather than Expanded

It seems that you need space to place your ListView inside the Column(). Remove the Expanded widget, and replace it with Container. For example:

Container( height: 100, child: ListView( children: _commentBubbleWidget ),)

But, I don't recommend the solution above for you. That's too bad for the UI (just my opinion). Because, you use ListView inside Column. By using this way, you have to decide height of the ListView. Don't forget, the phones' size are vary.

Better to separate the ListView, and place your textfield in BottomNavigationBar. This is mine:

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,
                    ))
          ],
        ),
      ),
    ),
  ),
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM