Flutter : Google Sign In を試す。AndroidとiPhoneで。

Flutter + Firebase でアプリ開発の部品集め。Googleサインインを試す。

準備

https://pub.dev/packages/google_sign_in

  1. Android,iPhone アプリケーションを、Firebaseに登録
  2. 連絡先を取得するためには、Google People API を有効化
  3. iOS
    1. GoogleService-Info.plist をダウンロード
    2. KEY=CFBundleURLSchemes の array/string の内容を、上記でダウンロードした
    3. KEY=REVERSED_CLIENT_ID の値に置き換え

pubspec.yaml

  • 以下を追記

dependencies:
    :
  google_sign_in: 4.4.4

lib/main.dart

  • メインメニューに、GoogleSignInWidgetへの遷移ボタンを配置

import 'dart:io';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_ml_vision/firebase_ml_vision.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image_cropper/image_cropper.dart';

import './google_sign_in.dart';
import './second.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  final message = "Initial Message.";
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Sample',
      home: MyHomePage(message:this.message),
    );
  }
}

class MyHomePageState extends State{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.message)
      ),
      body: Column(
        children: [
          Container(
            child: RaisedButton(
              child: Text("Google Signin"),
              onPressed:  () => _pushPage(context, GoogleSignInWidget()),
            ),
          ),
          Container(
            child: RaisedButton(
              child: Text("Firestore, Cloud Vision"),
              onPressed:  () => _pushPage(context, MyPage()),
            ),
          )
        ],
      )
    );
  }

  void _pushPage(BuildContext context, Widget page) {
    Navigator.of(context).push(
      MaterialPageRoute(builder: (_) => page)
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String message;
  MyHomePage({this.message}):super() {}
  @override
  State createState() => new MyHomePageState();
}

lib/google_sign_in.dart

import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import "package:http/http.dart" as http;
import 'dart:convert' show json;

GoogleSignIn _googleSignIn = GoogleSignIn(
  scopes: <String>[
    'email',
    'https://www.googleapis.com/auth/contacts.readonly',
  ]
);

class GoogleSignInWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => GoogleSignInWidgetState();
}

class GoogleSignInWidgetState extends State<GoogleSignInWidget>   {
  GoogleSignInAccount _currentUser;
  String _contactText;

  @override
  void initState() {
    super.initState();
    _googleSignIn.onCurrentUserChanged.listen(
        (GoogleSignInAccount account) {
          setState(() {
            _currentUser = account;
          });
          if (_currentUser != null) {
            _handleGetContact();
          }
        }
    );
    _googleSignIn.signInSilently();
  }

  Future<void> _handleGetContact() async {
    setState(() {
      _contactText = "Loading contact info...";
    });
    final http.Response response = await http.get(
      'https://people.googleapis.com/v1/people/me/connections'
          '?requestMask.includeField=person.names',
      headers: await _currentUser.authHeaders,
    );
    final Map<String, dynamic> data = json.decode(response.body);
    print(data);
  }

  Future<void> _handleSignIn() async {
    try {
      await _googleSignIn.signIn();
    } catch(error) {
      print(error);
    }
  }

  Future<void> _handleSignOut() => _googleSignIn.disconnect();

  Widget _buildBody() {
    if (_currentUser != null) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          ListTile(
            leading: GoogleUserCircleAvatar(
              identity: _currentUser,
            ),
            title: Text(_currentUser.displayName ?? ''),
            subtitle: Text(_currentUser.email ?? ''),
          ),
          const Text('サインイン成功'),
          Text(_contactText ?? ''),
          RaisedButton(
            child: const Text('SIGN OUT'),
            onPressed: _handleSignOut,
          ),
          RaisedButton(
            child: const Text('REFRESH'),
            onPressed: _handleGetContact,
          ),
        ],
      );
    } else {
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          const Text('現在サインインしていません。'),
          RaisedButton(
            child: const Text("Sign In"),
            onPressed: _handleSignIn,
          ),
        ],
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Google Sign In"),
      ),
      body: ConstrainedBox(
        constraints: const BoxConstraints.expand(),
        child: _buildBody(),
      ),
    );
  }
}

エラー対応

PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null)

Follow me!

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です