[054] 플러터 (Flutter) 배우기 - country_calling_code_picker 사용하여 국가 선택하기

2023. 4. 15. 12:26모바일어플개발/Flutter

반응형

안녕하세요~ totally 개발자입니다.

 

country_calling_code_picker

 

이 패키지를 사용하여 국가 선택을 쉽게 할 수 있습니다. 

 

Step 1: pubspec.yaml에 country_calling_code_picker를 넣어줍니다.

 

 

 

Step 2: main.dart에 import해줍니다.

 

 

 

Step 3: 다음을 추가해줍니다. 이 Country 클래스에는 name, flag, countryCode, callingCode가 들어가 있습니다. 그리고 국가 리스트들을 초기화하고 기본 국가를 가지고 오기 위한 작업을 진행합니다.

 

 

 

Step 4: 아래쪽에서 국가를 고를 수 있는 UI부분을 만들어주며 heightFactor는 기기 대비 높이 비율을 말하며 cancelWidget은 선택하지 않고 그냥 닫고자 할 때 위젯, 55-59번째 줄에서는 나라가 선택되었다면 _selectedCountry에 업데이트해줍니다.

 

 

 

Step 5: 나머지 부분을 다음처럼 구성해주면 됩니다. 72-75번째 줄은 버튼, 77-80번째 줄에는 나라 선택을 마무리하고 나서 어떤 국가, 국가 코드, 국가 전화 번호 등의 정보를 나타내도록 만들어줍니다.

 

 

 

Step 6: 결과는 아래와 같습니다.

 

 

 

 

[전체 소스 코드]

 

import 'package:flutter/material.dart';
import 'package:country_calling_code_picker/picker.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(title: 'Flutter App', home: HomePage());
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Country? _selectedCountry;
@override
void initState() {
_initCountry();
super.initState();
}
void _initCountry() async {
final country = await getDefaultCountry(context);
setState(() {
_selectedCountry = country;
});
}
void _showBottomSheet() async {
final country = await showCountryPickerSheet(
context,
heightFactor: 0.6,
cancelWidget: Align(
alignment: Alignment.topRight,
child: Padding(
padding: const EdgeInsets.only(right: 8.0),
child: IconButton(
icon: const Icon(Icons.close),
onPressed: () => Navigator.pop(context),
),
),
),
);
if (country != null) {
setState(() {
_selectedCountry = country;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter App'),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextButton(
onPressed: () => _showBottomSheet(),
child: const Text("국가 선택"),
),
const SizedBox(height: 20),
_selectedCountry == null
? const SizedBox.shrink()
: Text(
"${_selectedCountry?.callingCode} ${_selectedCountry?.name} (${_selectedCountry?.countryCode})"),
],
),
),
);
}
}
view raw 054_main.dart hosted with ❤ by GitHub

 

References

 

https://pub.dev/packages/country_calling_code_picker

 

country_calling_code_picker | Flutter Package

Flexible Country picker for getting Country code and Calling code.

pub.dev

 

반응형