在没有 ListView 等的情况下刷新 Flutter 中的小部件或页面

Refresh widget or page in Flutter without ListView et al

我想在没有可滚动内容的情况下刷新我的页面,即没有 ListView

当我想使用 RefreshIndicator 时,文档说它需要 scrollable 小部件,例如 ListView

但是如果我想刷新并想使用 RefreshIndicator 的刷新动画而不使用 ListViewGridView 或任何其他可滚动的小部件,我该怎么做?

你可以直接使用GestureDetector,我已经为你创建了一个示例,但它并不完美,你可以根据自己的需要自定义它,它只检测你从顶部滑动的时间。

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {

  var refresh=false;

  void  refreshData(){
    if(!refresh){
      refresh=true;
      print("Refreshing");
      Future.delayed(Duration(seconds: 4),(){
        refresh =false;
        print("Refreshed");
      });
    }
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: Text("Test"),
          centerTitle: true,
        ),
        body: GestureDetector(
          child: Container(
            color: Colors.yellow,
            height: double.infinity,
            width: double.infinity,
            child: Center(child: Text('TURN LIGHTS ON')),
          ),
          onVerticalDragUpdate: (DragUpdateDetails details){
            print("direction ${details.globalPosition.direction}");
            print("distance ${details.globalPosition.distance}");
            print("dy ${details.globalPosition.dy}");
            if(details.globalPosition.direction < 1 && (details.globalPosition.dy >200 && details.globalPosition.dy < 250)){

              refreshData();

            }
          },
        ));
  }
} 

您可以简单地将您的内容包裹在 SingleChildScrollView, which will allow you to use a RefreshIndicator. In order to make the pull down to refresh interaction work, you will have to use AlwaysScrollableScrollPhysics 中,因为您的内容很可能不会比没有滚动视图的可用内容多 space:

RefreshIndicator(
      onRefresh: () async {
        // Handle refresh.
      },
      child: SingleChildScrollView(
        physics: const AlwaysScrollableScrollPhysics(),
        child: /* your content */,
      ),
    );