Login is not working in flutter with REST API - flutter

Hi in the below code when I enter my mobile number, password and then click on the login button nothing is happening. My API working in Postman is not working here.
When I press the button it is not working, Entering a valid mobile number and password are not working.
Can anyone help me to find where I did any mistakes?
Login_screen.dart:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:sample_live/home_screen.dart';
import 'package:sample_live/model/login_model.dart';
import 'package:sample_live/splash_screen.dart';
import 'package:sample_live/login_otp.dart';
import 'ProgressHUD.dart';
import 'api/api_service.dart';
class LoginScreen extends StatefulWidget {
String name;
LoginScreen({this.name});
#override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final mobileController = TextEditingController();
final passwordController = TextEditingController();
LoginRequestModel requestModel;
bool isApiCallProcess = false;
GlobalKey<FormState> globalFormKey = GlobalKey<FormState>();
LoginRequestModel loginRequestModel;
final scaffoldKey = GlobalKey<ScaffoldState>();
#override
void initState(){
super.initState();
requestModel=new LoginRequestModel();
}
#override
Widget build(BuildContext context) {
return ProgressHUD(
child: _uiSetup(context),
inAsyncCall: isApiCallProcess,
opacity: 0.3,
);
}
Widget _uiSetup(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Login", style: TextStyle(color: Colors.white)),
centerTitle: true,
),
body:
Stack(
children: [
Padding(
padding: EdgeInsets.all(30),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset('assets/images/hand.png',),
Padding(
padding: EdgeInsets.all(10),
child: Text("Welcome Doctor! ",
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontWeight: FontWeight.bold
),),
),
Padding(
padding: EdgeInsets.all(10),
),
Text("Let's treat everyone great",
style: TextStyle(
color: Colors.black,
fontSize: 15,
),),
Padding(
padding: EdgeInsets.all(10),
),
TextFormField(
minLines: 1,
keyboardType: TextInputType.number,
onSaved: (input) => loginRequestModel.Mobile = input,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
labelText: "Enter Mobile No.",
hintText: "Enter Mobile No.",
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(16.0)))),
),
SizedBox(
height: 10,
),
TextFormField(
onSaved: (input) =>
loginRequestModel.Password = input,
validator: (input) =>
input.length < 3
? "Password should be more than 3 characters"
: null,
minLines: 1,
obscureText: true,
keyboardType: TextInputType.text,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
labelText: "Password",
hintText: "Password",
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(16.0)))),
),
SizedBox(
height: 10,
),
Container(
width: double.infinity,
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 20),
margin: EdgeInsets.symmetric(vertical: 20, horizontal: 20),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30)
),
child: RaisedButton(
color: Color(0xFF0769AA),
onPressed: () {
if (validateAndSave()) {
print(loginRequestModel.toJson());
setState(() {
isApiCallProcess = true;
});
APIService apiService = new APIService();
apiService.login(loginRequestModel).then((value) {
if (value != null) {
setState(() {
isApiCallProcess = false;
});
if (value.Status.isNotEmpty) {
final snackBar = SnackBar(
content: Text("Login Successful"));
scaffoldKey.currentState
.showSnackBar(snackBar);
} else {
final snackBar =
SnackBar(content: Text(value.Message));
scaffoldKey.currentState
// ignore: deprecated_member_use
.showSnackBar(snackBar);
}
}
});
}
},
child: Text(
"Login",
style: TextStyle(color: Colors.white),
),
),
),
SizedBox(
height: 10,
),
Text("Or",
style: TextStyle(
color: Colors.black,
fontSize: 15,
),),
Container(
width: double.infinity,
child: FlatButton(
color: Color(0xFF0769AA),
onPressed: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => LoginOtp("Welcome")),
(route) => false);
},
child: Text(
"Login With OTP",
style: TextStyle(color: Colors.white),
),
),
),
SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
GestureDetector(
onTap: () {
// write your function
Navigator.push(
context,
MaterialPageRoute(
builder: (contex) => SplashScreen()));
},
child: Text(
"Forgot Password",
style: TextStyle(
color: Colors.blue,
fontSize: 16,
fontWeight: FontWeight.bold,
)
)),
],
),
],
),
),
Container(
alignment: Alignment.bottomCenter,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
"By logging in or signing up, you agree to the",
textAlign: TextAlign.end,
style: TextStyle(
color: Colors.black,
fontSize: 12,
),
),
Text(
"Privacy Policy & Terms and Condition",
textAlign: TextAlign.end,
style: TextStyle(
color: Colors.blue,
fontSize: 12,
),
),
],
)
)
]),
);
}
bool validateAndSave() {
final form = globalFormKey.currentState;
if (form.validate()) {
form.save();
return true;
}
return false;
}
}

Related

SingleChildScrollView not working for password textfield in Flutter

I am currently creating my first flutter application. So, when I was testing the login and sign up page. I encountered a problem.
The SingleChildScrollView() is not working in my Flutter login and Signin page for the password textfield only. The SingleChildScrollView() works perfectly for the email textfield. Can someone help me .
Code of Login page :
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:secure_pass/constants/routes.dart';
import 'package:secure_pass/services/auth/auth_exceptions.dart';
import 'package:secure_pass/services/auth/auth_service.dart';
import 'package:secure_pass/utilities/dialogs/error_dialog.dart';
class LoginView extends StatefulWidget {
const LoginView({Key? key}) : super(key: key);
#override
State<LoginView> createState() => _LoginViewState();
}
class _LoginViewState extends State<LoginView> {
late final TextEditingController _email;
late final TextEditingController _password;
#override
void initState() {
_email = TextEditingController();
_password = TextEditingController();
super.initState();
}
#override
void dispose() {
_email.dispose();
_password.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[300],
body: SafeArea(
child: Center(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children:[
//App icon
Icon(
Icons.android,
size: 100,
),
SizedBox(height: 25),
//Hello Again
Text(
'Hello Again!',
style: GoogleFonts.bebasNeue(
fontSize: 52,
),
),
SizedBox(height: 10),
Text(
'Welcome back, you\'ve been missed!',
style: TextStyle(
fontSize: 20,
),
),
SizedBox(height: 50),
//email textfield
Padding(
padding: const EdgeInsets.symmetric(horizontal: 25.0),
child: Container(
decoration: BoxDecoration(
color: Colors.grey[200],
border: Border.all(color: Colors.white),
borderRadius: BorderRadius.circular(12),
),
child: Padding(
padding: const EdgeInsets.only(left: 20.0),
child: TextField(
controller: _email,
enableSuggestions: false,
autocorrect: false,
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
hintText: 'Enter your email here',
border: InputBorder.none
),
),
),
),
),
SizedBox(height: 10),
//Password textfield
Padding(
padding: const EdgeInsets.symmetric(horizontal: 25.0),
child: Container(
decoration: BoxDecoration(
color: Colors.grey[200],
border: Border.all(color: Colors.white),
borderRadius: BorderRadius.circular(12),
),
child: Padding(
padding: const EdgeInsets.only(left: 20.0),
child: TextField(
controller: _password,
obscureText: true,
enableSuggestions: false,
autocorrect: false,
decoration: const InputDecoration(
hintText: 'Enter your password here',
border: InputBorder.none
),
),
),
),
),
SizedBox(height: 10),
TextButton(
onPressed: () async {
final email = _email.text;
final password = _password.text;
try {
await AuthService.firebase().logIn(
email: email,
password: password,
);
final user = AuthService.firebase().currentUser;
if (user?.isEmailVerified ?? false) {
// user's email is verified
Navigator.of(context).pushNamedAndRemoveUntil(
passwordsRoute,
(route) => false,
);
} else {
// user's email is NOT verified
Navigator.of(context).pushNamedAndRemoveUntil(
verifyEmailRoute,
(route) => false,
);
}
} on UserNotFoundAuthException {
await showErrorDialog(
context,
'User not found',
);
} on WrongPasswordAuthException {
await showErrorDialog(
context,
'Wrong credentials',
);
} on GenericAuthException {
await showErrorDialog(
context,
'Authentication error',
);
}
},
//log in button
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 25.0),
child: Container(
padding: EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.deepPurple,
borderRadius: BorderRadius.circular(12),
),
child: Center(
child: const Text(
'Login',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
),
),
),
),
SizedBox(height: 25),
TextButton(
onPressed: () {
Navigator.of(context).pushNamedAndRemoveUntil(
registerRoute,
(route) => false,
);
},
//Not Registered yet ?
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const[
Text(
'Not registered yet?',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
Text(
' Register now',
style: TextStyle(
color: Colors.blue,
fontWeight: FontWeight.bold,
),
),
],
),
)
],
),
),
),
),
);
}
}
You can add bottom padding to the email text field.
Padding(
padding: const EdgeInsets.only(
left: 25,
right: 25,
bottom: MediaQuery.of(context).viewInsets.bottom + 32.0,
),
I assume you want both the email and the password textfield to come up, when the user is entering his data in the respective text fields.
In order to achieve in your scaffold set resizeToAvoidBottomInset property to true and it will work fine
Just Add reverse: true on SingleChildScrollView.
child: Center(
child: SingleChildScrollView(
reverse: true,
child: Column(
I was able to solve the problem by removing the "Center" widget.

Error on my UI using SingleChildScrollView when i try to run my firebase?

this is my first time using community to ask about my project. First thing first, english isn't my first language and I'm a very beginner in flutter world. I'm trying to build my first mobile application using flutter and now I'm trying to connect my project to firebase (I looked at youtube tutorial). I don't know if the firebase already connect because when I'm trying to run the application and go to registration page, there this error message.
And here is my code:
import 'package:dfu_check_application/common/auth_controller.dart';
import 'package:flutter/material.dart';
import 'package:dfu_check_application/common/theme_helper.dart';
import 'package:dfu_check_application/pages/widgets/header_widget.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'profile_page.dart';
class RegistrationPage extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _RegistrationPageState();
}
}
class _RegistrationPageState extends State<RegistrationPage> {
final _formKey = GlobalKey<FormState>();
bool checkedValue = false;
bool checkboxValue = false;
#override
Widget build(BuildContext context) {
var nameController = TextEditingController();
var emailController = TextEditingController();
var passwordController = TextEditingController();
return Scaffold(
backgroundColor: Colors.white,
body: SingleChildScrollView(
child: Stack(children: [
Container(
height: 150,
child: HeaderWidget(150, false, Icons.person_add_alt_1_rounded),
),
Container(
margin: EdgeInsets.fromLTRB(25, 50, 25, 10),
padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
alignment: Alignment.center,
child: Column(
children: [
Form(
key: _formKey,
child: Column(
children: [
GestureDetector(
child: Stack(
children: [
Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(100),
border:
Border.all(width: 5, color: Colors.white),
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.black12,
blurRadius: 20,
offset: const Offset(5, 5),
),
],
),
child: Icon(
Icons.person,
color: Colors.grey.shade300,
size: 80.0,
),
),
Container(
padding: EdgeInsets.fromLTRB(80, 80, 0, 0),
child: Icon(
Icons.add_circle,
color: Colors.grey.shade700,
size: 25.0,
),
),
],
),
),
SizedBox(
height: 30,
),
Container(
child: TextFormField(
controller: nameController,
decoration: ThemeHelper().textInputDecoration(
'Full Name', 'Enter your full name'),
),
decoration: ThemeHelper().inputBoxDecorationShaddow(),
),
SizedBox(
height: 30,
),
SizedBox(height: 20.0),
Container(
child: TextFormField(
controller: emailController,
decoration: ThemeHelper().textInputDecoration(
"E-mail address", "Enter your email"),
keyboardType: TextInputType.emailAddress,
validator: (val) {
// ignore: prefer_is_not_empty
if (!(val!.isEmpty) &&
!RegExp(r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?)*$")
.hasMatch(val)) {
return "Enter a valid email address";
}
return null;
},
),
decoration: ThemeHelper().inputBoxDecorationShaddow(),
),
SizedBox(height: 20.0),
Container(
child: TextFormField(
obscureText: true,
controller: passwordController,
decoration: ThemeHelper().textInputDecoration(
"Password*", "Enter your password"),
validator: (val) {
if (val!.isEmpty) {
return "Please enter your password";
}
return null;
},
),
decoration: ThemeHelper().inputBoxDecorationShaddow(),
),
SizedBox(height: 15.0),
FormField<bool>(
builder: (state) {
return Column(
children: <Widget>[
Row(
children: <Widget>[
Checkbox(
value: checkboxValue,
onChanged: (value) {
setState(() {
checkboxValue = value!;
state.didChange(value);
});
}),
Text(
"I accept all terms and conditions.",
style: TextStyle(color: Colors.grey),
),
],
),
Container(
alignment: Alignment.centerLeft,
child: Text(
state.errorText ?? '',
textAlign: TextAlign.left,
style: TextStyle(
color: Theme.of(context).errorColor,
fontSize: 12,
),
),
)
],
);
},
validator: (value) {
if (!checkboxValue) {
return 'You need to accept terms and conditions';
} else {
return null;
}
},
),
SizedBox(height: 20.0),
GestureDetector(
onTap: () {
AuthController.instance.register(
nameController.text.trim(),
emailController.text.trim(),
passwordController.text.trim());
},
),
Container(
decoration: ThemeHelper().buttonBoxDecoration(context),
child: ElevatedButton(
style: ThemeHelper().buttonStyle(),
child: Padding(
padding: const EdgeInsets.fromLTRB(40, 10, 40, 10),
child: Text(
"Register".toUpperCase(),
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
onPressed: () {
if (_formKey.currentState!.validate()) {
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (context) => ProfilePage()),
(Route<dynamic> route) => false);
}
},
),
),
SizedBox(height: 30.0),
Text(
"Or create account using social media",
style: TextStyle(color: Colors.grey),
),
SizedBox(height: 25.0),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GestureDetector(
child: FaIcon(
FontAwesomeIcons.google,
size: 35,
color: HexColor("#EC2D2F"),
),
onTap: () {
setState(() {
showDialog(
context: context,
builder: (BuildContext context) {
return ThemeHelper().alartDialog(
"Google Account",
"You tap on Google icon.",
context);
},
);
});
},
),
],
),
],
),
),
],
),
),
]),
),
);
}
}
If you guys see more error on my code, please tell me because I'm very clueless about this. Thank you in advance!
The issue occurs from Stack the one inside
Column(
children: [
Form(
key: _formKey,
child: Column(
children: [
GestureDetector(
child: Stack( // this one
Can be fixed by providing hight
GestureDetector(
child: SizedBox(
height: MediaQuery.of(context).size.height, //this based on your need
child: Stack(
I think you can re struct the widget and don't need to use multi-Stack.
More about /ui/layout and Unbounded height / width

email validation flutter before running API

I'm making forget password screen for my app and API has integrated in my code. when I click "reset password" button by submitting empty field it running my API code. but I want to run email validation when I submit empty field and click "reset button". how can I do that part in my code. appreciate your help on this.
import 'package:dio/dio.dart';
import 'package:doctor_app/constants/Button.dart';
import 'package:doctor_app/constants/base_api.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import '../constants/colors.dart';
class ForgetPassword extends StatelessWidget {
const ForgetPassword({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
SystemChrome.setEnabledSystemUIMode(SystemUiMode.leanBack);
return Scaffold(
resizeToAvoidBottomInset: false,
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(
height: 20,
),
Text('DOCTOR',
style: TextStyle(
fontFamily: 'Dubai',
fontSize: 30,
color: Color(0xff05ABA3),
fontWeight: FontWeight.w500,
)),
],
),
SizedBox(
height: 90,
),
Row(mainAxisAlignment: MainAxisAlignment.start, children: [
Text('Forgot your password?',
style: TextStyle(
height: 1.2,
fontFamily: 'Dubai',
fontSize: 25,
color: Color(0xff040000),
fontWeight: FontWeight.w500,
)),
]),
// Spacer(
// flex: 1,
// ),
SizedBox(
height: 20,
),
Column(
//mainAxisAlignment: MainAxisAlignment.center,
//crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text('Confirm your email and we will send the Instructions ',
style: TextStyle(
height: 1.2,
fontFamily: 'Dubai',
fontSize: 18,
color: Color(0xff707070),
fontWeight: FontWeight.w100,
)),
],
),
SizedBox(
height: 20,
),
ForgetPasswordForm(), //email
SizedBox(
height: 5,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'didnt receive an email?',
style: TextStyle(
height: 1.2,
fontFamily: 'Dubai',
fontSize: 13,
color: Colors.grey,
fontWeight: FontWeight.w500,
),
),
SizedBox(
width: 5,
),
Align(
alignment: Alignment.bottomLeft,
child: InkWell(
onTap: () {
// add action here whatever you want.
},
child: Text('send again ',
style: TextStyle(
height: 1.2,
fontFamily: 'Dubai',
fontSize: 13,
color: Colors.blue,
fontWeight: FontWeight.w500,
))))
],
),
Spacer(
flex: 1,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
color: Color(0xff05ABA3),
),
height: 5,
width: 120,
),
],
),
],
),
),
);
}
}
class ForgetPasswordForm extends StatefulWidget {
const ForgetPasswordForm({Key? key}) : super(key: key);
#override
_ForgetPasswordFormState createState() => _ForgetPasswordFormState();
}
class _ForgetPasswordFormState extends State<ForgetPasswordForm> {
final _formKey = GlobalKey<FormState>();
//String _userName = "";
String email = "";
Future Resetpassword() async {
try {
var response = await Dio().post(BASE_API+'user/forgotpassword', data: {
"email": email,
});
if (response.data["data"] ==
"Please check your email to reset password.") {
Get.snackbar("success", "Email Sent Successfully!");
//Get.to(VideoScreen());
} else {
Get.snackbar("Error", "No Server Found",
backgroundColor: textWhite.withOpacity(0.5),
borderWidth: 1,
borderColor: textGrey,
colorText: textGrey,
icon: Icon(
Icons.error_outline_outlined,
color: heartRed,
size: 30,
));
}
print("res: $response");
} catch (e) {
Get.snackbar("Error", "Something went wrong.Please contact admin",
backgroundColor: textWhite.withOpacity(0.5),
borderWidth: 1,
borderColor: textGrey,
colorText: textGrey,
icon: Icon(
Icons.error_outline_outlined,
color: heartRed,
size: 30,
));
print(e);
}
}
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Form(
child: Container(
key: _formKey,
child: Container(
child: Padding(
padding: const EdgeInsets.all(30.0),
child: Column(children: [
TextFormField(
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
hintText: "Email",
hintStyle: TextStyle(
color: textGrey,
fontFamily: "Dubai",
fontSize: 14)),
validator: (String? Email) {
if (Email != null && Email.isEmpty) {
return "Email can't be empty";
}
return null;
},
onChanged: (String? text) {
email = text!;
print(email);
},
),
SizedBox(
height: 50,
),
Container(
child: GestureDetector(
child: ButtonM("Reset Password"),
onTap: () async {
Resetpassword();
},
),
)
]),
)))));
}
}
Just wrap your ResetPassword() method like below:
if (_formKey.currentState!.validate()) {
Resetpassword();
}
This will check the validation.
Make sure key in attached to Form widget not Container
class ForgetPasswordForm extends StatefulWidget {
const ForgetPasswordForm({Key? key}) : super(key: key);
#override
_ForgetPasswordFormState createState() => _ForgetPasswordFormState();
}
class _ForgetPasswordFormState extends State<ForgetPasswordForm> {
final _formKey = GlobalKey<FormState>();
String email = "";
Future Resetpassword() async {
print("123");
}
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Form(
key: _formKey,
autovalidateMode: AutovalidateMode.disabled,
child: Container(
child: Container(
child: Padding(
padding: const EdgeInsets.all(30.0),
child: Column(children: [
TextFormField(
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
hintText: "Email",
hintStyle: TextStyle(
color: Colors.grey,
fontFamily: "Dubai",
fontSize: 14)),
validator: (String? Email) {
if (Email != null && Email.isEmpty) {
return "Email can't be empty";
}
return null;
},
onChanged: (String? text) {
email = text!;
print(email);
},
),
SizedBox(
height: 50,
),
Container(
child: TextButton(
child: Text("Reset Password"),
onPressed: () async {
if (_formKey.currentState!.validate()) {
Resetpassword();
}
},
),
)
]),
)))));
}
}
Add variable
final GlobalKey<FormState> keys = GlobalKey<FormState>();
validate like that
if (_keys.currentState!.validate()) {
Resetpassword();
}

Flutter: Carrying over data from one file to another

I have two files...Workout.dart and Submit.dart. In Workout.dart I have variables: name, sets, rep, pmg, and smg. The use will input things for the variables and then once they click submit, a new page will open displaying the data. However, I don't know how to carry over that data. I'm new to Flutter and Dart, Please help!
Workout.dart
import 'package:flutter/material.dart';
import 'package:gyminprogress/Submit.dart';
class This extends StatefulWidget{
#override
Workout createState() => Workout();
}
class Workout extends State<This> {
String name , sets , rep , pmg , smg ;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueGrey,
appBar: AppBar(
title: Text('Create Workouts'),
centerTitle: true,
),
body: Container(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
TextField(
decoration: InputDecoration(
hintText: 'Exercise Name'
),
style: TextStyle(color:Colors.white),
onChanged: (value){
setState(() {
name = value;
});
},
),
SizedBox(
height: 40.0,
),
TextField(
decoration: InputDecoration(
hintText: 'Primary Muscle Group'
),
style: TextStyle(color:Colors.white),
onChanged: (value){
setState(() {
pmg = value;
});
},
),
SizedBox(
height: 40.0,
),
TextField(
decoration: InputDecoration(
hintText: 'Secondary Muscle Group'
),
style: TextStyle(color:Colors.white),
onChanged: (value){
setState(() {
smg = value;
});
},
),SizedBox(
height: 40.0,
),
TextField(
decoration: InputDecoration(
hintText: 'Reps'
),
style: TextStyle(color:Colors.white),
onChanged: (value){
setState(() {
rep = value;
});
},
),
SizedBox(
height: 40.0,
),
TextField(
decoration: InputDecoration(
hintText: 'Sets'
),
style: TextStyle(color:Colors.white),
onChanged: (value){
setState(() {
sets = value;
});
},
),
Expanded(
child: Container(
child: Column(mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
RaisedButton(
color: Colors.cyan[200],
padding: EdgeInsets.symmetric(
horizontal: 80.0,
vertical: 20.0
,),
child: Text('Submit',style: TextStyle(
color: Colors.black,fontWeight: FontWeight.w200
),) ,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Submit (
)),
);
},
),
]
),]),)
)
]
)
),
),
);
}
}
Submit.dart
import 'package:flutter/material.dart';
import 'package:gyminprogress/Workout.dart';
class Submit extends StatefulWidget{
#override
Enter createState() => Enter();
}
class Enter extends State<Submit> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueGrey,
appBar: AppBar(
title: Text('Create Workouts'),
centerTitle: true,
),
body: Container(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: <Widget>[
Text('Exercise Name : ${Workout.name}',
style: TextStyle(fontSize: 20.0,color: Colors.white, fontWeight: FontWeight.w200),),
Text('Primary Muscle Group : ${Workout.pmg} ',
style: TextStyle(fontSize: 20.0,color: Colors.white, fontWeight: FontWeight.w200),),
Text('Secondary Muscle Group : ${Workout.smg} ',
style: TextStyle(fontSize: 20.0,color: Colors.white, fontWeight: FontWeight.w200),),
Text('Reps : ${Workout.rep}',
style: TextStyle(fontSize: 20.0,color: Colors.white, fontWeight: FontWeight.w200),),
Text('Sets : ${Workout.sets}',
style: TextStyle(fontSize: 20.0,color: Colors.white, fontWeight: FontWeight.w200),),
]
)
)
)
);
}
}
To pass data from one widget to another you have to do two things,
Create a constructor of widget having data which it will accept,
Pass that data while calling it from another widget.
here is the code which solves your problem:
workout.dart
import "package:flutter/material.dart";
import './submit.dart';
class Workout extends StatefulWidget {
#override
_WorkoutState createState() => _WorkoutState();
}
class _WorkoutState extends State<Workout> {
String name, sets, rep, pmg, smg;
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Builder(
builder: (context) => Scaffold(
appBar: AppBar(
title: Text('Create Workouts'),
centerTitle: true,
),
body: Container(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Scaffold(
body: Column(children: <Widget>[
TextField(
decoration: InputDecoration(hintText: 'Exercise Name'),
style: TextStyle(color: Colors.black),
onChanged: (value) {
setState(() {
name = value;
});
},
),
SizedBox(
height: 40.0,
),
TextField(
decoration:
InputDecoration(hintText: 'Primary Muscle Group'),
style: TextStyle(color: Colors.black),
onChanged: (value) {
setState(() {
pmg = value;
});
},
),
SizedBox(
height: 40.0,
),
TextField(
decoration:
InputDecoration(hintText: 'Secondary Muscle Group'),
style: TextStyle(color: Colors.black),
onChanged: (value) {
setState(() {
smg = value;
});
},
),
SizedBox(
height: 40.0,
),
TextField(
decoration: InputDecoration(hintText: 'Reps'),
style: TextStyle(color: Colors.black),
onChanged: (value) {
setState(() {
rep = value;
});
},
),
SizedBox(
height: 40.0,
),
TextField(
decoration: InputDecoration(hintText: 'Sets'),
style: TextStyle(color: Colors.black),
onChanged: (value) {
setState(() {
sets = value;
});
},
),
Expanded(
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
RaisedButton(
color: Colors.cyan[200],
padding: EdgeInsets.symmetric(
horizontal: 80.0,
vertical: 20.0,
),
child: Text(
'Submit',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w600),
),
onPressed: () {
//String name, sets, rep, pmg, smg;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Submit(
name: name,
sets: sets,
rep: rep,
pmg: pmg,
smg: smg,
),
),
);
},
),
]),
]),
))
]))),
),
),
),
);
}
}
submit.dart
import "package:flutter/material.dart";
class Submit extends StatelessWidget {
final String name, sets, rep, pmg, smg;
const Submit({
Key key,
this.name = "",
this.sets = "",
this.rep = "",
this.pmg = "",
this.smg = "",
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueGrey,
appBar: AppBar(
title: Text('Create Workouts'),
centerTitle: true,
),
body: Container(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(children: <Widget>[
Text(
'Exercise Name : ${name}',
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
fontWeight: FontWeight.w200),
),
Text(
'Primary Muscle Group : ${pmg} ',
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
fontWeight: FontWeight.w200),
),
Text(
'Secondary Muscle Group : ${smg} ',
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
fontWeight: FontWeight.w200),
),
Text(
'Reps : ${rep}',
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
fontWeight: FontWeight.w200),
),
Text(
'Sets : ${sets}',
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
fontWeight: FontWeight.w200),
),
]))));
}
}
Output:
New Updated code
Output:
You can pass data in the navigator.
class Workout extends ....> {
String name;
Person(this.name);
}
// Navigate to second screen with data
Navigator.push(context, new MaterialPageRoute(builder: (context) => new SecondScreenWithData(person: new Person("Vishal"))));
Then in the second screen
class SecondScreenWithData extends StatelessWidget {
// Declare a field that holds the Person data
final Person person;
// In the constructor, require a Person
SecondScreenWithData({Key key, #required this.person}) : super(key: key);
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Second Screen With Data"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
// Display passed data from first screen
Text("name: ${person.name}"),
RaisedButton(
child: Text("Back to previous screen"),
onPressed: () {
// Navigate back to first screen when tapped!
Navigator.pop(context);
}
),
],
)
),
);
}

Accessing a function from one to another dart class

I am new to flutter. I have class name LoginCard.dart in this I have another class named _FormPageState which have _validateInputs function `
import 'package:firstapp/Future/app_futures.dart';
import 'package:firstapp/Models/Base/EventObject.dart';
import 'package:firstapp/Widgets/SignupCard.dart';
import 'package:firstapp/utils/constants.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:firstapp/Components/ProgressDialog.dart';
class LoginCard extends StatelessWidget {
#override
Widget build (BuildContext context){
return new Container(
child: new LoginFormContainer(),
);
}
}
class LoginFormContainer extends StatefulWidget{
// #override
// _FormPageState createState() => _FormPageState();
State<StatefulWidget> createState() {
return _FormPageState();
}
}
class _FormPageState extends State<LoginFormContainer>{
final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
bool _autoValidate = false;
// bool _obscureText = true;
String _email;
String _password;
ProgressDialog progressDialog = ProgressDialog
.getProgressDialog(ProgressDialogTitles.USER_LOG_IN);
#override
Widget build(BuildContext context) {
return new Container(
width: double.infinity,
height: ScreenUtil.getInstance().setHeight(500),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8.0),
boxShadow: [
BoxShadow(
color: Colors.black12,
offset: Offset(0.0, 15.0),
blurRadius: 15.0),
BoxShadow(
color: Colors.black12,
offset: Offset(0.0, -10.0),
blurRadius: 10.0),
]),
child: Padding(
padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0),
child: new Form(
key: _formKey,
autovalidate: _autoValidate,
child: new Stack(
children: <Widget>[loginFormUI(), progressDialog]
)
),
),
);
}
Widget loginFormUI(){
return new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("Login",
style: TextStyle(
fontSize: ScreenUtil.getInstance().setSp(45),
fontFamily: "Poppins-Bold",
letterSpacing: .6)),
SizedBox(
height: ScreenUtil.getInstance().setHeight(30),
),
Text("Username",
style: TextStyle(
fontFamily: "Poppins-Medium",
fontSize: ScreenUtil.getInstance().setSp(26))),
new TextFormField(
autofocus: true,
keyboardType: TextInputType.text,
validator: validateEmail,
onSaved: (val) =>
_email = val,
decoration: InputDecoration(
hintText: "username",
hintStyle: TextStyle(color: Colors.grey, fontSize: 12.0)),
),
SizedBox(
height: ScreenUtil.getInstance().setHeight(30),
),
Text("Password",
style: TextStyle(
fontFamily: "Poppins-Medium",
fontSize: ScreenUtil.getInstance().setSp(26))),
new TextFormField(
obscureText: true,
keyboardType: TextInputType.text,
validator: validatePassword,
onSaved: (val) =>
_password = val,
decoration: InputDecoration(
hintText: "Password",
hintStyle: TextStyle(color: Colors.grey, fontSize: 12.0)),
),
SizedBox(
height: ScreenUtil.getInstance().setHeight(35),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Text(
"Forgot Password?",
style: TextStyle(
color: Colors.blue,
fontFamily: "Poppins-Medium",
fontSize: ScreenUtil.getInstance().setSp(28)),
)
],
)
],
);
}
String validateEmail(String value){
Pattern pattern = r'^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
RegExp regex = new RegExp(pattern);
if(value.isEmpty)
return "Email is required";
else if(!regex.hasMatch(value))
return 'Enter valid email';
else
return null;
}
String validatePassword(String value){
if (value.isEmpty)
return "Password is required";
else
return null;
}
void _validateInputs() {
if (_formKey.currentState.validate()){
print("hello");
// If all data are correct then save data to out variables
_formKey.currentState.save();
FocusScope.of(context).requestFocus(new FocusNode());
progressDialog.showProgress();
// _addNewUser();
_performLogin();
} else {
// If all data are not valid then start auto validation.
setState(() {
_autoValidate = true;
});
}
}
void _performLogin() async{
EventObject eventObject = await performLogin(_email, _password);
}
}
`
and Another class name is main.dart `
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'Widgets/LoginCard.dart';
import 'Widgets/SocialIcons.dart';
import 'CustomIcons.dart';
import 'signup.dart';
//
void main() => runApp(MaterialApp(
home: MyApp(),
debugShowCheckedModeBanner: false,
));
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool _isSelected = false;
// _FormPageState formPageState;
void _radio() {
setState(() {
_isSelected = !_isSelected;
});
}
Widget radioButton(bool isSelected) => Container(
width: 16.0,
height: 16.0,
padding: EdgeInsets.all(2.0),
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(width: 2.0, color: Colors.black)),
child: isSelected
? Container(
width: double.infinity,
height: double.infinity,
decoration:
BoxDecoration(shape: BoxShape.circle, color: Colors.black),
)
: Container(),
);
Widget horizontalLine() => Padding(
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Container(
width: ScreenUtil.getInstance().setWidth(120),
height: 1.0,
color: Colors.black26.withOpacity(.2),
),
);
#override
Widget build(BuildContext context) {
ScreenUtil.instance = ScreenUtil.getInstance()..init(context);
ScreenUtil.instance =
ScreenUtil(width: 750, height: 1334, allowFontScaling: true);
return new Scaffold(
backgroundColor: Colors.white,
resizeToAvoidBottomPadding: true,
body: Stack(
fit: StackFit.expand,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 100.0),
child: Image.asset("assets/carscartoon.png"),
),
Expanded(
child: Container(),
),
Image.asset("assets/image_02.png")
],
),
SingleChildScrollView(
child: Padding(
padding: EdgeInsets.only(left: 28.0, right: 28.0, top: 60.0),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Image.asset(
"assets/tlrlogo.png",
width: ScreenUtil.getInstance().setWidth(110),
height: ScreenUtil.getInstance().setHeight(110),
),
Text("Transport Levy Record",
style: TextStyle(
fontFamily: "Poppins-Bold",
fontSize: ScreenUtil.getInstance().setSp(30),
letterSpacing: .6,
fontWeight: FontWeight.bold))
],
),
SizedBox(
height: ScreenUtil.getInstance().setHeight(180),
),
LoginCard(),
SizedBox(height: ScreenUtil.getInstance().setHeight(40)),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
SizedBox(
width: 12.0,
),
GestureDetector(
onTap: _radio,
child: radioButton(_isSelected),
),
SizedBox(
width: 8.0,
),
Text("Remember me",
style: TextStyle(
fontSize: 12, fontFamily: "Poppins-Medium"))
],
),
InkWell(
child: Container(
width: ScreenUtil.getInstance().setWidth(330),
height: ScreenUtil.getInstance().setHeight(100),
decoration: BoxDecoration(
gradient: LinearGradient(colors: [
Color(0xFF17ead9),
Color(0xFF6078ea)
]),
borderRadius: BorderRadius.circular(6.0),
boxShadow: [
BoxShadow(
color: Color(0xFF6078ea).withOpacity(.3),
offset: Offset(0.0, 8.0),
blurRadius: 8.0)
]),
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: () {
// LoginFormContainer()
},
child: Center(
child: Text("SIGNIN",
style: TextStyle(
color: Colors.white,
fontFamily: "Poppins-Bold",
fontSize: 18,
letterSpacing: 1.0)),
),
),
),
),
)
],
),
SizedBox(
height: ScreenUtil.getInstance().setHeight(40),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
horizontalLine(),
Text("Social Login",
style: TextStyle(
fontSize: 16.0, fontFamily: "Poppins-Medium")),
horizontalLine()
],
),
SizedBox(
height: ScreenUtil.getInstance().setHeight(40),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SocialIcons(
colors: [
Color(0xFF102397),
Color(0xFF187adf),
Color(0xFF00eaf8),
],
iconData: CustomIcons.facebook,
onPressed: () {},
),
SocialIcons(
colors: [
Color(0xFFff4f38),
Color(0xFFff355d),
],
iconData: CustomIcons.googlePlus,
onPressed: () {},
),
SocialIcons(
colors: [
Color(0xFF17ead9),
Color(0xFF6078ea),
],
iconData: CustomIcons.twitter,
onPressed: () {},
),
SocialIcons(
colors: [
Color(0xFF00c6fb),
Color(0xFF005bea),
],
iconData: CustomIcons.linkedin,
onPressed: () {},
)
],
),
SizedBox(
height: ScreenUtil.getInstance().setHeight(30),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"New User? ",
style: TextStyle(fontFamily: "Poppins-Medium"),
),
InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder:
(context) => Signup()));
},
child: Text("SignUp",
style: TextStyle(
color: Color(0xFF5d74e3),
fontFamily: "Poppins-Bold")),
)
],
)
],
),
),
)
],
),
);
}
}
`
On line No. 143 there is onTap function of SignIn button in my main.dart class, I want access _validateInputs() function of _FormPageState.
I am new in dart. Please let me know, if any solution for this.
Put _validateInputs() function and all variables in main.dart file which is used in LoginCard.dart file and pass variables to Logincard constructor as argument from main.dart file.
In main.dart file
final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
pass _formkey to LoginCard() constructor
LoginCard(_formKey);
in LoginCard.dart file
class LoginCard extends StatelessWidget {
final GlobalKey<FormState> formKey;
LoginCard(this.formKey);
#override
Widget build (BuildContext context){
return new Container();
}