Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter,How to let a child widget's height match parent in SingleChildScrollView?

I want to create a custom widget that can refresh list items.it looks like this:

...
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(...)
);
}

but it can't refresh when I touch the screen and move,I guess that is too short so not enough to be scroll? I try to defined a Container instate of Center as the same result but if i define 1000 to Container's height, it can be refresh now, how can i do?

like image 841
parcool Avatar asked Dec 14 '22 12:12

parcool


1 Answers

You need to make sure the scroll view is always scrollable by using AlwaysScrollableScrollPhysics().

You also need to make a large scrollable area. You can use a Container and get the screen height with 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'),
    ),
  ),
),

This isn't a perfect solution. The refresh function only works when the user drags the white space around the text. If the user drags the text, then they don't see the refresh symbol. Also they can scroll up a little.

The best solution is to use a PageView with vertical always-enabled scrolling and a single page:

child: RefreshIndicator(
  onRefresh: () async {
    print('onRefresh called');
  },
  child: PageView(
    scrollDirection: Axis.vertical,
    physics: const AlwaysScrollableScrollPhysics(),
    children: <Widget>[
      Center(
        child: Text('hello'),
      )
    ],
  ),
),
like image 189
M. Leonhard Avatar answered Apr 19 '23 15:04

M. Leonhard