如何解决显示垂直视口的Flutter抽屉的高度不受限制的问题

时间:2020-02-20 14:04:52

标签: android ios flutter mobile

值得一提的是,我对Flutter和Stackoverflow都是新手。

在我的新闻阅读器应用程序中,我添加了一个侧面抽屉,该抽屉可使用FutureBuilder从API中提取新闻类别。有一个DrawerHeader包含一个名为Popular News的类别,该类别不是从API提取的,它是静态的。

每次打开API时,“热门新闻”类别都会显示并正常运行,但其他类别不会显示,而是会在控制台中显示如下错误。

I/flutter ( 4486): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 4486): The following assertion was thrown during performResize():
I/flutter ( 4486): Vertical viewport was given unbounded height.
I/flutter ( 4486): Viewports expand in the scrolling direction to fill their container.In this case, a vertical
I/flutter ( 4486): viewport was given an unlimited amount of vertical space in which to expand. This situation
I/flutter ( 4486): typically happens when a scrollable widget is nested inside another scrollable widget.
I/flutter ( 4486): If this widget is always nested in a scrollable widget there is no need to use a viewport because
I/flutter ( 4486): there will always be enough vertical space for the children. In this case, consider using a Column
I/flutter ( 4486): instead. Otherwise, consider using the "shrinkWrap" property (or a ShrinkWrappingViewport) to size
I/flutter ( 4486): the height of the viewport to the sum of the heights of its children.

我的代码如下

返回抽屉的小部件

@override
  Widget build(BuildContext context) {
    SizeConfig().init(context);

    return SizedBox(
      width: SizeConfig.safeBlockHorizontal*50,
      child: Theme(
        data: Theme.of(context).copyWith(canvasColor: const Color(0xFF2b4849)),
        child: Drawer(
          child: ListView(
            padding: EdgeInsets.zero,
            children: <Widget>[
              DrawerHeader(
                child:  ListTile(
                  title: Text(
                    "Popular News",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 25
                    ),
                  ),
                  onTap: (){
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (BuildContext context) => MostPopularNewsfeed(),
                        )
                    );
                  },
                ),
              ),
          FutureBuilder(
            future: category,
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if(snapshot.data == null) {
                return Container(
                  child: Center(
                    child: Text(
                      "Loading",
                      style: TextStyle(
                          color: Colors.white
                      ),
                    ),
                  ),
                );
              } else {
                return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemBuilder: (BuildContext context, int index) {
                    return _getDrawer(snapshot, index);
                  },
                );
              }
            },
          ),
            ],
          ),
        ),
      ),
    );
  }

initState():此categoryFuture<List>

void initState() {
    super.initState();

    setState(() {
       category = fetchCategory();
    });
  }

fetchCategory():这是从API中提取类别。

Future<List<Category>> fetchCategory() async {
    //try {
    String url = "https://tbsnews.net/json/category/news/list";
    dio.interceptors.add(DioCacheManager(CacheConfig(baseUrl: url)).interceptor);
    Response response = await Dio().get(url);
    print(response);

    List<Category> categoryList = [];
    final Future<Database> dbFuture = categoryDatabaseHelper.initDb();

    if(response.statusCode == 200) {
      var decode = response.data;
      print(decode);
      for (var c in decode) {
        Category category = Category(c['tid'], c['name']);
        await categoryDatabaseHelper.insertCategory(category);
        categoryList.add(category);
      }
      return categoryList;
      //categoryDatabaseHelper.insertCategory(categoryList);
    } else {
      throw Exception("Failed to fetch category");
    }
  }

到目前为止我尝试过的事情

我尝试将DrawerHeaderFutureBuilder放在Expanded小部件中,而不是ListView中。没有用。

在ListView中,我添加了shrinkWrap: true,也添加了scrollDirection: Axis.vertical。那也没有用。

试图将它们也放入SizeBoxColumn小部件中。那也不起作用。

以上是我通过在StackOverflow中搜索与该问题相关的先前问题发现的。最后,我自己发布了一个问题。

要注意的是,当我拿走DrawerHeader时一切正常,然后再没有麻烦了。但是这个DrawerHeader必须在那里。

非常感谢您的时间和真诚的帮助。

1 个答案:

答案 0 :(得分:1)

如果问题仅出在DrawerHeader上,请尝试用SizedBoxConstrainedBox包装它,并为其指定一定的高度和宽度。 问题是DrawerHeader不受约束,因此ListView在构建时不会知道其尺寸或约束,并且会抛出此错误。

这是我有根据的猜测,请让我知道它是否有效。