본문 바로가기

Flutter

[j Flutter] Flutter 2.x SnackBar ( 스낵바 ) 새로운 적용 방법

728x90
반응형

기존 스낵바 적용 방법은 해당 코드 처럼 적용을 해주면 됐었다. 

 

 Scaffold.of(context).showSnackBar(SnackBar(
            content: const Text('snack'),
            duration: const Duration(seconds: 1),
            action: SnackBarAction(
              label: 'ACTION',
              onPressed: () { },
            ),
          ));
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
Scaffold(
  key: scaffoldKey,
  body: ...,
);

scaffoldKey.currentState.showSnackBar(mySnackBar);

 

 

-->새로운 SnackBar ( 스낵바 ) 적용방법

 

1. ScaffoldMessenger 사용

 ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: const Text('snack'),
        duration: const Duration(seconds: 1),
        action: SnackBarAction(
          label: 'ACTION',
          onPressed: () { },
        ),
      ));

 

2. GlobalKey<ScaffoldMessengerState> 사용 (ScaffoldMessenger)

final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
ScaffoldMessenger(
  key: scaffoldMessengerKey,
  child: ...
)

scaffoldMessengerKey.currentState.showSnackBar(mySnackBar);
scaffoldMessengerKey.currentState.hideCurrentSnackBar(mySnackBar);
scaffoldMessengerKey.currentState.removeCurrentSnackBar(mySnackBar);

 

 

3. GlobalKey<ScaffoldMessengerState> 사용 2 (MeterialApp)

final GlobalKey<ScaffoldMessengerState> rootScaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
MaterialApp(
  scaffoldMessengerKey: rootScaffoldMessengerKey,
  home: ...
)

rootScaffoldMessengerKey.currentState.showSnackBar(mySnackBar);
rootScaffoldMessengerKey.currentState.hideCurrentSnackBar(mySnackBar);
rootScaffoldMessengerKey.currentState.removeCurrentSnackBar(mySnackBar);

 

 

 

출처 

https://docs.flutter.dev/release/breaking-changes/scaffold-messenger

 

SnackBars managed by the ScaffoldMessenger

SnackBars are now managed by the ScaffoldMessenger, and persist across routes.

docs.flutter.dev

 

728x90
반응형