Flutter/Flutter 기본

[Flutter] FutureBuilder

Chafle 2023. 5. 20. 03:01
반응형

 

3초 뒤에 랜덤하게 100이하의 숫자 생성

  Future<int> getNumber() async {
    await Future.delayed(Duration(seconds: 3));

    final random = Random();
    return random.nextInt(100);
  }
}

 

 

Future값을 아직 넣지 않았을 때의 기본

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    final textStyle = TextStyle(
      fontSize: 16.0,
    );
    return Scaffold(
      body: FutureBuilder(
        builder: (context, snapshot) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Text('FutureBuilder',
              style: textStyle.copyWith(
                fontWeight: FontWeight.w700,
                fontSize: 20.0,
              ),
              ),
              Text(
                'ConnectionState : ${snapshot.connectionState}',
                style: textStyle,
              ),
              Text(
                'Data : ${snapshot.data}',
                style: textStyle,
              ),
              Text(
                'Error : ${snapshot.error}',
                style: textStyle,
              ),
            ],
          );
        },
      )
    );
  }

 

 


class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    final textStyle = TextStyle(
      fontSize: 16.0,
    );
    return Scaffold(
      body: FutureBuilder(
        future: getNumber(), // future에 future함수를 넣음
        builder: (context, snapshot) {
          if(snapshot.hasData) {
            //hasData는 Data값이 null인지 아닌지만 확인, 데이터가 있을 때 위젯 렌더링
          }
          if(snapshot.hasError) {
            //에러가 났을 때의 렌더링
          }
          //데이터도 없고, 에러도 없는, 로딩중일 때 위젯 렌더링

          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Text('FutureBuilder',
              style: textStyle.copyWith(
                fontWeight: FontWeight.w700,
                fontSize: 20.0,
              ),
              ),
              Text(
                'ConnectionState : ${snapshot.connectionState}',
                style: textStyle,
              ),
              Text(
                'Data : ${snapshot.data}',
                style: textStyle,
              ),
              Text(
                'Error : ${snapshot.error}',
                style: textStyle,
              ),
              ElevatedButton(
                  onPressed: () {
                    setState(() {
                      //snapshot값이 변경되면, builder를 다시 부르고
                      // setState를 해도 FutureBuilder는 캐싱기능을 통해 이전 값을 화면에 남겨둔다.(FutureBuilder의 장점)
                    });
                  },
                  child: Text('setState')),
            ],
          );
        },
      )
    );
  }
반응형