본문 바로가기

Flutter/12 Clone 'Used Goods app'

[Flutter] Clone - 당근마켓13(Shared reference)

이번시간에는 간단한 데이터들을 디바이스에 저장했다가 로딩하는 방법에 대해서 알아하겠습니다.

개발환경 : 윈도우11, 안드로이드 스튜디오, flutter 3.0.1

 

 

 

추가된 패키지는 아래와 같습니다.

 

shared_preferences: ^2.0.15

 

 

./src/screens/start/address_page.dart - 공유 정보 저장

 


// 함수 추가
_saveAddressOnSharedPreference(String address, num lat, num lon) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  debugPrint('save Address: $address.');
  await prefs.setString(SHARED_ADDRESS, address);
  await prefs.setDouble(SHARED_LAT, lat.toDouble());
  await prefs.setDouble(SHARED_LON, lon.toDouble());
}


if (_addressModel != null)
  Expanded(
    child: ListView.builder(
      padding: const EdgeInsets.symmetric(vertical: padding_16),
      itemCount: (_addressModel == null) ? 0 : _addressModel!.results.juso.length,
      itemBuilder: (context, index) {
        if (_addressModel == null) {
          return Container();
        }
        // 동정보, 지번 정보 추출하기 위함
        var subAddress = _addressModel!.results.juso[index].jibunAddr.split(' ');
        return ListTile(
          onTap: () async {
            // 주소를 좌표로 변환하는 함수
            myLocation = await GoogleMapServices.getLocationFromAddress(
                _addressModel!.results.juso[index].roadAddrPart1);
            debugPrint(myLocation!.results[0].formattedAddress);
            debugPrint(myLocation!.results[0].geometry.location.toString());
// 함수 추가 위치
            _saveAddressOnSharedPreference(
              _addressModel!.results.juso[index].roadAddrPart1,
              myLocation!.results[0].geometry.location.lat,
              myLocation!.results[0].geometry.location.lng,
            );
          },
          title: Text(_addressModel!.results.juso[index].roadAddrPart1),
          subtitle: Text('${subAddress[2]} ${subAddress[3]}'),
        );
      },
    ),
  ),
  
if (_addressModelXYList.isNotEmpty)
  Expanded(
    child: ListView.builder(
      padding: const EdgeInsets.symmetric(vertical: padding_16),
      // shrinkWrap: true,
      itemCount: _addressModelXYList.length,
      itemBuilder: (context, index) {
        if (_addressModelXYList[index].results.isEmpty) {
          //_addressModelXYList[index].results == null ||
          return Container();
        }
        var zipcode = _addressModelXYList[index].results[0].addressComponents.length;
        var shortAddress = _addressModelXYList[index]
            .results[0]
            .formattedAddress
            .replaceFirst('대한민국 ', '');
        return ListTile(
          onTap: () {
            debugPrint(_addressModelXYList[index].results[0].formattedAddress);
            debugPrint(
                _addressModelXYList[index].results[0].geometry.location.toString());
// 함수 추가 위치
            _saveAddressOnSharedPreference(
              _addressModelXYList[index].results[0].formattedAddress,
              _addressModelXYList[index].results[0].geometry.location.lat,
              _addressModelXYList[index].results[0].geometry.location.lng,
            );
          },
          // leading: ExtendedImage.asset('assets/imgs/apple.png'),
          title: Text(shortAddress),
          subtitle: Text(_addressModelXYList[index]
              .results[0]
              .addressComponents[zipcode - 1]
              .longName),
        );
      },
    ),
  ),

 

 

./src/screens/start/auth_page.dart - 공유 정보 읽기

 

// 저장된 정보 읽기
_getAddress() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  String address = prefs.getString(SHARED_ADDRESS) ?? '';
  double lat = prefs.getDouble(SHARED_LAT) ?? 0.0;
  double lon = prefs.getDouble(SHARED_LON) ?? 0.0;
  debugPrint('get Address: [$address] [$lat] [$lon]');
}


    onPressed: () async {
      debugPrint(
          '_verificationStatus: $_verificationStatus');
// 저장된 정보 읽기
      _getAddress();
      FocusScope.of(context).unfocus();
      if (_verificationStatus ==
          VerificationStatus.codeSending) {
        return;
      }
      if (_formKey.currentState != null) {
        bool passed = _formKey.currentState!.validate();
        if (passed) {
          var phoneNum = _phoneNumberController.text;
          phoneNum = phoneNum.replaceAll(' ', '');
          phoneNum = phoneNum.replaceFirst('0', '');
          phoneNum = '+82$phoneNum';

          setState(() {
            // 인증단계 코드 전송중~~
            _verificationStatus =
                VerificationStatus.codeSending;
          });

          // 임시 시간 딜레이 코드
          await Future.delayed(const Duration(seconds: 3));
          setState(() {
            // 인증단계 코드 전송완료~~
            _verificationStatus =
                VerificationStatus.codeSent;
          });

        } else {
          setState(() {
            _verificationStatus = VerificationStatus.none;
          });
        }
      }
      debugPrint(
          '_verificationStatus: $_verificationStatus');
    },
    // 검증상태에 따라서 버튼의 문자열을 변경하여 동작중임을 표시함
    child: _verificationStatus ==
            VerificationStatus.codeSending
        ? const SizedBox(
            height: 26,
            width: 26,
            child: CircularProgressIndicator(
              color: Colors.white,
            ),
          )
        : const Text('인증문자 발송')),

 

 

./src/constants/shared_pref_key.dart - 정보 공유시 사용하는 키값

 

// ignore_for_file: constant_identifier_names
const SHARED_ADDRESS = 'address';
const SHARED_LAT = 'latitude';
const SHARED_LON = 'longitude';