[flutter] RefreshIndicator를 사용하여 데이터를 새로 고침할 때 로딩 상태 표시하기

앱에서 데이터를 가져오거나 업데이트할 때, 사용자에게 즉각적인 피드백을 제공하는 것은 매우 중요합니다. Flutter에서 RefreshIndicator를 사용하여, 사용자가 리스트를 새로 고칠 때 로딩 상태를 표시하는 방법을 알아봅시다.

1. RefreshIndicator 추가

먼저, 리스트를 감싸는 RefreshIndicator를 추가해야 합니다. 아래는 RefreshIndicator로 감싸진 리스트 예제입니다.

RefreshIndicator(
  onRefresh: _handleRefresh,
  child: ListView.builder(
    itemCount: _data.length,
    itemBuilder: (context, index) {
      return ListTile(
        title: Text(_data[index]),
      );
    },
  ),
),

2. 상태 관리

이제 _handleRefresh 메서드를 구현하여 새로 고침 동작을 처리할 수 있습니다. 새로운 데이터를 가져오는 도중에 로딩 상태를 표시해야 합니다. 이를 위해 StatefulWidget을 사용하여 데이터 로딩 중에 상태를 관리합니다.

bool _isRefreshing = false;

Future<void> _handleRefresh() async {
  setState(() {
    _isRefreshing = true;
  });

  await _fetchData(); // 새로운 데이터 가져오기

  setState(() {
    _isRefreshing = false;
  });
}

위 예제에서는 _isRefreshing 변수를 사용하여 새로 고침 동작 여부를 추적하고, 새로운 데이터를 가져오는 동안에 true로 설정합니다.

3. 로딩 상태 표시

마지막으로, 로딩 상태를 표시하는데 사용할 수 있는 CircularProgressIndicator를 추가해야 합니다.

child: _isRefreshing
  ? Center(child: CircularProgressIndicator())
  : ListView.builder(
    itemCount: _data.length,
    itemBuilder: (context, index) {
      return ListTile(
        title: Text(_data[index]),
      );
    },
  ),

위 코드에서는 _isRefreshing이 true일 때 CircularProgressIndicator가 표시됩니다.

이제 RefreshIndicator를 사용하여 데이터를 새로 고칠 때 로딩 상태를 표시하는 방법에 대해 알아보았습니다. 사용자 경험을 향상시키기 위해 이러한 로딩 상태 표시는 매우 중요합니다.

참고: Flutter Documentation