Navigation.pop() and Navigation.push() acting strangely有一个类似的问题。
所以我正在尝试制作“登录”页面。
这就是我希望代码执行的操作:
因此从技术上讲,它应该像从Home()-> Navigation.push()-> RegisterPage()的登录按钮一样工作, 当用户将其内容添加到“文本”字段中时 应该从RegisterPage()-> Navigation.pop()-> Home()->返回值中点击Submit按钮。
现在面临的问题在第4点,只要用户点击“提交”按钮,它就会使我进入同一页面。有趣的是,虽然返回了值,但仍然显示RegisterPage()不应显示的位置。
Here's the Problem am facing...
我正在使用Firebase数据库存储用户数据,因此正如我所说,这些值确实会返回,因为当我检查数据库时,这些值已输入到数据库中,问题是当它弹出时,相同的RegisterPage ()屏幕而不是Home()页面。
我之前在另一个应用程序中使用过这种push()和pop(),在该应用程序中我从其他页面返回了一些值,并且从未遇到过这个问题,也许我的代码不正确,我不知道。
以下是代码要求从页面返回数据:-
createUserInFirestore() async {
// check if user exists
final GoogleSignInAccount user = googleSignIn.currentUser;
DocumentSnapshot doc = await usersRef.document(user.id).get();
//if user does not exist
if (!doc.exists) {
final data = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RegisterPage(),
),
);
usersRef.document(user.id).setData({
"id": user.id,
"email": user.email,
"address": data.item1,
"phoneNo": data.item2,
"displayName": user.displayName,
});
doc = await usersRef.document(user.id).get();
}
currentUser = User.fromDocument(doc);
}
在此处调用函数createUserInFirestore:
handleSignIn(GoogleSignInAccount account) async {
if (account != null) {
await createUserInFirestore();
setState(() {
isAuth = true;
});
print(isAuth);
print("Current user: ${currentUser.displayName}");
} else {
setState(() {
isAuth = false;
});
}
}
这是Navigation.pop()的代码,我希望如何返回数据。
SnackBar snackBar = SnackBar(
content: Text("Your profile has been Registered."),
);
_scaffoldkey.currentState.showSnackBar(snackBar);
Timer(Duration(seconds: 2), () {
Navigator.pop(
context,
Tuple2(address, phoneNo),
);
这是完整的Home()代码:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:sparq/model/user.dart';
import 'package:sparq/pages/register_page.dart';
import 'package:tuple/tuple.dart';
final GoogleSignIn googleSignIn = GoogleSignIn();
final StorageReference storageRef = FirebaseStorage.instance.ref();
final usersRef = Firestore.instance.collection('users');
User currentUser;
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
PageController pageController;
bool isAuth = false;
@override
void initState() {
// TODO: implement initState
super.initState();
pageController = PageController();
googleSignIn.onCurrentUserChanged.listen((account) {
handleSignIn(account);
}, onError: (err) {
print('Error signing in: $err');
});
googleSignIn.signInSilently(suppressErrors: false).then((account) {
handleSignIn(account);
}).catchError((err) {
print('Error signing in: $err');
});
}
handleSignIn(GoogleSignInAccount account) async {
if (account != null) {
await createUserInFirestore();
setState(() {
isAuth = true;
});
print(isAuth);
print("Current user: ${currentUser.displayName}");
} else {
setState(() {
isAuth = false;
});
}
}
createUserInFirestore() async {
// check if user exists
final GoogleSignInAccount user = googleSignIn.currentUser;
DocumentSnapshot doc = await usersRef.document(user.id).get();
//if user does not exist
if (!doc.exists) {
final data = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RegisterPage(),
),
);
usersRef.document(user.id).setData({
"id": user.id,
"email": user.email,
"address": data.item1,
"phoneNo": data.item2,
"displayName": user.displayName,
});
doc = await usersRef.document(user.id).get();
}
currentUser = User.fromDocument(doc);
}
login() {
googleSignIn.signIn();
}
logout() {
googleSignIn.signOut();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
iconTheme: IconThemeData(
color: Colors.white,
),
title: Text(
"title",
style: TextStyle(
color: Colors.white,
),
)),
body: Center(child: Text('My Page!')),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
Container(
height: !isAuth ? 150 : 120,
child: DrawerHeader(
child: !isAuth
? Padding(
padding:
EdgeInsets.symmetric(horizontal: 10, vertical: 15),
child: RaisedButton(
color: Theme.of(context).accentColor,
onPressed: login,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8)),
child: Text(
"Sign in...",
style: TextStyle(
color: Colors.white,
),
),
),
)
: Text(
"Welcome ${currentUser.displayName},",
style: TextStyle(
fontSize: 20,
color: Colors.white,
),
),
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.3),
blurRadius: 10,
spreadRadius: 0,
offset: Offset(-1, 10),
),
],
color: Colors.deepOrange.shade200,
),
),
),
Card(
elevation: 5,
color: Theme.of(context).accentColor,
margin: EdgeInsets.only(
top: 10,
left: 10,
right: 10,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
child: ListTile(
leading: Icon(
Icons.home,
color: Colors.white,
),
title: Text(
'Home',
style: TextStyle(color: Colors.white),
),
onTap: () {
// Update the state of the app
// ...
// Then close the drawer
Navigator.pop(context);
},
),
),
Card(
elevation: 5,
color: Theme.of(context).accentColor,
margin: EdgeInsets.only(
top: 10,
left: 10,
right: 10,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
child: ListTile(
leading: Icon(
Icons.shopping_cart,
color: Colors.white,
),
title: Text(
'Cart',
style: TextStyle(
color: Colors.white,
),
),
onTap: () {
// Update the state of the app
// ...
// Then close the drawer
Navigator.pop(context);
},
),
),
],
),
),
);
}
}
这是完整的RegisterPage()代码:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:sparq/model/user.dart';
import 'package:sparq/pages/home.dart';
import 'package:sparq/widgets/header.dart';
import 'package:tuple/tuple.dart';
User user;
class RegisterPage extends StatefulWidget {
@override
_RegisterPageState createState() => _RegisterPageState();
}
class _RegisterPageState extends State<RegisterPage> {
String address;
String phoneNo;
final _scaffoldkey = GlobalKey<ScaffoldState>();
final _formkey = GlobalKey<FormState>();
submit() {
final form = _formkey.currentState;
form.save();
SnackBar snackBar = SnackBar(
content: Text("Your profile has been Registered."),
);
_scaffoldkey.currentState.showSnackBar(snackBar);
Timer(Duration(seconds: 2), () {
Navigator.pop(
context,
Tuple2(address, phoneNo),
);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldkey,
appBar: header(
titleText: "Set up your Profile",
removeBackButton: true,
),
body: ListView(
children: <Widget>[
Container(
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 25),
child: Center(
child: Text(
"Enter the Following Details.",
style: TextStyle(
fontSize: 20.0,
color: Colors.grey,
),
),
),
),
Padding(
padding: EdgeInsets.all(16),
child: Container(
child: Form(
key: _formkey,
autovalidate: true,
child: Column(
children: <Widget>[
TextFormField(
keyboardType: TextInputType.multiline,
maxLines: null,
onSaved: (val1) => address = val1,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: "Address",
labelStyle: TextStyle(fontSize: 15),
hintText: "Enter your full Address here..."),
),
Padding(
padding: const EdgeInsets.only(top: 10.0),
child: TextFormField(
onSaved: (val2) => phoneNo = val2,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: "Phone no",
labelStyle: TextStyle(fontSize: 15),
hintText: "Enter your Phone no."),
),
)
],
),
),
),
),
GestureDetector(
onTap: submit,
child: Container(
height: 50,
width: 350,
decoration: BoxDecoration(
color: Theme.of(context).accentColor,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.3),
blurRadius: 15,
spreadRadius: 3,
offset: Offset(0, 10),
)
]),
child: Center(
child: Text(
"Submit",
style: TextStyle(
color: Colors.white,
fontSize: 15,
fontWeight: FontWeight.bold,
),
),
),
),
)
],
),
)
],
),
);
}
}