on login page navigation am sending the response - flutter

Am trying to achieve app that if person logged in the response of app is sent to another screen. here it is asking to add the same details in splash screen, am using shared preferences to see the user is logged in or not. how can we fix this issue.
splash.dart
#override
void initState() {
super.initState();
// navigate();
getValidationData().whenComplete(() async {
Future.delayed(const Duration(seconds: 6), () {
PageNavigator(ctx: context).nextPageOnly(
page: finalEmail == null ? const LoginPage() : const HomeScreen(// what to do here));
});
});
}
login.dart
///Save users data and then navigate to homepage
final int userId = res['userId'];
final String token = res['token'];
final bool recharge = res['recharge'];
final String name = res['name'];
PageNavigator(ctx: context).nextPageOnly(
page: HomeScreen(
userId: userId,
token: token,
recharge: recharge,
name: name,
));
home.dart
class HomeScreen extends StatefulWidget {
final int userId;
final String token;
final bool recharge;
final String name;
const HomeScreen({
Key? key,
required this.userId,
required this.token,
required this.recharge,
required this.name,
}) : super(key: key);

Related

fetching data. for user from firebase for flutter gives null

After i have created the sign in and signup in flutter and i have connect it to firebase, i added a textfield for the name of the user. So if the user register his name also will be stored, then this data is saved into firebase with the id of the user. The problem is when i try to fetch this data my these method it gives me null ,
This is the way how i am fetching the data of the user :
class WelcomePage extends StatefulWidget {
String email;
WelcomePage ({Key? key, required this.email}) : super(key: key);
#override
State<WelcomePage> createState() => _WelcomePageState();
}
class _WelcomePageState extends State<WelcomePage> {
ScrollController? _scrollcontroller;
final FirebaseAuth _auth =FirebaseAuth.instance;
String? _name ;
String? _uid;
#override
void initState() {
super.initState();
_scrollcontroller = ScrollController();
_scrollcontroller?.addListener(() {
setState(() {});
});
getData();
}
void getData() async{
User? user = _auth.currentUser;
_uid = user!.uid;
final DocumentSnapshot userDoc =
await FirebaseFirestore.instance.collection('users').doc(user.uid).get();
_name = userDoc.get('name');
}

"'key' is required, but there's no corresponding argument" flutter error

How to solve this error?
The named parameter 'key' is required, but there's no corresponding argument. (Documentation) Try adding the required argument.
error
Future<void> onJoin() async {
// update input validation
setState(() {
_channelController.text.isEmpty
? _validateError = true
: _validateError = false;
});
if (_channelController.text.isNotEmpty) {
await _handleCameraAndMic(Permission.camera);
await _handleCameraAndMic(Permission.microphone);
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VideoCall(
channelName: _channelController.text,
role: _role,
),
),
);
}
}
class VideoCall
class VideoCall extends StatefulWidget {
final String channelName;
final ClientRole role;
const VideoCall({Key key, required this.channelName, required this.role})
: super(key: key);
#override
_VideoCallState createState() => _VideoCallState();
}
class _VideoCallState extends State<VideoCall> {
final _users = <int>[];
final _infoStrings = <String>[];
bool muted = false;
late RtcEngine _engine;
#override
void dispose() {
// clear users
_users.clear();
// destroy sdk
_engine.leaveChannel();
_engine.destroy();
super.dispose();
}
#override
void initState() {
super.initState();
// initialize agora sdk
initialize();
}
this is the videoCall class in there no any error shows.
when add "key" show this
When remove required property from key in video call class
show this error
In VideoCall class, key property set as a required, change it to optional:
class VideoCall extends StatefulWidget {
final String? channelName;
final ClientRole? role;
const VideoCall({Key? key, this.channelName, this.role})
: super(key: key);
#override
_VideoCallState createState() => _VideoCallState();
}

Payment through razorpay on flutter web produces error

I had implemented the razorpay payment gateway in my flutter project of an ecom store.
The payment works fine on mobile platform, but on web it is creating an issue. On web the user is redirected to different file named webpayment for making payment.
On web, when the user pays for an item on list page, the first time the webpayment gets succeeded and the user is redirected to detail page and on detail page when back button is pressed the user gets redirected to list page where other items are listed.
But when user pays for another item on list page the details of previous item whose payment was made is sent to webpayment page not the item on which the user had clicked.
Hot reloading the web,solves the problem but, now if after making another payment ,if user try to purchase another item the details of previous item is sent to the web payment page.Means user need to reload the page in web for making payment to another product.
The mobile app is working fine.There is some state management issue,I think in webpayment page which forces the details of previous purchased item to persist.
Below is the webpayment code which redirects user from list page to web payment page:
class Webpayment extends StatefulWidget {
final String? name;
final Map? buyer;
final String? postId;
final String? userId;
final String? category;
final String? usercity;
final double? price;
Webpayment({
Key? key,
this.name,
this.buyer,
this.postId,
this.userId,
this.category,
this.usercity,
this.price,
}) : super(key: key);
#override
_WebpaymentState createState() => _WebpaymentState(this.name, this.buyer,
this.postId, this.userId, this.category, this.usercity, this.price);
}
class _WebpaymentState extends State<Webpayment>
with AutomaticKeepAliveClientMixin<Webpayment> {
final String? name;
final Map? buyer;
final String? postId;
final String? userId;
final String? category;
final String? usercity;
final double? price;
_WebpaymentState(this.name, this.buyer, this.postId, this.userId,
this.category, this.usercity, this.price);
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
super.build(context);
ui.platformViewRegistry.registerViewFactory("rzp-html", (int viewId) {
IFrameElement element = IFrameElement();
window.onMessage.forEach((element) {
print('Event Received in callback: ${element.data}');
if (element.data == 'MODAL_CLOSED') {
} else if (element.data == 'SUCCESS') {
print('PAYMENT SUCCESSFULL!!!!!!! ${widget.postId}');
var userid = auth.currentUser!.uid.toString();
FirebaseFirestore.instance
.collection('${widget.category}${widget.usercity}')
.doc(widget.postId)
.update({'buyer.$userid': "true", 'deal': "Completed"});
Navigator.push(
this.context,
MaterialPageRoute(
builder: (context) => CategoryFeedDetail(
postId: widget.postId,
userId: widget.userId,
category: widget.category,
usercity: widget.usercity,
),
));
}
});
element.src =
'assets/payments.html?name=${widget.name}&price=${widget.price}';
element.style.border = 'none';
return element;
});
return Scaffold(body: Builder(builder: (BuildContext context) {
return Container(
child: HtmlElementView(viewType: 'rzp-html'),
);
}));
}
#override
void dispose() {
// TODO: implement dispose
super.dispose();
}
#override
bool get wantKeepAlive => false;
}
After payment the user is redirected to detail page and on detail page follwing is the code is there on back press to go on list page
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => CategoryFeed(
widget.userId, widget.usercity, widget.category),
),
);
}),

Unable to get bool value in Getx Flutter

I am trying to develop login checker. The following code should redirect to HomeScreen when user is loggedin and to LoginPage in User is not loggedin. But it only gets redirect to LoginScreen() not to HomeScreen() even though it's already logged in.
User Model:
class User {
User({
required this.id,
required this.name,
required this.email,
required this.cart,
});
String id;
String name;
String email;
List cart;
}
UserController:
class UserController extends GetxController {
RxString id = ''.obs;
RxBool isLoggedIn = false.obs;
RxString name = ''.obs;
RxString email = ''.obs;
RxString image = ''.obs;
RxList cart = [].obs;
final NetworkHandler _handler = NetworkHandler();
#override
void onInit() {
super.onInit();
getUserDetails();
}
getUserDetails() {
User _user = _handler.userDetails();
id.value = _user.id;
if (id.value != '') {
isLoggedIn.value = true;
}
name.value = _user.name;
}
}
Checker Screen
class StateCheck extends StatelessWidget {
var controller = Get.put(UserController());
StateCheck({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
SizeConfig().init(context);
return Obx(
() => controller.isLoggedIn.value
? const HomeScreen()
: const LoginScreen(),
);
}
}
First you have to set login value in SharedPreferences.
when login success
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool("isLogin", true);
log out
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool("isLogin", false);
You can Check login state || check this in splash screen for best practice (inside init method)
if(prefs.getBool('isLogin')==null||prefs.getBool('isLogin')==false){
// login screen
}else{
// home screen
}

Undefined name user

I have 3 screens, login, homepage and chat. In chat I want to use user, but for some reasons I am getting an error.
Error in HomePage class while trying to pass user to the Chat: 'Undefined name 'user''.
Here samples of code:
class Login extends StatefulWidget {
#override
_LoginState createState() => _LoginState();
}
class _LoginState extends State<Login> {
String email;
String password;
final FirebaseAuth _auth = FirebaseAuth.instance;
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
Future<String> login(String _email, String _password) async {
FirebaseUser user = (await _firebaseAuth.signInWithEmailAndPassword(
email: _email, password: _password))
.user;
() =>
Navigator.push(context, MaterialPageRoute(builder: (context) => Bar(user: user)));
}
...
Why is it not defined? I want to pass user from Login(), through Homepage() to the Chat().
Thank you in advance
EDIT:
I noticed it is not defined only in List, but besides it works properly.
How can I pass it to the list?
class HomePage extends StatefulWidget {
final FirebaseUser user;
const HomePage({Key key, this.user}) : super(key:key);
#override
_BarState createState() => _BarState();
}
class _BarState extends State<HomePage> {
void test() {
() =>
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) =>
Chat(user: widget.user))); < ---- WORKING
}
int tabIndex = 0;
List<Widget> widgetOptions = [
Match(),
Chat(user: widget.user), < --- NOT WORKING
AddBook(),
Profile(),
];
Here you want to access user object in other screen, instead of passing it in cconstructor, create a singleton class, Like this
class AuthUser {
static var authUserId;
static var email;
static var userName;
static var role;
static var companyId;
}
During login Set values like this, please check here print(user); and set value respectively
Future<String> login(String _email, String _password) async {
FirebaseUser user = (await _firebaseAuth.signInWithEmailAndPassword(
email: _email, password: _password))
.user;
() =>
AuthUser.email = user.email,
AuthUser.email = user.userName,
..........
));
}
Access data in other screens like, AuthUser.email, AuthUser.userName.....
Use Chat(user: widget.user) instead.
when you are using a stateful widgets and what to get properties from constructor you need to do it like this:
widget.varNameInConstructor
most of the time it's not needed but if you want to assign that to you own new variable in state you can do it at initState.