본문 바로가기
프로그래밍/Flutter <Dart>

[Flutter] Futurebuilder Future 객체 리로드 중일 때의 상태 표현하기

by TaeGyeong Lee 2024. 9. 22.

개요 

주의 
일부 올바르지 않은 내용이 있을 수 있습니다. 최신 플러터 버전을 참고하세요.

FutureBuilder Future 객체의 상태를 snapshot 속성을 통해 감지할 수 있습니다. (예: snapshot.hasData 등)

첫 Future 객체가 성공적으로 불러온 후에 다시 Future 객체 정보를 불러들이는 경우 (새로고침 또는 불러올 정보가 바뀔 때) 새 Future 객체의 데이터를 가져오고 있는 중에 다시 로딩중임을 출력할 필요가 있습니다. 

isLoading 과 같은 형태로 관련 속성이 당연히 지원되리라 생각했지만, 그렇지 않습니다. 관련 속성이 없습니다. 

 

솔루션 

* Future 객체에 null 저장 

setState 를 사용하여 Future 객체에 null을 저장하도록 합니다. 

FutureBuilder 에서 제공하는 snapshot.hasData 속성은 null이 아닐 때 true 를 반환합니다. 

따라서 새로운 데이터를 로딩하는 과정에서 처음과 동일한 로딩 화면을 출력하기 위해서는 먼저 null 을 저장해야 합니다.

// Future 객체 선언
Future? _dataListFuture;
// 새로운 데이터를 불러올 때 setState 활용
...
onTap : () {
  setState(() {
    _dataListFuture = null;
    _dataListFuture = getNewDataList();
  })
}
...
// FutureBuilder 위젯 일부
FutureBuilder<String>(
        future: _dataListFuture,
        builder: (context,  snapshot) {
          children;
          if (snapshot.hasData) {
            /// Future 객체가 null이 아닐 경우
          } else if (snapshot.hasError) {
            /// 에러가 발생하는 경우, null 여부와 다릅니다.
          } else {
           /// 로딩 중일떄, Future 객체가 null 일 경우 이 조건을 탑니다.
          }
        })

 

* StreamBuilder 활용

자세한 사항은 StreamBuilder 공식 문서를 참고하세요. 

 

참고 자료 

 

FutureBuilder class - widgets library - Dart API

A widget that builds itself based on the latest snapshot of interaction with a Future. Managing the future The future must have been obtained earlier, e.g. during State.initState, State.didUpdateWidget, or State.didChangeDependencies. It must not be create

api.flutter.dev

 

FutureBuilder: add a way to refresh it. · Issue #62019 · flutter/flutter

There's stated in the docs: The future must have been obtained earlier, e.g. during State.initState, State.didUpdateConfig, or State.didChangeDependencies. It must not be created during the State.b...

github.com

 

Reloading future with flutter FutureBuilder - Greycastle

The Flutter FutureBuilder is a great way to render async operations but you need to take care if you want to reload or rerun the future. Here I'll show how.

www.greycastle.se

 

Reload data when using FutureBuilder

I am loading data when widget is loading like the code below. Once the UI is fully loaded, I like to add one refresh button to reload the data again. How can I refresh the view ? class

stackoverflow.com