Разный контент для разных пользователей Flutter - PullRequest
0 голосов
/ 14 июля 2020

Я создаю приложение, в котором пользователи могут делать заказы на стрижку кошек. Я уже подключил приложение к Firebase, где пользователи могут зарегистрироваться и войти в приложение. Вот в чем проблема: каждый раз, когда я вхожу в систему с другой учетной записью, история бронирования других пользователей все еще там.

введите описание изображения здесь

Как я могу сделать разный контент для разных пользователей, которые вошли в систему? так что каждый пользователь может иметь свой собственный контент. Вот код со страницы истории.

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

class HistoryPage extends StatefulWidget {
  static const String id = 'HistoryPage';
  @override
  _HistoryPageState createState() => _HistoryPageState();
}

class _HistoryPageState extends State<HistoryPage> {
  final _firestore = Firestore.instance;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            margin: EdgeInsets.fromLTRB(25.0, 68.0, 70.0, 25.0),
            child: Text(
              'History',
              style: TextStyle(fontSize: 35.0),
            ),
          ),
          Column(
            children: <Widget>[
              StreamBuilder<QuerySnapshot>(
                stream: _firestore.collection('ReservationData').snapshots(),
                builder: (context, snapshot) {
                  if (!snapshot.hasData) {
                    return Center(
                      child: CircularProgressIndicator(),
                    );
                  }
                  final messages = snapshot.data.documents;
                  List<HistoryBox> historyWidgets = [];
                  for (var message in messages) {
                    final historyDate = message.data['Reservation Date'];
                    final historyTime = message.data['Reservation Time'];
                    final historyWidget =
                        HistoryBox(date: historyDate, time: historyTime);
                    historyWidgets.add(historyWidget);
                  }
                  return Column(
                    children: historyWidgets,
                  );
                },
              ),
            ],
          )
        ],
      )),
    );
  }
}

class HistoryBox extends StatelessWidget {
  final String date;
  final String time;

  HistoryBox({this.date, this.time});
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 25.0),
      child: Material(
        elevation: 5.0,
        child: Container(
          child: Text(
            'Date Reservation : \n $date and $time',
            style: TextStyle(
              fontSize: 20.0,
            ),
          ),
        ),
      ),
    );
  }
}

(Обновлено)

Это код для пользователей, чтобы зарегистрироваться.

import 'package:flutter/material.dart';
import 'package:project_pi/screens/HomePage/home_page.dart';
import 'inputform_signup.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class SignUpPage extends StatefulWidget {
  static const String id = 'SignUpPage';
  @override
  _SignUpPageState createState() => _SignUpPageState();
}

class _SignUpPageState extends State<SignUpPage> {
  final _firestore = Firestore.instance;
  final _auth = FirebaseAuth.instance;
  bool showSpinner = false;
  String nama;
  String email;
  String password;
  String phoneNumber;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ModalProgressHUD(
        inAsyncCall: showSpinner,
        child: Form(
          child: SafeArea(
            child: Center(
              child: SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      'SIGN UP',
                      style: TextStyle(
                        fontSize: 28.0,
                      ),
                    ),
                    InputForm(
                      hint: 'Full Name',
                      hidetext: false,
                      onChanged: (value) {
                        nama = value;
                      },
                    ),
                    InputForm(
                      hint: 'Email Address',
                      hidetext: false,
                      onChanged: (value) {
                        email = value;
                      },
                    ),
                    InputForm(
                      hint: 'Phone Number',
                      hidetext: false,
                      onChanged: (value) {
                        phoneNumber = value;
                      },
                    ),
                    InputForm(
                      hint: 'Password',
                      hidetext: true,
                      onChanged: (value) {
                        password = value;
                      },
                    ),
                    InputForm(
                      hint: 'Confirm Password',
                      hidetext: true,
                    ),
                    SizedBox(height: 15.0),
                    Container(
                      height: 45.0,
                      width: 270.0,
                      child: RaisedButton(
                        child: Text('SIGN UP'),
                        onPressed: () async {
                          setState(() {
                            showSpinner = true;
                          });
                          try {
                            final newUser =
                                await _auth.createUserWithEmailAndPassword(
                                    email: email, password: password);

                            _firestore.collection('UserAccount').add({
                              'Email Address': email,
                              'Full Name': nama,
                              'Phone Number': phoneNumber,
                            });
                            if (newUser != null) {
                              Navigator.pushNamed(context, HomePage.id);
                            }
                            setState(() {
                              showSpinner = false;
                            });
                          } catch (e) {
                            print(e);
                          }
                        },
                      ),
                    ),
                    SizedBox(
                      height: 15.0,
                    ),
                    Text('Have an Account?'),
                    SizedBox(
                      height: 7.5,
                    ),
                    InkWell(
                      child: Text(
                        'SIGN IN',
                        style: TextStyle(
                          color: Colors.red,
                        ),
                      ),
                      onTap: () {
                        AlertDialog(
                          title: Text("Finish?"),
                          content: Text("Are you sure with the data?"),
                          actions: <Widget>[
                            FlatButton(onPressed: null, child: null)
                          ],
                        );
                      },
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

И это класс для текущего пользователя, который вошел в систему

import 'package:flutter/material.dart';
import 'package:project_pi/screens/HomePage/homebutton.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:project_pi/screens/LiveMaps/live_maps.dart';
import 'package:project_pi/screens/LoginPage/HalamanLogin.dart';
import 'package:project_pi/screens/ReservationHistory/history_page.dart';
import 'package:project_pi/screens/ReservationPage/information_detail.dart';

class HomePage extends StatefulWidget {
  static const String id = "HomePage";

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

class _HomePageState extends State<HomePage> {
  final _auth = FirebaseAuth.instance;
  FirebaseUser loggedInUser;

  @override
  void initState() {
    super.initState();
    getCurrentUser();
  }

  void getCurrentUser() async {
    try {
      final user = await _auth.currentUser();
      if (user != null) {
        loggedInUser = user;
      }
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Expanded(
          child: Container(
            child: Column(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.fromLTRB(25.0, 68.0, 256.0, 47.0),
                  child: Text(
                    'Home',
                    style: TextStyle(fontSize: 35.0),
                  ),
                ),
                Center(
                  child: Column(
                    children: <Widget>[
                      HomeNavButton(
                        prefixIcon: Icons.date_range,
                        textbutton: 'Make Reservation',
                        onPressed: () {
                          Navigator.pushNamed(context, InformationDetail.id);
                        },
                      ),
                      SizedBox(
                        height: 40.0,
                      ),
                      HomeNavButton(
                        prefixIcon: Icons.list,
                        textbutton: 'Reservation History',
                        onPressed: () {
                          Navigator.pushNamed(context, HistoryPage.id);
                        },
                      ),
                      SizedBox(
                        height: 40.0,
                      ),
                      HomeNavButton(
                        prefixIcon: Icons.gps_fixed,
                        textbutton: 'Live Maps Track',
                        onPressed: () {
                          Navigator.pushNamed(context, LiveMaps.id);
                        },
                      ),
                      SizedBox(
                        height: 40.0,
                      ),
                      HomeNavButton(
                        prefixIcon: Icons.person,
                        textbutton: 'Account Profile',
                        onPressed: () {
                          FirebaseAuth.instance.signOut();
                          Navigator.pushNamed(context, HalamanLogin.id);
                        },
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

как реализовать фильтр для каждого текущего пользователя, который вошел в систему, чтобы он мог отображать контент на основе пользователей?

1 Ответ

2 голосов
/ 14 июля 2020

, когда пользователь создает учетную запись через firebase, им назначается uid userId, который можно получить с помощью

     String userId;
  getCurrentUser() async {
    FirebaseUser firebaseUser = await FirebaseAuth.instance.currentUser();
    setState(() {
      userId = firebaseUser.uid;
    });
 
  }

, а затем при сохранении резервирований вы можете включить поле "userId":userid

сейчас когда вы запрашиваете, вы можете запросить своего текущего пользователя

_firestore.collection('ReservationData') .where("userId", isEqualTo: userId).snapshots(),
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...