How to achieve this design using flutter? - flutter

I want to achieve this:
For now, I have this:
This is my code:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class LogInEnterEmailPassword extends StatefulWidget {
const LogInEnterEmailPassword({Key? key}) : super(key: key);
#override
State<LogInEnterEmailPassword> createState() => _LogInEnterEmailPasswordState();
}
class _LogInEnterEmailPasswordState extends State<LogInEnterEmailPassword> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xffF6F6F6),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text("Enter Email",
style: TextStyle(
fontSize: 25,
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
color: Color(0xff313640),
),),
Text("______________________________",
style: TextStyle(
fontSize: 25,
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
color: Color(0xff313640),
),),
Text("Enter Password",
style: TextStyle(
fontSize: 25,
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
color: Color(0xff313640),
),),
Text("______________________________",
style: TextStyle(
fontSize: 25,
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
color: Color(0xff313640),
),),
],
)
)
);
}
}
I tried using sizedBox(), but no luck, my design shows a lot of space and I don't like that, it doesn't look great in my opinion, so, I have to erase the MainAxisAlignment to achieve the first design? Or what properties do I have to write?
Thank you in advance

Could you try to change MainAxisAlignment from spaceEvenly to center? You could see the difference between them.
Actually, I fully use SizeBox to separate them with specific spaces.
mainAxisAlignment: MainAxisAlignment.spaceEvenly
mainAxisAlignment: MainAxisAlignment.center
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Padding(
padding: EdgeInsets.symmetric(horizontal: 24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Flexible(
child: Hero(
tag: 'logo',
child: Container(
height: 200.0,
child: Image.asset('images/logo.png'),
),
),
),
SizedBox(
height: 48.0,
),
TextField(
keyboardType: TextInputType.emailAddress,
textAlign: TextAlign.center,
onChanged: (value) {
email = value;
//Do something with the user input.
}, decoration: kTextFieldDecoration.copyWith(hintText: 'Eenter your email')),
SizedBox(
height: 8.0,
),
TextField(
obscureText: true,
textAlign: TextAlign.center,
onChanged: (value) {
password = value;
//Do something with the user input.
},
decoration: kTextFieldDecoration.copyWith(hintText: 'Eenter your password')),
SizedBox(
height: 24.0,
),
RoundButton(
title: 'Register',
colour: Colors.blueAccent,
onPressed: () async{
print(email);
print(password);
print('Register');
//Go to login screen.
// Navigator.pushNamed(context, RegistrationScreen.id);
try{
final newUser = await _auth.createUserWithEmailAndPassword(email: email, password: password);
if (newUser != null) {
Navigator.pushNamed(context, ChatScreen.id);
}
}
catch(e) {
print(e);
}
},
),
],
),
),
);
enter image description here

Related

DioError [DioErrorType.response] Http status error [404] - flutter

DioError [DioErrorType.response] Http status error [404] - flutter
I'm creating a forget password screen for my app. I want to display "email sent" message when I click "Reset password " button.. instead of that ,I'm getting above error when I'm enter already registered email address. postman request is successfully working. how to solve this issue. appreciate your help on this.
import 'package:dio/dio.dart';
import 'package:doctor_app/constants/Button.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,
)),
],
),
Spacer(
flex: 1,
),
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,
),
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,
)),
],
),
Spacer(
flex: 1,
),
ForgetPasswordForm(), //email
Spacer(
flex: 1,
),
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(
'https://doctor-app2-hit.herokuapp.com/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 User Found");
}
print("res: $response");
} catch (e) {
Get.snackbar("error", "Server Error");
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;
}),
SizedBox(
height: 50,
),
Container(
child: GestureDetector(
child: ButtonM("Reset Password"),
onTap: () async {
Resetpassword();
},
),
)
]),
)))));
}
}
404 is thrown since the endpoint you are trying to call cannot be found. Notice that the URL you try to call has two forward slashes before the user path.
Change this: https://doctor-app2-hit.herokuapp.com//user/forgotpassword
to this: https://doctor-app2-hit.herokuapp.com/user/forgotpassword

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);
}
),
],
)
),
);
}

Flutter Dart Error Format Timestep from Cloud_Firestore into Date

I Store the Meal and the Date in Cloud_Firestore. Getting it back, it looks like this shown on the Screen Show.
I tried to formate the Timestamp with DateTime but this doesn't work.
I also tried it with the intl.dart Package to format it,
How can I parse the Timestamp and Format it into Year,Month and Day?
Code
import 'package:flutter/material.dart';
import 'package:mealapp/models/Widgets/whenAndWhatToEat.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:intl/intl.dart';
import 'package:mealapp/models/global.dart';
class MealTile extends StatefulWidget {
final MealsAndWhen mealsAndWhen;
MealTile ({ this.mealsAndWhen });
#override
MealTileState createState() {
return MealTileState();
}
}
class MealTileState extends State<MealTile> {
String id;
final db = Firestore.instance;
String meal;
Widget buildItem(DocumentSnapshot doc) {
return Container(
margin: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
'Meal: ${doc.data['Meal']}',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Colors.white),
textAlign: TextAlign.center,
),
Text(
'Date: ${doc.data['Date']}',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white),
textAlign: TextAlign.center,
),
SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
SizedBox(width: 8),
FlatButton(
onPressed: () => deleteData(doc),
child: Text('Delete',
style: TextStyle(fontWeight: FontWeight.bold,
color: Colors.white)
),
),
],
),
],
),
decoration: BoxDecoration(
color: lightBlueColor,
borderRadius: BorderRadius.all(Radius.circular(12)),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: darkGreyColor,
body: ListView(
padding: EdgeInsets.only(top: 220),
children: <Widget>[
StreamBuilder<QuerySnapshot>(
stream: db.collection('mealList').snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(children: snapshot.data.documents.map((doc) => buildItem(doc)).toList());
} else {
return SizedBox();
}
},
)
],
),
);
}
void deleteData(DocumentSnapshot doc) async {
await db.collection('mealList').document(doc.documentID).delete();
setState(() => id = null);
}
}
You can try to convert it to date before printing.
Text(
'Date: ${doc.data['Date'].toDate()}',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white),
textAlign: TextAlign.center,
),

How to Turn Some Functions to an Independent Widget in Flutter?

I need to turn these two functions : _collectKeywords and _matchKeywords into a Widget, so I can reuse them another time. I have tried it, but I don't know how and where to instatiate the a widget that only processes data without returning any value. Can somebody help me?
//please don't mind the UI, button's color, etc
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttermatchcard/cardButton.dart';
class MainMenu extends StatelessWidget {
void _accessCardMatcher(String butKeyword)
{
_collectKeywords(butKeyword);
}
//================================================
String _keyword_1;
String _keyword_2;
void _collectKeywords(String _keyword_now){
if(_keyword_1==null)
{
_keyword_1=_keyword_now;
}
else{
_keyword_2=_keyword_now;
_matchKeyword(_keyword_1,_keyword_2);
}
}
void _matchKeyword(_keyWord_one, _keyWord_two){
if(_keyWord_one==_keyWord_two){
//Lock the But
print("MATCH!!!!");
}
_keyword_1=null;
_keyword_1=null;
}
//================================================
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
//textBaseline: ,
children: <Widget>[
Container(
child: Text("Match Card", style: TextStyle(
fontSize: 50,
color: Colors.amber,
fontFamily: "FreeHand"
),
),
),
Icon( Icons.filter_none,
color: Colors.amber,
size: 40,
),
SizedBox(
height: 30,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
//But Start
CardButton(
onTapExecute:_accessCardMatcher,
keyword: "start",
text: Text("STA", style: TextStyle(
fontSize: 20,
),),
alignment: Alignment.centerRight,
),
//But Start2
CardButton(
onTapExecute:_accessCardMatcher,
keyword: "start",
text: Text("RT", style: TextStyle(
fontSize: 20,
),),
alignment: Alignment.centerLeft,
),
SizedBox(
width: 10,
),
//But Option
CardButton(
onTapExecute:_accessCardMatcher,
keyword: "option",
text: Text("OPT", style: TextStyle(
fontSize: 20,
),),
alignment: Alignment.centerRight,
),
CardButton(
onTapExecute:_accessCardMatcher,
keyword: "option",
text: Text("ION", style: TextStyle(
fontSize: 20,
),),
alignment: Alignment.centerLeft,
),
],
),
SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
//But
CardButton(
onTapExecute:_accessCardMatcher,
keyword: "credit",
text: Text("CRE", style: TextStyle(
fontSize: 20,
),),
alignment: Alignment.centerRight,
),
CardButton(
onTapExecute:_accessCardMatcher,
keyword: "credit",
text: Text("DIT", style: TextStyle(
fontSize: 20,
),),
alignment: Alignment.centerLeft,
),
],
)
],
)
);
}
}
Its a sample, Modify as your requirement !
class MyWidget extends StatefulWidget {
#override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
int buttonCount = 0;
String textYouWantToModify = '';
TextEditingController te;
CommonMethods methods = CommonMethods();
#override
void initState() {
super.initState();
te = TextEditingController();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(title: Text('Title')),
body: Container(
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
//Other widgets like TextFiled to save text......or whatever
TextField(
controller: te,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Type something 1',
labelStyle: TextStyle(color: Colors.black)),
style: TextStyle(color: Colors.black)
),
RaisedButton(
color: Colors.black,
onPressed: () {
setState(() {
buttonCount++;
if (buttonCount == 2) {
methods.method1(te.text);
methods.method2();
}
});
},
child:
Text('Button 1', style: TextStyle(color: Colors.white))),
RaisedButton(
onPressed: () {
setState(() {
buttonCount++;
if (buttonCount == 2) {
methods.method1(te.text);
methods.method2();
}
});
},
child:
Text('Button 2', style: TextStyle(color: Colors.black))),
//Other widgets.....
]))));
}
}
class CommonMethods {
void method1(String s) {
//your code.....
print(s);
}
void method2() {
//your code.....
}
}