SNS 로그인을 넣다보니 KakaoLogin도 구현을 하게 되어 문서로 정리를 해보자
기능별로 분단 나눠 설명을 통해 전반적인 코드 흐름을 알아보도록 합시다.
void main() => runApp(KakaoLoginTest());
class KakaoLoginTest extends StatelessWidget {
// This widget is the root of your application.
Widget build(BuildContext context) {
KakaoContext.clientId = 'MyKey';
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
appBarTheme: AppBarTheme(
color: Color(0xFFF7E600),
textTheme: TextTheme(
title: TextStyle(
color: Color.fromRGBO(56, 35, 36, 1),
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
),
home: KakaoLogin(),
);
}
}
class KakaoLogin extends StatefulWidget {
KakaoLogin({Key key, this.title}) : super(key: key);
final String title;
_KakaoLoginState createState() => _KakaoLoginState();
}
class _KakaoLoginState extends State<KakaoLogin> {
bool _isKakaoTalkInstalled = false;
void dispose() {
super.dispose();
}
void initState() {
super.initState();
// String kakaoAppKey= "k4tzR2Azj8nfJL2mpM78WFn4tvQ=";
// KakaoContext.clientId = kakaoAppKey;
_initKakaoTalkInstalled();
}
_initKakaoTalkInstalled() async {
final installed = await isKakaoTalkInstalled();
print('kakao Install : ' + installed.toString());
setState(() {
_isKakaoTalkInstalled = installed;
});
}
_issueAccessToken(String authCode) async {
try {
var token = await AuthApi.instance.issueAccessToken(authCode);
AccessTokenStore.instance.toStore(token);
print(token);
Navigator.push(
context,
MaterialPageRoute(builder: (context) => LoginDone()),
);
} catch (e) {
print("error on issuing access token: $e");
}
}
_loginWithKakao() async {
try {
var code = await AuthCodeClient.instance.request();
await _issueAccessToken(code);
} catch (e) {
print(e);
}
}
_loginWithTalk() async {
try {
var code = await AuthCodeClient.instance.requestWithTalk();
await _issueAccessToken(code);
} catch (e) {
print(e);
}
}
unlinkTalk() async {
try {
var code = await UserApi.instance.unlink();
print(code.toString());
} catch (e) {
print(e);
}
}
Widget build(BuildContext context) {
isKakaoTalkInstalled();
return Scaffold(
appBar: AppBar(
title: Text("Kakao Flutter SDK Login"),
actions: [],
),
body: Center(
child: Column(
children: <Widget>[
ElevatedButton(
child: Text("Login with Talk"),
onPressed:
_isKakaoTalkInstalled ? _loginWithTalk : _loginWithKakao),
],
),
),
);
}
}
class LoginDone extends StatelessWidget {
Future<bool> _getUser() async {
try {
User user = await UserApi.instance.me();
print(user.toString());
} on KakaoAuthException catch (e) {
} catch (e) {
}
}
Widget build(BuildContext context) {
_getUser();
logOutTalk() async {
try {
var code = await UserApi.instance.logout();
await AccessTokenStore.instance.clear();
print(code.toString());
print("로그아웃 되었습니다.");
} catch (e) {
print("오류");
print(e);
}
}
return Scaffold(
body: SafeArea(
child: Column(
children: [
Center(
child: Text('Login Success!'),
),
ElevatedButton(
child: Text("Logout"),
onPressed: logOutTalk,
),
],
),
),
);
}
}