【问题标题】:Flutter,How to let a child widget's height match parent in SingleChildScrollView?Flutter,如何让 SingleChildScrollView 中子部件的高度与父部件匹配?
【发布时间】:2019-08-02 10:17:24
【问题描述】:

我想创建一个可以刷新列表项的自定义小部件。它看起来像这样:

...
Widget build(BuildContext context){
 return new RefreshIndicator(
   child:data.isEmpty?
     new SingleChildScrollView(
      child:new Center(
        child:new Text("this is a empty widget which needs to be center in parent!)
       ),
     )
     :
     new ListView.separated(...)
);
}

但是当我触摸屏幕并移动时它无法刷新,我猜它太短以至于不足以滚动? 我尝试将CenterContainer 状态定义为相同的结果,但是如果我将1000 定义为Containerheight,它现在可以刷新,我该怎么办?

【问题讨论】:

  • 接受的答案可能会导致一些问题。 Here 是我的优化版。

标签: listview flutter scrollview


【解决方案1】:

您需要使用AlwaysScrollableScrollPhysics() 确保滚动视图始终可滚动。

您还需要制作一个大的可滚动区域。您可以使用Container 并使用MediaQuery 获取屏幕高度。

child: RefreshIndicator(
  onRefresh: () async {
    print('onRefresh called');
  },
  child: SingleChildScrollView(
    physics: const AlwaysScrollableScrollPhysics(),
    child: Container(
      alignment: Alignment.topCenter,
      padding: EdgeInsets.only(top: 50),
      height: MediaQuery.of(context).size.height,
      child: Text('hello'),
    ),
  ),
),

这不是一个完美的解决方案。刷新功能仅在用户拖动文本周围的空白区域时起作用。如果用户拖动文本,则他们看不到刷新符号。他们也可以向上滚动一点。

最好的解决方案是使用具有始终启用垂直滚动和单页的 PageView:

child: RefreshIndicator(
  onRefresh: () async {
    print('onRefresh called');
  },
  child: PageView(
    scrollDirection: Axis.vertical,
    physics: const AlwaysScrollableScrollPhysics(),
    children: <Widget>[
      Center(
        child: Text('hello'),
      )
    ],
  ),
),

【讨论】:

    【解决方案2】:

    您可以使用具有viewportConstraintsLayoutBuilder 包装您的RefreshIndicator,还可以使用ConstrainedBoxSingleChildScrollView 的子级)包装Center 小部件并将minHeight 设置为viewportConstraints.maxHeight . SingleChildScrollView 也需要一直可滚动以使刷新指示器起作用,因此您需要将physics 设置为const AlwaysScrollableScrollPhysics()。在你的情况下,它会是这样的:

      Widget build(BuildContext context) {
        return LayoutBuilder(
          builder: (BuildContext context, BoxConstraints viewportConstraints) {
            return RefreshIndicator(
              onRefresh: () async {},
              child: data.isEmpty
                  ? SingleChildScrollView(
                      physics: const AlwaysScrollableScrollPhysics(),
                      child: ConstrainedBox(
                        constraints: BoxConstraints(
                          minHeight: viewportConstraints.maxHeight,
                        ),
                        child: Center(
                            child: Text(
                                "this is an empty widget which needs to be center in parent!")),
                      ),
                    )
                  : ListView.separated(...),
            );
          },
        );
      }
    

    【讨论】:

      猜你喜欢
      • 2019-12-27
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 1970-01-01
      • 2021-08-30
      • 2021-01-07
      • 2019-06-23
      • 1970-01-01
      相关资源
      最近更新 更多