【问题标题】:Using DefaultTabController in widget tree with variable height在具有可变高度的小部件树中使用 DefaultTabController
【发布时间】:2020-09-19 07:51:02
【问题描述】:

在我的应用程序中,我有一个 PageView,然后在那个 PageView 中,我有一些选项卡式内容(通过使用 DefaultTabController)。在这些选项卡中,我有一些可变高度的内容。无论我做什么,每当我尝试使用 DefaultTabController 时,Flutter 都会抛出这个错误:

Viewports expand in the cross axis to fill their container and constrain their children to match their extent in the cross axis. In this case, a horizontal viewport was given an unlimited amount of vertical space in which to expand.
The relevant error-causing widget was: 
  TabBarView file:///C:/code/samples/tabbed/lib/main.dart:104:23

我试过了:

  • 使用 shrinkWrap 将所有内容包装在 ListView 中:true
  • 使用具有最小主轴尺寸的列

无论我做什么,TabBarView 总是试图渲染成无穷大。如何使用 DefaultTabController 显示可变高度选项卡?

这是我的代码:

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: PageView(
        children: [
          Container(
            height: 200,
            color: Colors.blueGrey,
            child: DefaultTabController(
              length: 2,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  TabBar(
                    tabs: [
                      Tab(
                        text: "Okay",
                      ),
                      Tab(
                        text: "Go",
                      )
                    ],
                  ),
                  ListView(
                    scrollDirection: Axis.vertical,
                    shrinkWrap: true,
                    children: [
                      TabBarView(
                        children: [
                          Text("one"),
                          Text("two"),
                        ],
                      )
                    ],
                  ),
                ],
              ),
            ),
          ),
          Container(
            color: Colors.deepOrange,
          ),
          Container(
            color: Colors.cyan,
          )
        ],
      ),
    );
  }

【问题讨论】:

    标签: flutter flutter-layout flutter-pageview


    【解决方案1】:

    删除ListView 并用Expanded 包裹TabBarView,你应该很高兴:

    Expanded(
      child: TabBarView(
        children: [
          Text("one"),
          Text("two"),
        ],
      ),
    )
    

    请注意,现在TabBarView 和PageView 滑动手势之间存在冲突(您只能从TabBar 滑动PageView,因为后者下方的所有内容都被TabBarView 覆盖)

    【讨论】:

    • 啊,是的,我通常使用 ScrollPhysics: NeverScrollableScrollPhysics() 来克服这个问题。我会试试这个并回复你。
    猜你喜欢
    • 2019-07-18
    • 2020-10-20
    • 2016-02-28
    • 2012-05-31
    • 2011-04-24
    • 2012-11-24
    • 2013-04-29
    • 2017-03-11
    • 2021-03-06
    相关资源
    最近更新 更多