使用飞镖中的按钮更改布尔状态
Changing boolean state with a button in dart
这是我的第一个堆栈溢出 post 所以请坦诚面对我,并在需要时给我建设性的批评。
我正在开发一个需要有两种不同帐户类型的应用程序,一种是学生帐户类型,另一种是辅导员帐户类型。我决定使用自定义索赔代码来区分这两种帐户类型。我做了一个,以便用户帐户设置存在于 firestore 数据库中,并且我正在尝试这样做,以便当我在注册屏幕中单击一个按钮时,它会将布尔值设置为 true。我尝试在另一个身份验证 class 中调用 returnCounselor 函数,但收到此错误。 “方法 'returnCounselor' 没有为类型 'Register' 定义。”
更多背景信息在 class 中,我设置了身份验证,我调用了一个函数,该函数接受两个参数,即用户名和顾问变量的状态,这就是我拥有顾问的地方可变输入。
我试图让按钮在身份验证中设置顾问变量的状态 class 但显然我可以设置可行的状态,除非它在有状态的小部件中。这是我的代码
//database class
import 'package:cloud_firestore/cloud_firestore.dart';
class DatabaseService {
final String uid;
DatabaseService({this.uid});
//collection reference
final CollectionReference userCollection = Firestore.instance.collection('User Data');
Future updateUserData(String name, bool counselor) async {
return await userCollection.document(uid).setData({
'name': name,
'Counselor': true,
});
}
}
//register class stful widget
import 'package:flutter/material.dart';
import 'package:strength_together/services/auth.dart';
import 'package:strength_together/shared/constants.dart';
import 'package:strength_together/shared/loading.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:strength_together/models/user.dart';
import 'package:strength_together/services/database.dart';
import 'package:strength_together/services/auth.dart';
class Register extends StatefulWidget {
final Function toggleView;
Register({this.toggleView });
@override
_RegisterState createState() => _RegisterState();
}
class _RegisterState extends State<Register> {
final AuthService _auth = AuthService();
final _formKey = GlobalKey<FormState>();
bool loading = false;
//text field state
String email = '';
String password = '';
String error = '';
//set counselor state
//setCounselor(){
//counselor = true;
//}
bool counselor = false;
bool returnCounselor(){
return counselor;
}
@override
Widget build(BuildContext context) {
return loading ? Loading() : Scaffold(
backgroundColor: Colors.grey[900],
appBar: AppBar(
backgroundColor: Colors.black,
elevation: 0.0,
title: Text(
'Sign up to Strength Together',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.yellow,
),
),
actions: <Widget>[
FlatButton.icon(
icon: Icon(
Icons.person,
color: Colors.yellow,
),
label: Text(
'Sign in',
style: TextStyle(
color: Colors.yellow,
),
),
onPressed: () {
widget.toggleView();
}
)
],
),
body: Container(
padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 50.0),
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
SizedBox(height: 20.0,),
TextFormField(
decoration: textInputDecoration.copyWith(hintText: 'Email'),
validator: (val) => val.isEmpty ? 'Enter an email': null,
onChanged: (val){
setState(() => email = val);
},
),
SizedBox(height: 20.0),
TextFormField(
decoration: textInputDecoration.copyWith(hintText: 'Password'),
validator: (val) => val.length < 6 ? 'Enter a password 6+ chars long': null,
obscureText: true,
onChanged: (val){
setState(() => password = val);
},
),
SizedBox(height: 20.0),
RaisedButton(
color: Colors.black,
child: Text(
'Register',
style: TextStyle(color: Colors.yellow),
),
onPressed: () async{
if(_formKey.currentState.validate()){
setState(() => loading = true);
dynamic result = await _auth.registerWithEmailAndPassword(email, password);
if(result == null){
setState(() {
error = 'Please supply a valid email';
loading = false;
});
}
}
}
),
SizedBox(height:12.0),
Text(
error,
style: TextStyle(color: Colors.red, fontSize: 14.0),
),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async{
counselor = true;
//setCounselor();
},
),
);
}
}
//authentification class
import 'package:firebase_auth/firebase_auth.dart';
import 'package:strength_together/Screens/authenticate/register.dart';
import 'package:strength_together/models/user.dart';
import 'package:strength_together/services/database.dart';
import 'package:flutter/material.dart';
class AuthService{
final FirebaseAuth _auth = FirebaseAuth.instance;
//instance of couns
bool counselor = Register().returnCounselor();
//bool counselor = false;
//setCounselor(){
//counselor = true;
//}
//create user obj based on firebase user
User _userFromFirebaseUser(FirebaseUser user){
return user != null ? User(uid: user.uid) : null;
}
//auth change user stream
Stream<User> get user {
return _auth.onAuthStateChanged
.map(_userFromFirebaseUser);
}
//method to sign in anon
Future signInAnon() async{
try{
AuthResult result = await _auth.signInAnonymously();
FirebaseUser user = result.user;
return _userFromFirebaseUser(user);
}catch(e){
print(e.toString());
return null;
}
}
//method to sign in with email/pass
Future signInWithEmailAndPassword(String email, String password) async{
try{
AuthResult result = await _auth.signInWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
return _userFromFirebaseUser(user);
}catch(e){
print(e.toString());
return null;
}
}
//method to register with email/pass
Future registerWithEmailAndPassword(String email, String password) async{
try{
AuthResult result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
//create a new document for that user with the uid
await DatabaseService(uid: user.uid).updateUserData('New user', counselor);
return _userFromFirebaseUser(user);
}catch(e){
print(e.toString());
return null;
}
}
//sign in with google
//sign out
Future signOut() async{
try{
return await _auth.signOut();
}catch(e){
print(e.toString());
return null;
}
}
我会将您的 get getCounselor 方法放在您的 AuthService 中 class 将顾问设为私有。像这样:
bool _counselor;
bool get counselor => _counselor;
void setCounselor(bool counselor) {
_counselor = counselor;
}
然后,您可以在您的注册小工具中调用它。
_auth.couselor;
_auth.setCounselor;
处理此问题的最佳方法是使用 ChangeNotifier class,然后使用 Provider 将其注入您的 Register Class.
class AuthBloc extends ChangeNotifier {
bool _counselor;
String _userName;
String _email;
String _password;
bool get counselor => _counselor;
String get userName => _userName;
void setCounselor(bool counselor) {
_counselor = counselor;
notifyListeners();
}
void setUserName(String userName) {
_userName = userName;
notifyListeners();
}
void setEmail(String email) {
_email = email;
notifyListeners();
}
void setPassword(String password) {
_password = password;
notifyListeners();
}
AuthService _auth = AuthService();
Future<User> signInAnon() async{
return await _auth.signInAnon();
}
Future<User> signInWithEmailAndPassword() async{
_return await _auth.signInWithEmailAndPassword(_email, _password);
}
Future<User> createUserWithEmailAndPassword() async{
_return await _auth.createUserWithEmailAndPassword(_email, _password);
}
}
然后您也可以将您的 AuthService 和数据库服务方法放在那里。
在您的 main.dart 文件中:
ChangeNotifierProvider(
create: (context) => AuthBloc(),
child: MyApp(),
),
然后,在您的注册小工具中:
Consumer<AuthBloc>(
builder: (context, bloc, child) {
return TextFormField(
decoration: textInputDecoration.copyWith(hintText: 'Password'),
validator: (val) => val.length < 6 ? 'Enter a password 6+ chars long':
null,
obscureText: true,
onChanged: (val){
bloc.setPassword(val);
},
},
);
只需在需要访问集团的任何地方使用消费者小工具即可。
这是我的第一个堆栈溢出 post 所以请坦诚面对我,并在需要时给我建设性的批评。
我正在开发一个需要有两种不同帐户类型的应用程序,一种是学生帐户类型,另一种是辅导员帐户类型。我决定使用自定义索赔代码来区分这两种帐户类型。我做了一个,以便用户帐户设置存在于 firestore 数据库中,并且我正在尝试这样做,以便当我在注册屏幕中单击一个按钮时,它会将布尔值设置为 true。我尝试在另一个身份验证 class 中调用 returnCounselor 函数,但收到此错误。 “方法 'returnCounselor' 没有为类型 'Register' 定义。”
更多背景信息在 class 中,我设置了身份验证,我调用了一个函数,该函数接受两个参数,即用户名和顾问变量的状态,这就是我拥有顾问的地方可变输入。
我试图让按钮在身份验证中设置顾问变量的状态 class 但显然我可以设置可行的状态,除非它在有状态的小部件中。这是我的代码
//database class
import 'package:cloud_firestore/cloud_firestore.dart';
class DatabaseService {
final String uid;
DatabaseService({this.uid});
//collection reference
final CollectionReference userCollection = Firestore.instance.collection('User Data');
Future updateUserData(String name, bool counselor) async {
return await userCollection.document(uid).setData({
'name': name,
'Counselor': true,
});
}
}
//register class stful widget
import 'package:flutter/material.dart';
import 'package:strength_together/services/auth.dart';
import 'package:strength_together/shared/constants.dart';
import 'package:strength_together/shared/loading.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:strength_together/models/user.dart';
import 'package:strength_together/services/database.dart';
import 'package:strength_together/services/auth.dart';
class Register extends StatefulWidget {
final Function toggleView;
Register({this.toggleView });
@override
_RegisterState createState() => _RegisterState();
}
class _RegisterState extends State<Register> {
final AuthService _auth = AuthService();
final _formKey = GlobalKey<FormState>();
bool loading = false;
//text field state
String email = '';
String password = '';
String error = '';
//set counselor state
//setCounselor(){
//counselor = true;
//}
bool counselor = false;
bool returnCounselor(){
return counselor;
}
@override
Widget build(BuildContext context) {
return loading ? Loading() : Scaffold(
backgroundColor: Colors.grey[900],
appBar: AppBar(
backgroundColor: Colors.black,
elevation: 0.0,
title: Text(
'Sign up to Strength Together',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.yellow,
),
),
actions: <Widget>[
FlatButton.icon(
icon: Icon(
Icons.person,
color: Colors.yellow,
),
label: Text(
'Sign in',
style: TextStyle(
color: Colors.yellow,
),
),
onPressed: () {
widget.toggleView();
}
)
],
),
body: Container(
padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 50.0),
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
SizedBox(height: 20.0,),
TextFormField(
decoration: textInputDecoration.copyWith(hintText: 'Email'),
validator: (val) => val.isEmpty ? 'Enter an email': null,
onChanged: (val){
setState(() => email = val);
},
),
SizedBox(height: 20.0),
TextFormField(
decoration: textInputDecoration.copyWith(hintText: 'Password'),
validator: (val) => val.length < 6 ? 'Enter a password 6+ chars long': null,
obscureText: true,
onChanged: (val){
setState(() => password = val);
},
),
SizedBox(height: 20.0),
RaisedButton(
color: Colors.black,
child: Text(
'Register',
style: TextStyle(color: Colors.yellow),
),
onPressed: () async{
if(_formKey.currentState.validate()){
setState(() => loading = true);
dynamic result = await _auth.registerWithEmailAndPassword(email, password);
if(result == null){
setState(() {
error = 'Please supply a valid email';
loading = false;
});
}
}
}
),
SizedBox(height:12.0),
Text(
error,
style: TextStyle(color: Colors.red, fontSize: 14.0),
),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async{
counselor = true;
//setCounselor();
},
),
);
}
}
//authentification class
import 'package:firebase_auth/firebase_auth.dart';
import 'package:strength_together/Screens/authenticate/register.dart';
import 'package:strength_together/models/user.dart';
import 'package:strength_together/services/database.dart';
import 'package:flutter/material.dart';
class AuthService{
final FirebaseAuth _auth = FirebaseAuth.instance;
//instance of couns
bool counselor = Register().returnCounselor();
//bool counselor = false;
//setCounselor(){
//counselor = true;
//}
//create user obj based on firebase user
User _userFromFirebaseUser(FirebaseUser user){
return user != null ? User(uid: user.uid) : null;
}
//auth change user stream
Stream<User> get user {
return _auth.onAuthStateChanged
.map(_userFromFirebaseUser);
}
//method to sign in anon
Future signInAnon() async{
try{
AuthResult result = await _auth.signInAnonymously();
FirebaseUser user = result.user;
return _userFromFirebaseUser(user);
}catch(e){
print(e.toString());
return null;
}
}
//method to sign in with email/pass
Future signInWithEmailAndPassword(String email, String password) async{
try{
AuthResult result = await _auth.signInWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
return _userFromFirebaseUser(user);
}catch(e){
print(e.toString());
return null;
}
}
//method to register with email/pass
Future registerWithEmailAndPassword(String email, String password) async{
try{
AuthResult result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
//create a new document for that user with the uid
await DatabaseService(uid: user.uid).updateUserData('New user', counselor);
return _userFromFirebaseUser(user);
}catch(e){
print(e.toString());
return null;
}
}
//sign in with google
//sign out
Future signOut() async{
try{
return await _auth.signOut();
}catch(e){
print(e.toString());
return null;
}
}
我会将您的 get getCounselor 方法放在您的 AuthService 中 class 将顾问设为私有。像这样:
bool _counselor;
bool get counselor => _counselor;
void setCounselor(bool counselor) {
_counselor = counselor;
}
然后,您可以在您的注册小工具中调用它。
_auth.couselor;
_auth.setCounselor;
处理此问题的最佳方法是使用 ChangeNotifier class,然后使用 Provider 将其注入您的 Register Class.
class AuthBloc extends ChangeNotifier {
bool _counselor;
String _userName;
String _email;
String _password;
bool get counselor => _counselor;
String get userName => _userName;
void setCounselor(bool counselor) {
_counselor = counselor;
notifyListeners();
}
void setUserName(String userName) {
_userName = userName;
notifyListeners();
}
void setEmail(String email) {
_email = email;
notifyListeners();
}
void setPassword(String password) {
_password = password;
notifyListeners();
}
AuthService _auth = AuthService();
Future<User> signInAnon() async{
return await _auth.signInAnon();
}
Future<User> signInWithEmailAndPassword() async{
_return await _auth.signInWithEmailAndPassword(_email, _password);
}
Future<User> createUserWithEmailAndPassword() async{
_return await _auth.createUserWithEmailAndPassword(_email, _password);
}
}
然后您也可以将您的 AuthService 和数据库服务方法放在那里。
在您的 main.dart 文件中:
ChangeNotifierProvider(
create: (context) => AuthBloc(),
child: MyApp(),
),
然后,在您的注册小工具中:
Consumer<AuthBloc>(
builder: (context, bloc, child) {
return TextFormField(
decoration: textInputDecoration.copyWith(hintText: 'Password'),
validator: (val) => val.length < 6 ? 'Enter a password 6+ chars long':
null,
obscureText: true,
onChanged: (val){
bloc.setPassword(val);
},
},
);
只需在需要访问集团的任何地方使用消费者小工具即可。