본문 바로가기

Dead Code/Flutter_Dart

[플러터] 위젯 사이즈 확인하기

 

GlobalKey... 이 녀석 어디다 쓰는지 명쾌하지 않았는데, 그중 한 예제가 될 수 있을 듯하다.

우선 키를 생성한다.

 

GlobalKey sizekey = GlobalKey();

 

 

사이즈 확인을 원하는 위젯에서, 키를 받아온다.

 

Positioned(
  child: SizedBox(
    key: sizekey, // apply Global key for check size...
    width: 200,
    height: 250,
  ),
),

 

 

onPressed 이하 코드를 보게 되면, GlobalKey에서 Size를 가져오게 된다. 솔직히 말하면, 정확하게 무슨 과정인지 잘 모르겠다.

 

Positioned(
  top: 180,
  left: 20,
  child: TextButton(
    style: ButtonStyle(
      // foregroundColor: MaterialStateProperty.all(Colors.red),
      foregroundColor:
          MaterialStateProperty.resolveWith((states) {
        if (states.contains(MaterialState.pressed)) {
          return Colors.red;
        } else {
          return Colors.black;
        }
      }),
    ),
    onPressed: () {
      RenderBox renderBox =
          sizekey.currentContext!.findRenderObject() as RenderBox;
      Size sizeText = renderBox.size;
      showToast(
          'width : ${sizeText.width.toStringAsFixed(1)}' +
              ' / ' +
              'height : ${sizeText.height.toStringAsFixed(1)}',
          position: ToastPosition.bottom);
    },
    child: const Text(
      'Widget Size Detecting',
    ),
  ),
),

 

 

그래도 원하는데로 되었긴 한데, 한가지 문제는 layout이 완료되기 전에는 그 사이즈를 알 수는 없다. 고로, 처음 렌더링을 할때 그 사이즈를 사용할 수는 없다는 것이다. 그래서, 최초 렌더링이 된 이후, 사이즈를 체크해서 적용하는 방법은 아래와 같다.

세 가지가 있는데, 뭔 차이가 있긴 하겠지만, 잘 모르겠다.

 

@override
void initState() {
  super.initState();
  WidgetsBinding.instance.addPostFrameCallback((_) {
    print("WidgetsBinding");
  });

  SchedulerBinding.instance.addPostFrameCallback((_) {
    print("SchedulerBinding");
  });

  WidgetsBinding.instance.endOfFrame.then(
    (_) {
      if (mounted) {
        print('it works too');
      }
    },
  );
}

 

끝.