본문 바로가기

프로젝트

Firebase users 정보 UI로 가져오기

Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Top banner with changing images and text - 배너 인디케이터 제거
          GestureDetector(
            onTap: () {
              _launchURL(_bannerData[_currentBannerIndex]['url']!);
            },
            child: Container(
              height: 250,
              width: double.infinity,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: _bannerData[_currentBannerIndex]['imageUrl']!.startsWith('http')
                      ? NetworkImage(_bannerData[_currentBannerIndex]['imageUrl']!)
                      : AssetImage(_bannerData[_currentBannerIndex]['imageUrl']!) as ImageProvider,
                  fit: BoxFit.cover,
                ),
              ),
              child: Stack(
                children: [
                  Container(
                    width: double.infinity,
                    height: double.infinity,
                    color: Colors.black.withOpacity(0.4),
                  ),
                  Positioned(
                    bottom: 80,
                    left: 20,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: const [
                        Text(
                          '이름 님,',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 24,
                            fontWeight: FontWeight.bold,
                            shadows: [
                              Shadow(
                                offset: Offset(1.0, 1.0),
                                blurRadius: 3.0,
                                color: Color.fromARGB(255, 0, 0, 0),
                              ),
                            ],
                          ),
                        ),
                        Text(
                          '대전 인기 여행지',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 24,
                            fontWeight: FontWeight.bold,
                            shadows: [
                              Shadow(
                                offset: Offset(1.0, 1.0),
                                blurRadius: 3.0,
                                color: Color.fromARGB(255, 0, 0, 0),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  Positioned(
                    bottom: 30,
                    left: 20,
                    child: Container(
                      padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 10),
                      decoration: BoxDecoration(
                        color: Colors.black.withOpacity(0.5),
                        borderRadius: BorderRadius.circular(20),
                      ),
                      child: Row(
                        children: [
                          Text(
                            _bannerData[_currentBannerIndex]['description']!,
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(width: 4),
                          const Icon(
                            Icons.arrow_forward,
                            color: Colors.white,
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),

보는 것과 같이  현재는 ui상으로 '이름 님' 이라는 텍스트가 화면에 출력되고 있다. 이 '이름' 을 fire auth에 저장된 users의 닉네임으로 가져와보도록 하겠다. 

 

먼저 import는 다음 2개를 해준다.

import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

 

uid 문서를 보고 해당하는 nickname 값을 가져오는 함수를 작성해준다.

Future<String?> getNickname(String uid) async {
  final doc = await FirebaseFirestore.instance
      .collection('users')
      .doc(uid)
      .get();
  if (doc.exists) {
    return doc.data()?['nickname'] as String?;
  } else {
    return null;
  }
}

 

String? nickname으로 class _HomePageState 클래스 안에 변수 선언먼저 한다.

초기 실행 코드 initState() 에서 아까 만든 함수를 넣어준다.

@override
  void initState() {
    super.initState();
    // 15초마다 배너 변경 타이머 설정
    
    _bannerTimer = Timer.periodic(const Duration(seconds: 15), (timer) {
      setState(() {
        _currentBannerIndex = (_currentBannerIndex + 1) % _bannerData.length;
      });
    });

    final uid = FirebaseAuth.instance.currentUser?.uid;
  if (uid != null) {
    getNickname(uid).then((value) {
      setState(() {
        nickname = value;
      });
    });
  }
  }

  @override
  void dispose() {
    _bannerTimer?.cancel();
    super.dispose();
  }

dispose 함수도 메모리에 남아있는 것을 방지하기 위해 만들어두는 편이 좋다.

이제 nickname에 값이 할당되었다.

@override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Top banner with changing images and text - 배너 인디케이터 제거
          GestureDetector(
            onTap: () {
              _launchURL(_bannerData[_currentBannerIndex]['url']!);
            },
            child: Container(
              height: 250,
              width: double.infinity,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: _bannerData[_currentBannerIndex]['imageUrl']!.startsWith('http')
                      ? NetworkImage(_bannerData[_currentBannerIndex]['imageUrl']!)
                      : AssetImage(_bannerData[_currentBannerIndex]['imageUrl']!) as ImageProvider,
                  fit: BoxFit.cover,
                ),
              ),
              child: Stack(
                children: [
                  Container(
                    width: double.infinity,
                    height: double.infinity,
                    color: Colors.black.withOpacity(0.4),
                  ),
                  Positioned(
                    bottom: 80,
                    left: 20,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          nickname != null ? '$nickname 님,' : '님,', // 불러오기 전엔 빈 값,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 24,
                            fontWeight: FontWeight.bold,
                            shadows: [
                              Shadow(
                                offset: Offset(1.0, 1.0),
                                blurRadius: 3.0,
                                color: Color.fromARGB(255, 0, 0, 0),
                              ),
                            ],
                          ),
                        ),

 

이렇게 가져와보면

 

잘 출력되고 있다.