FlutterでGoogle_Sign_in
ポイントだけ簡単に。
- codelabsにflutterでfirebase使うチュートリアルがあるんだけども、プラグインがかなりバージョンアップして(0.3.1 -> 3.0.0)少し使い方なんかも変わったよう。
- https://codelabs.developers.google.com/codelabs/flutter-firebase/
- codelabsのチュートリアルcloneしてきて動かそうとすると罠にハマりやすいので新規プロジェクトでやったほうがやりやすそう。
- ということで簡単にまとめてみた。
- とりあえずAndroidだけ
Firebaseコンソールにてアプリ登録
- アプリの登録を行う
- アプリのpackage名だけじゃなくてハッシュを登録することを忘れないこと
- keystoreファイルからSHA1を確認する。デバッグであれば→ハッシュ確認方法
- 次のステップで
google-services.jsonファイルをダウンロードできるので、プロジェクトに追加する - 場所は[project directory] > android > app > google-services.json
- 次のステップで指示されるbuild.gradleの追記はgoogle_sign_inを使うだけなら必要なし。analytics等firebaseの他の機能を使う場合は指示通り追記
FirebaseコンソールにてAuthenticationを有効化
Develop > Authenticationログイン方法 > プロバイダにて好きな認証方法を有効にする(例えばgoogleアカウントでのログイン)- プロバイダの横に
有効となればok
Flutter Plugin [google_sign_in]を追加
...
dependencies:
flutter:
sdk: flutter
google_sign_in: ^3.0.0#←を追加
...
... import 'package:google_sign_in/google_sign_in.dart';//importに追加 ...
コード
//Stateなどのプロパティに初期化し追加
GoogleSignIn _googleSignIn = new GoogleSignIn(
scopes: [
'email',
'https://www.googleapis.com/auth/contacts.readonly',
],
);
//Stateなどのプロパティに追加、初期化
GoogleSignIn _googleSignIn = new GoogleSignIn(
scopes: [
'email',
'https://www.googleapis.com/auth/contacts.readonly',
],
);
//サインインしていない場合にサインインを試みる関数を追加
//Silentlyは前回のログイン情報でログインできる場合にダイアログ無しで自動ログインを試みる
//googleSignIn.singIn();でサインインダイアログが出る。
Future<Null> _ensureLoggedIn() async {
GoogleSignInAccount user = _googleSignIn.currentUser;
if (user == null)
user = await _googleSignIn.signInSilently();
if (user == null) {
await _googleSignIn.signIn();
}
}
//ユーザー情報の取得の仕方 _googleSignIn.currentUser.photoUrl _googleSignIn.currentUser.displayName _googleSignIn.currentUser.email //など。
すごく雑な使用例
child: new Column(
children: <Widget>[
new Container(
child: (_googleSignIn.currentUser != null)?new CircleAvatar(
backgroundImage:
new NetworkImage(_googleSignIn.currentUser.photoUrl)
): new Text("no login")
),
(_googleSignIn.currentUser != null)?
new Text(_googleSignIn.currentUser.displayName)
: new Text("no name")
,
(_googleSignIn.currentUser != null)?
new Text(_googleSignIn.currentUser.email)
: new Text("no email")
],
)
....
floatingActionButton: new FloatingActionButton(
onPressed: ()async{await _ensureLoggedIn(); setState((){});},
child: new Icon(Icons.add),
),
トラブルシューティング!
- 起動しない!
- build.gradleにしなくていい追記をした可能性。firebaseから指示されるbuild.gradleの変更はしなくてよい。
_googleSignIn.signIn();を呼び出したあとにエラー発生- firebaseに登録したアプリのpackage名とandroidアプリのpackage名が一致してるか再確認
- firebaseに登録したハッシュ(SHA1 or SHA256)は現在起動してるAPKの署名のものと一致してるか確認
- デバッグモードでも署名は必要

mashi@exciton.jp
トラックバックURL - http://mashi.exciton.jp/archives/310/trackback