Flutter,如何让子部件的高度与 SingleChildScrollView 中的父部件匹配?

par*_*ool 4 listview scrollview flutter

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

...
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(...)
);
}
Run Code Online (Sandbox Code Playgroud)

但是当我触摸屏幕并移动时它无法刷新,我想这太短了所以不足以滚动?我尝试将Containerinstate定义Center为相同的结果,但如果我定义1000Container's height,则现在可以刷新,我该怎么办?

M. *_*ard 9

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

您还需要制作一个大的可滚动区域。您可以使用 aContainer并使用获取屏幕高度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'),
    ),
  ),
),
Run Code Online (Sandbox Code Playgroud)

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

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

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