Flutter Push Notification (feat.flutterfire)

강정우·2023년 8월 20일
0

Flutter&Dart

목록 보기
68/82
post-thumbnail

FPNs

class ChatScreen extends StatefulWidget {
  const ChatScreen({super.key});

  
  State<ChatScreen> createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> {
  void setupPushNotifications() async {
    final fcm = FirebaseMessaging.instance;

    await fcm.requestPermission();
    final token = await fcm.getToken();
    print(token);
  }

  
  void initState() {
    super.initState();
    setupPushNotifications();
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('FlutterChat'),
        actions: [
          IconButton(
            onPressed: () {
              FirebaseAuth.instance.signOut();
            },
            icon: Icon(
              Icons.exit_to_app,
              color: Theme.of(context).colorScheme.primary,
            ),
          ),
        ],
      ),
      body: Column(
        children: const [
          Expanded(
            child: ChatMessages(),
          ),
          NewMessage(),
        ],
      ),
    );
  }
}
  • 우선 screens에 코드에 들어와서 여기서 작업을 해주겠다. 왜냐하면 해당 screens이 login후 authenticated된 사용자들만 들어오는 페이지이기 때문이다.

  • 그래서 위 코드에서 push 알림을 주기위해서는

  1. StatelessWidget을 StatefulWidget으로 바꿔주어야한다. 왜냐하면 우리는 init메서드가 필요하기 때문이다.
    그리고 앞서 언급했듯 이 페이지는 한 번 처음 로드될 때 실행되도록 셋업작업을 하기 좋은 screens 위젯이기 때문이다.

  2. init 메서드에 작업을 해줘야한다. 하지만 init 메서드는 flutter에 의해 1번 실행되는 메서드로 Futre객체를 반환할 수 없다. 즉, async 기능을 지원하지 않는다. 따라서 async를 사용할 수 있는 일반 메서드를 하나 임의로 만들어서 사용해야한다.

  1. .getToken() 메서드는 중요한 메서드이다. 이는 실행 중인 장치의 주소를 얻어온다.
    그리고 특정 장치에게 알림을 보내려면 이 주소가 필요하다. 즉, 푸시 알림이 있다면 개별 장치별 주소로 알림을 보낸다.
    그래서 위 메서드로 각각의 장치의 주소를 확보하고
    이를 HTTP 요청과 함께 이 주소를 백엔드로 전송해 데이터베이스에 저장해 사용자의 다른 메타데이터와 연결할 수도 있고 해당 주소로 알림을 보낼수 있는 것이다.

profile
智(지)! 德(덕)! 體(체)!

0개의 댓글