【问题标题】:Flutter Listview of items as divider with Listview of items Size problemsFlutter Listview 项目作为分隔符与项目 Listview 大小问题
【发布时间】:2018-04-24 23:33:01
【问题描述】:

我有一个工作页面,它是使用 Listview.builder 的消息的动态列表视图。 itembuilder 调用创建卡片的小部件。我想要做的是将第一个列表更改为一个分隔符,它将是一个日期,然后将在该日期之前调用一个项目列表。正在创建所有数据调用和列表,但不断出现 hasSize is not true 错误并且看不到大小问题所在,我只是使用了相同的布局。

不确定要显示哪些代码以获得帮助,所以如果您有想法以及可能需要查看哪些代码,请告诉我。

这是改变之前有效的开始:

var _children = <Widget>[

  new Expanded(
    child: new RefreshIndicator(
      child: new ListView.builder(
        itemBuilder: _divBuilder,
        itemCount: listcount,
      ),
      onRefresh: _onRefresh,
    ),
  ),
  new Stack(
    alignment: Alignment.centerRight,
    children: <Widget>[
      new TextField(
        decoration: const InputDecoration(
          hintText: 'Chat Reply',
          labelText: 'Chat Reply:',
        ),
        autofocus: false,
        focusNode: _focusnode,
        maxLines: 2,
        controller: _newreplycontroller,
        keyboardType: TextInputType.url,
      ),
      new IconButton(
        icon: new Icon(Icons.send),
        onPressed: _sendReply,
        alignment: Alignment.centerRight,
      )
    ],
  ),
];
return new Scaffold(
  appBar: new AppBar(
    title: mytitle,
    actions: getAppBarActions(context),
  ),
  body: new Column(
    mainAxisSize: MainAxisSize.max,
    children: _children,
  ),
);

现在我有 2 个正在使用的小部件。

    class MyChatWidget extends StatefulWidget {
  MyChatWidget({Key key, this.datediv, this.msgkey}) : super(key: key);

  final DateTime datediv;
  final String msgkey;

  @override
  _MyChatWidgetState createState() => new _MyChatWidgetState();
}

class _MyChatWidgetState extends State<MyChatWidget> {
  List messagelist;
  int messagecount = 0;
  var jsonCodec = const JsonCodec();

  _getMessages() async {
    var _url = 'http://$baseurl/csapi/messages/getbydate';
    DateChatMessage dcm = new DateChatMessage(widget.msgkey, widget.datediv.toString());
    var json = jsonCodec.encode(dcm);
    var http = createHttpClient();
    var response = await http.post(_url, headers: getAuthHeader(), body: json);

    var messages = await jsonCodec.decode(response.body);

    if (mounted) {
      setState(() {
        messagelist = messages.toList();
        messagecount = messagelist.length;
        //replysub = 'Re: ' + chatlist[0]['sub'];
      });
    }
  }

  @override
  void initState() {
    super.initState();
    //controller = new TabController(length: 4, vsync: this);
    _getMessages();
  }

  @override
  Widget build(BuildContext context) {
    var _children = <Widget>[
      new Divider(height: 5.0,color: Colors.red,),
      new Expanded(
        child: new ListView.builder(
          itemBuilder: _itemBuilder,
          itemCount: messagecount,
        ),
      ),

    ];


    return new Column(
        mainAxisSize: MainAxisSize.min,
        children: _children,
      );
  }

  Widget _itemBuilder(BuildContext context, int index) {
    ChatMessage mychat = getChat(index);
    return new ChatWidget(
      mychat: mychat,
    );
  }

  ChatMessage getChat(int index) {
    //prefs.setInt('pid', myReferralList[index]['pid']);
    return new ChatMessage(
      messagelist[index]['msgkey'],
      messagelist[index]['referralname'],
      messagelist[index]['sub'],
      messagelist[index]['oid'],
      messagelist[index]['oname'],
      messagelist[index]['pid'],
      messagelist[index]['pname'],
      messagelist[index]['sender'],
      messagelist[index]['sendname'],
      messagelist[index]['receiver'],
      messagelist[index]['receivename'],
      messagelist[index]['message'],
      messagelist[index]['submitdate'],
      messagelist[index]['pgrpid'],
      messagelist[index]['prid'],
      messagelist[index]['fcmtoken'],
    );
  }
}


class ChatWidget extends StatefulWidget {
  ChatWidget({Key key, this.mychat}) : super(key: key);

  final ChatMessage mychat;

  @override
  _ChatWidgetState createState() => new _ChatWidgetState();
}

class _ChatWidgetState extends State<ChatWidget> {
  @override
  Widget build(BuildContext context) {
    DateTime submitdate = DateTime.parse(widget.mychat.submitdate).toLocal();

    return new Card(
      child: new Container(
        width: 150.0,
        padding: new EdgeInsets.all(10.0),
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            new Row(
              children: <Widget>[
                new Text(
                  widget.mychat.sendname,
                  style: new TextStyle(
                      fontSize: 15.0, fontWeight: FontWeight.bold),
                ),
                new Text(' @ '),
                new Text(new DateFormat.yMd().add_Hm().format(submitdate)),
                //new Text(submitdate.toLocal().toString())
              ],
            ),

            //new Text(widget.mychat.receivename,style: new TextStyle(fontSize: 15.0, fontWeight: FontWeight.bold),),
            //new Text(new DateFormat.yMd().add_Hm().format(submitdate)),
            new Text('${widget.mychat.message}'),
          ],
        ),
      ),
    );
    /*return new ListTile(
      leading: new CircleAvatar(child: new Text(widget.mychat.oname[0])),
      title: new Text(widget.mychat.referralname),
      subtitle: new Text(new DateFormat.yMd().add_Hm().format(submitdate)),
      trailing: new Text(widget.mychat.sendname),
      onTap: _onTap,
    );*/
  }



void _onTap() {
    Route route = new MaterialPageRoute(
      settings: new RouteSettings(name: "/chats/chatconvodetil"),
      builder: (BuildContext context) =>
      new ChatConvoDetail(mychat: widget.mychat),
    );
    Navigator.of(context).push(route);
  }
}

任何指导都会很棒


完整的错误堆栈

══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY 

╞═════════════════════════════════════════════════════════
RenderFlex children have non-zero flex but incoming height constraints are unbounded.
When a column is in a parent that does not provide a finite height constraint, for example if it is
in a vertical scrollable, it will try to shrink-wrap its children along the vertical axis. Setting a
space in the vertical direction.
These two directives are mutually exclusive. If a parent is to shrink-wrap its child, the child
cannot simultaneously expand to fit its parent.
Consider setting mainAxisSize to MainAxisSize.min and using FlexFit.loose fits for the flexible
themselves to less than the infinite remaining space they would otherwise be forced to take, and
then will cause the RenderFlex to shrink-wrap the children rather than expanding to fit the maximum
constraints provided by the parent.
The affected RenderFlex is:
RenderFlex#d88d8 relayoutBoundary=up8 NEEDS-LAYOUT NEEDS-PAINT
The creator information is set to:
Column ← MyChatWidget ← RepaintBoundary-[<0>] ← NotificationListener<KeepAliveNotification> ←
KeepAlive ← AutomaticKeepAlive ← SliverList ← ShrinkWrappingViewport ← _ScrollableScope ←
IgnorePointer-[GlobalKey#ac8f6] ← Listener ← _GestureSemantics ← ⋯
See also: https://flutter.io/layout/
https://flutter.io/debugging/#rendering-layer
http://docs.flutter.io/flutter/rendering/debugDumpRenderTree.html
If none of the above helps enough to fix this problem, please don't hesitate to file a bug:
https://github.com/flutter/flutter/issues/new

When the exception was thrown, this was the stack:

The following RenderObject was being processed when the exception was fired:
RenderFlex#d88d8 relayoutBoundary=up8 NEEDS-LAYOUT NEEDS-PAINT
creator: Column ← MyChatWidget ← RepaintBoundary-[<0>] ←
NotificationListener<KeepAliveNotification> ← KeepAlive ← AutomaticKeepAlive ← SliverList ←
ShrinkWrappingViewport ← _ScrollableScope ← IgnorePointer-[GlobalKey#ac8f6] ← Listener ←
_GestureSemantics ← ⋯
size: MISSING
direction: vertical
mainAxisAlignment: start
mainAxisSize: min
crossAxisAlignment: center
verticalDirection: down
RenderConstrainedBox#1d682 relayoutBoundary=up9 NEEDS-PAINT
RenderPositionedBox#d9c42 relayoutBoundary=up10 NEEDS-PAINT
RenderPadding#c357c relayoutBoundary=up11 NEEDS-PAINT
RenderConstrainedBox#3ad51 relayoutBoundary=up12 NEEDS-PAINT
RenderDecoratedBox#e68e0 relayoutBoundary=up13 NEEDS-PAINT
RenderSemanticsGestureHandler#83b48 NEEDS-LAYOUT NEEDS-PAINT
RenderPointerListener#9b129 NEEDS-LAYOUT NEEDS-PAINT
RenderIgnorePointer#aa9c2 NEEDS-LAYOUT NEEDS-PAINT
RenderShrinkWrappingViewport#f658c NEEDS-LAYOUT NEEDS-PAINT
RenderSliverList#7b88e NEEDS-LAYOUT NEEDS-PAINT
════════════════════════════════════════════════════════════════════════════════════════════════════
Another exception was thrown: 'package:flutter/src/rendering/box.dart': Failed assertion: line 1433 pos 12: 'hasSize': is not true.
Another exception was thrown: 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 455 pos 12: 'child.hasSize': is not true.

【问题讨论】:

    标签: flutter


    【解决方案1】:

    'hasSize': is not true 通常与 ColumnRow 的大小不受限制有关,因此 Flutter 无法识别应该在多少空间内渲染这两个小部件。但是,在您的情况下,我相信这是由于通过您的ListView.builder,尝试将ListView.builder 中的shrinkWrap 属性设置为true,看看它是否解决了您的问题,否则是由ColumnRow 引起的。不过我想设置shrinkWrap:true应该可以解决,所以先试试吧。

    在详细了解该错误后,似乎将Expanded 更改为Flexible 已解决此问题。

    【讨论】:

    • shrinkwrap 没有解决它,同样的错误,我输入了我拥有的 2 个 listview.builders,我只有列和 1 行,如您所见,但我已经设置了所有可能的大小我可以找到,但还是一样。
    • 我刚刚注意到你有一个ListView 作为Column 的孩子?
    • 我在学习 Flutter 时从其中一个 Flutter 示例中得到了这一点。我经常使用它,它允许我拥有一个小部件变量并将它们应用到脚手架或其他返回显示。你有其他方法的建议吗?谢谢
    • 你想用你的布局做什么?我的意思是你为什么在 Column 中使用 ListView ?
    • 宾果游戏,如果我将第二个 Expanded 更改为 FLexible 并且它起作用了。感谢您的帮助,它完全按照我的预期工作。
    【解决方案2】:

    使用 Flexible 而不是 Expanded。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 2021-05-18
      相关资源
      最近更新 更多