Flutter Widget 之 RefreshIndicator

847 阅读2分钟

您追到当您下拉列表会刷新这件事吗?

如果有一个小部件能够表明正在刷新中,那岂不是很棒吗?

嗯,说的就是RefreshIndicator,将ListView或类似的可滚动小部件包装在RefreshIndicator中,将在列表过渡滚动时触发刷新。

RefreshIndicator(
    child: ListView(),
)

如果您希望会发生某些事情,请添加带有onRefresh属性的callback函数,这个函数没有任何给定的参数,但RefresshIndicator期待它返回一个Future

RefreshIndicator(
    onRefresh: _refresh,
    child: ListView(),
)

Future<void> _refresh() {}

只要Future尚未完成,不断旋转的刷新指示器将继续旋转。

如果它一直都不完成刷新旋转指示器永远都不会消失

ezgif.com-gif-maker.gif

所以,即便是立即的,请确保无论Refresh函数是做什么的,刷新终究都会完成

Future<void> _refresh() {
    return Future.delayed(
        Duration(seconds: 0),
    );
}

一旦我们刷新了RefreshIndicator,你就可以自定义它的外观改变它的: backgroundColor(背景颜色)

RefreshIndicator(
    backgroundColor: Colors.red,
    onRefresh: _refresh,
    child: ListView(),
)

image.png

刷新指示器的color(颜色)

RefreshIndicator(
    color: Colors.yellow,
    backgroundColor: Colors.red,
    onRefresh: _refresh,
    child: ListView()
)

image.png

Width(宽度)

RefreshIndicator(
    strokeWidth: 5,
    color: Colors.yellow,
    backgroundColor: Colors.red,
    onRefresh: _refresh,
    child: ListView(),
)

image.png

您还可以更改指示器出现的方式和时间 displacement(位移)将影响它出现在列表边缘多远的距离

RefreshIndicator(
    displacement: 200,
    strokeWidth: 5,
    color: Colors.yellow,
    backgroundColor: Colors.red,
    onRefresh: _refresh,
    child: ListView()
)

image.png

并且您可以使用edgeOffset,覆盖它认为列表边缘的位置,默认情况下。它设置为零,并在列表的实际边缘启动指标,指示器将在列表中出现相对应的像素数

RefreshIndicator(
    edgeOffset: 20,
    displacement: 200,
    strokeWidth: 5,
    color: Colors.yellow,
    backgroundColor: Colors.red,
    onRefresh: _refresh,
    child: ListView()
)

ezgif.com-gif-maker (1).gif

最后,使用triggerMode设置为anywhere或onEdge,来改变无论起始滚动位置在哪里 指示器是否会出现,或者只有当它已经在边缘时才会出现

RefreshIndicator(
    triggerMode: RefreshIndicatorTriggerMode.anywhere
    edgeOffset: 20,
    displacement: 200,
    strokeWidth: 5,
    color: Colors.yellow,
    backgroundColor: Colors.red,
    onRefresh: _refresh,
    child: ListView()
)
RefreshIndicator(
    triggerMode: RefreshIndicatorTriggerMode.onEdge
    edgeOffset: 20,
    displacement: 200,
    strokeWidth: 5,
    color: Colors.yellow,
    backgroundColor: Colors.red,
    onRefresh: _refresh,
    child: ListView()
)

ezgif.com-gif-maker (2).gif

如果想了解有关RefreshIndicator的内容,或者关于Flutter的其他功能,请访问flutter.dev

原文翻译自视频:视频地址