抖动中的嵌套ListViews会产生水平视口错误

时间:2019-01-07 12:23:07

标签: dart nested flutter flutter-layout

我试图制作一个类似Netflix的画廊UI,并在Vertical ListView内创建水平ListViews,但是我一直遇到视口错误,无法解决。

完整代码。

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Live Tree',
      home: Scaffold(
        appBar: AppBar(
          title: Text("Netflux"),
        ),
        body: HomePage(),
      ),
    );
  }
}

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {

    Row getMediaForCategory(CategoryModel category) {
      List<Column> mediaItems = [];
      for (Media media in category.media) {
        mediaItems.add(
          Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              media.image,
              Container(
                color: Colors.black,
                padding: EdgeInsets.only(top: 8, bottom: 8),
                child: Text(media.title),
              )
            ],
          ),
        );
      }
      return Row(mainAxisSize: MainAxisSize.min, children: mediaItems);
    }

    List<ListView> getCategoryRows(List<CategoryModel> categoryModels) {
      List<ListView> categoryRows = [];
      for (CategoryModel category in categoryModels) {
        categoryRows.add(
          ListView(
              scrollDirection: Axis.horizontal,
              children: [getMediaForCategory(category)]),
        );
      }
      return categoryRows;
    }

    Widget gallerySection = ListView(
      children: getCategoryRows(mockCategoryDataSet),
    );

    return Scaffold(
      body: gallerySection,
    );
  }
}

如果我将嵌套的ListViews更改为行,则会呈现出来但不能滚动。

在嵌套的ListViews中,出现以下错误:

I/flutter ( 9048): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 9048): The following assertion was thrown during performResize():
I/flutter ( 9048): Horizontal viewport was given unbounded height.
I/flutter ( 9048): Viewports expand in the cross axis to fill their container and constrain their children to match
I/flutter ( 9048): their extent in the cross axis. In this case, a horizontal viewport was given an unlimited amount of
I/flutter ( 9048): vertical space in which to expand.

1 个答案:

答案 0 :(得分:1)

The problem is that your horizontal list view doesn't have a height so you're better off using a SingleChildScrollView and a Row so the height can be implied by the content:

List<Widget> getCategoryRows(List<CategoryModel> categoryModels) {
  List<Widget> categoryRows = [];
  for (CategoryModel category in categoryModels) {
    categoryRows.add(
      SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          children: [getMediaForCategory(category)],
        ),
      ),
    );
  }
  return categoryRows;
}