ListView.separated returns 对空值错误使用了空检查

ListView.separated returns Null check used on a null value Error

我正在尝试创建磁贴列表。 我用过ListView.separated。但它总是报错。

════════ Exception caught by rendering library ═════════════════════════════════ RenderBox was not laid out: _RenderScrollSemantics#aa680 relayoutBoundary=up6 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE 'package:flutter/src/rendering/box.dart': package:flutter/…/rendering/box.dart:1 Failed assertion: line 1982 pos 12: 'hasSize'

════════ Exception caught by rendering library ═════════════════════════════════ Null check operator used on a null value

这是代码

class _NewtilesState extends State<Newtiles> {

  @override
  Widget build(BuildContext context) {
    
    return Container(
      child: Expanded(
        child: ListView(
          children: [
            ListView.separated(
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                    title: Text('Person $index'),
                    subtitle: Text("Your Message"),
                    trailing: Text("11:10 PM"),
                  );
                },
                separatorBuilder: (BuildContext context, int index) {
                  return Divider();
                },
                itemCount: 30)
          ],
        ),
      ),
    );
  }
}

问题的发生是因为你把 Scrollable 而没有 shrinkWrapListView.separated 放到另一个 Scrollable - ListView 中。在你的特定例子中你应该跳过外部 ListView 并将 ListView.separated 直接放入 Container.

当您将

Expanded 作为灵活小部件的直接子项时(因此 ColumnRow),它会占据所有剩余的 space.

您的 Container 也是多余的,因为除了 child.

之外,您没有向它传递任何参数

如果您想在这样的列中放置几个​​ variable-height 小部件,您可能需要使用 CustomScrollView with SliverList

这应该有效:

  return Container(
  child: ListView.separated(
      itemBuilder: (BuildContext context, int index) {
        return ListTile(
          title: Text('Person $index'),
          subtitle: const Text("Your Message"),
          trailing: const Text("11:10 PM"),
        );
      },
      separatorBuilder: (BuildContext context, int index) {
        return Divider();
      },
      itemCount: 30),
);
return Container(
  child: Expanded(
    child: ListView.separated(
      shrinkWrap: true,  // <--- add this line
        itemBuilder: (BuildContext context, int index) {
          return ListTile(
            title: Text('Person $index'),
            subtitle: Text("Your Message"),
            trailing: Text("11:10 PM"),
          );
        },
        separatorBuilder: (BuildContext context, int index) {
          return Divider();
        },
        itemCount: 30),
  ),
);