Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
@sudama221
Revisions
Report this question
Subscribe question
Help us understand the problem. What is going on with this question?
Q&A

ユーザー情報を他のページにも使う

SNSのようなものを作成したいのですが、ユーザー情報の保持に仕方がわかりません。
下記のコードでログイン後ユーザー情報を表示しているのですが、

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
//ここ
        home: MyHomePage());
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final GoogleSignIn _googleSignIn = GoogleSignIn();
  final FirebaseAuth _auth = FirebaseAuth.instance;

  Future<FirebaseUser> _handleSignIn() async {
    GoogleSignInAccount googleCurrentUser = _googleSignIn.currentUser;
    try {
      if (googleCurrentUser == null)
        googleCurrentUser = await _googleSignIn.signInSilently();
      if (googleCurrentUser == null)
        googleCurrentUser = await _googleSignIn.signIn();
      if (googleCurrentUser == null) return null;

      GoogleSignInAuthentication googleAuth =
          await googleCurrentUser.authentication;
      final AuthCredential credential = GoogleAuthProvider.getCredential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );
      final FirebaseUser user =
          (await _auth.signInWithCredential(credential)).user;
      print("signed in " + user.displayName);

      await Firestore.instance
          .collection('users') // コレクションID
          .document(user.uid) // ドキュメントID
          .setData({'name': '斉藤', 'age': 40});

      return user;
    } catch (e) {
      print(e);
      return null;
    }
  }

  void transitionNextPage(FirebaseUser user) {
    if (user == null) return;

    Navigator.push(context,
        MaterialPageRoute(builder: (context) => NextPage(userData: user)));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('widget.title'),
      ),
      body: Center(
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              RaisedButton(
                child: Text('Sign in Google'),
                onPressed: () {
                  _handleSignIn()
                      .then((FirebaseUser user) => transitionNextPage(user))
                      .catchError((e) => print(e));
                },
              ),
            ]),
      ),
    );
  }
}
class NextPage extends StatefulWidget {
  FirebaseUser userData;

  NextPage({Key key, this.userData}) : super(key: key);

  @override
  _NextPageState createState() => _NextPageState(userData);
}

class _NextPageState extends State<NextPage> {
  FirebaseUser userData;
  String name = "";
  String email;
  String photoUrl;
  final GoogleSignIn _googleSignIn = GoogleSignIn();

  _NextPageState(FirebaseUser userData) {
    this.userData = userData;
    this.name = userData.displayName;
    this.email = userData.email;
    this.photoUrl = userData.photoUrl;
  }

  Future<void> _handleSignOut() async {
    await FirebaseAuth.instance.signOut();
    try {
      await _googleSignIn.signOut();
    } catch (e) {
      print(e);
    }
    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("ユーザー情報表示"),
      ),
      body: Center(
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Image.network(this.photoUrl),
              Text(
                this.name,
                style: TextStyle(
                  fontSize: 24,
                ),
              ),
              Text(
                this.email,
                style: TextStyle(
                  fontSize: 24,
                ),
              ),
              RaisedButton(
                child: Text('Sign Out Google'),
                onPressed: () {
                  _handleSignOut().catchError((e) => print(e));
                },
              ),
            ]),
      ),
    );
  }
}

ここでユーザー情報を渡しているために表示できています。

loginページ

void transitionNextPage(FirebaseUser user) {
    if (user == null) return;

    Navigator.push(context,
        MaterialPageRoute(builder: (context) => NextPage(userData: user)));
  }
ネクストページ

  FirebaseUser userData;
  String name = "";
  String email;
  String photoUrl;
  final GoogleSignIn _googleSignIn = GoogleSignIn();

  _NextPageState(FirebaseUser userData) {
    this.userData = userData;
    this.name = userData.displayName;
    this.email = userData.email;
    this.photoUrl = userData.photoUrl;
  }

現状は名前、アドレス、画像を表示していますが、
uidをfirestoreに登録してプロフ画像は別で登録、他に年齢とエリアを登録する予定です。

投稿する際はuidに紐付けて投稿、コメント投稿、DMも実装予定です。
その場合、

await Firestore.instance
          .collection('users') // コレクションID
          .document('posts') // ドキュメントID
          .setData({'text': 'hogehoge'});

これのようにのように入れたいです。

このpostsをusers>idと紐付けるというコードも分からず、途方に暮れています。

0
1
Answer

FirebaseAuthでログイン済みなのであれば

final FirebaseAuth auth = FirebaseAuth.instance;
final uid = auth.currentUser.uid;

でuidを取得できますので、

await Firestore.instance
          .collection('users') // コレクションID
          .document(uid) // ドキュメントID
          .setData({'text': 'hogehoge'});

としてやれば良いかと思います。

0
Help us understand the problem. What is going on with this answer?
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login