본문 바로가기
기초다지기/Flutter&Dart

flutter 비동기 위젯 FutureBuilder, StreamBuilder

by 김빵그 2023. 6. 3.

비동기?

다트언어에서 제공하는 Future, Stream, await, async는 모두 비동기 프로그래밍을 지원하는 기능인데 비동기란 동시에 일어나지 않는 다는 의미로 요청한 결과가 바로 주어지지 않는다

 

1. FutureBuilder

  • Flutter와 dart는 서로 동기화가 이루어 진다.
  • dart의 future를 통해 스레드나 데드락에 대한 우려없이 IO를 관리할 수 있다 예) 앱을 외부에서 불러오는 graphQL, api 데는 시간이 걸리는데 요청된 데이터가 이용 가능할 때까지 futures로 dart에서 다른 업무가 가능
FutureBuilder(
	future:_data,
    builder:_myBuilderFunction,
)
  • FutureBuilder를 통해 Future의 현 상태를 쉽게 파악하고 데이터를 불러오는 동안 보여줄 것과 이용 가능할 때 보여줄 것의 선택이 가능하다
  • FutureBuilder내에 Future : http://....을 생성하면 안되는데 코딩을 하고 나면 FutureBuilder의 상위 요소가 다시 구축 될 때마다 데이터 가져오기가 재시작됨
  • 고로 아래와 같이 초기에 데이터를 얻어야한다
Future<MyData> _data; 
initState(){
	_data = http.get("http://awesome.data");
}

FutureBuilder(
	future:_data,
    builder: (context, snapshot) {
    	if(snapshot.connectionState ==done) {
        	if(snapshot.hasError){
            	return SomethingWentWrong();
            }
        	return AswesomdData(snapshot.data);
        }
    	else {
        	reuturn CircularProgressIndicator();
        }
    },
)
  • 새로운 상태 변수를 만들고 데이터 가져오기 요청을 FutureBuilder 밖으로 내보낸 뒤 initState로 옮긴다
  • 그런 다음 빌더에 전달 
  • Future의 상태를 connectionState로 통해 확인하고 future가 작업에 들어간 동안 적절한 위젯을 보여준다
 

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

 

2. StreamBuilder

  • 스트림은 반복해서 발생하는 데이터를 다룰 때 사용한다 
StreamBuilder(
	stream : test(),
    builder : (BuildContext context, AsyncSnapshot<int> snapshot) {
    	if (snapshot.hasData) {
        	return Text("data : ${snapshot.data}");
        }
        return ChircularProgressIndicator();
    });
)
 

StreamBuilder class - widgets library - Dart API

Widget that builds itself based on the latest snapshot of interaction with a Stream. Widget rebuilding is scheduled by each interaction, using State.setState, but is otherwise decoupled from the timing of the stream. The builder is called at the discretion

api.flutter.dev

'기초다지기 > Flutter&Dart' 카테고리의 다른 글

Flutter AnimatedCrossFade  (0) 2023.06.12
[flutter] input 값에 따라 disabled 시키기  (0) 2023.06.04
flutter splash 화면 구현하기  (0) 2023.05.31
Flutter FloatingActionButton  (0) 2023.05.22
Flutter Widget LinearGradient  (0) 2023.05.22