Pass Value between two class in Flutter - flutter

How can pass two String between two class? I have a Signin Class where i have two TextField for email and password. Then I have a Button class but I don't know how get email and password String.
I would not create a single class to keep tidy my code.
This is my code:
SigninClass
import 'package:cleverpot/Activity/home.dart';
import 'package:cleverpot/Helper/authelper.dart';
import 'package:cleverpot/signin/signout/Header.dart';
import 'package:cleverpot/signin/signout/InputField.dart';
import 'package:cleverpot/signin/signout/InputWrapper.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
class Signup extends StatefulWidget {
Signup({Key? key}) : super(key: key);
#override
_nameState createState() => _nameState();
}
class _nameState extends State<Signup> {
String email = "";
String password = "";
authHelper _helper = authHelper();
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: Container(
width: double.infinity,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
colors: [Colors.green, Colors.greenAccent])),
child: Column(
children: [
SizedBox(
height: 80,
),
Header(),
Expanded(
child: Container(
decoration: BoxDecoration(
color: Colors.green[300],
borderRadius: BorderRadius.only(
topLeft: Radius.circular(60),
topRight: Radius.circular(60))),
child: InputWrapper(),
))
],
),
),
);
}
}
InputWrapper Class:
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'Button.dart';
import 'InputField.dart';
class InputWrapper extends StatefulWidget {
InputWrapper({Key? key}) : super(key: key);
#override
_InputWrapperState createState() => _InputWrapperState();
}
class _InputWrapperState extends State<InputWrapper> {
String email = '';
String password = '';
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(30),
child: Column(
children: <Widget>[
SizedBox(
height: 20,
),
Container(
decoration: BoxDecoration(
color: Colors.white, borderRadius: BorderRadius.circular(10)),
child: InputField(),
),
SizedBox(
height: 20,
),
RichText(
text: TextSpan(
text: "Password dimenticata?",
style: TextStyle(color: Colors.grey),
recognizer: TapGestureRecognizer()
..onTap = () {
print("Cliccato");
})),
SizedBox(
height: 20,
),
Button(),
SizedBox(
height: 20,
),
Container(
decoration: BoxDecoration(
color: Colors.green[500],
borderRadius: BorderRadius.circular(50)),
child: RichText(
text: TextSpan(
text: "Non sei registrato? Clicca qua",
style: TextStyle(color: Colors.black),
recognizer: TapGestureRecognizer()
..onTap = () {
Navigator.of(context).push(PageRouteBuilder(
opaque: false,
pageBuilder: (BuildContext context, _, __) {
return Registration();
}));
print("Cliccato");
})),
),
],
),
);
}
InputField Class:
import 'package:flutter/material.dart';
class InputField extends StatefulWidget {
InputField({Key? key}) : super(key: key);
#override
_InputFieldState createState() => _InputFieldState();
}
class _InputFieldState extends State<InputField> {
String password = '';
String email = '';
String getil() {
return password;
}
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: Color(4294638330)))),
child: TextField(
decoration: InputDecoration(
hintText: "Enter your email",
hintStyle: TextStyle(color: Colors.grey),
border: InputBorder.none),
),
),
Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: Color(4294638330)))),
child: TextField(
onChanged: (value) {
setState(() {
password = value;
print(password);
});
},
decoration: InputDecoration(
hintText: "Enter your password",
hintStyle: TextStyle(color: Colors.grey),
border: InputBorder.none),
),
),
],
);
;
}
}
And Button Class:
import 'package:cleverpot/Helper/authelper.dart';
import 'package:cleverpot/signin/signout/InputField.dart';
import 'package:flutter/material.dart';
class Button extends StatelessWidget {
authHelper _helper = authHelper();
#override
Widget build(BuildContext context) {
return Container(
height: 50,
margin: EdgeInsets.symmetric(horizontal: 50),
decoration: BoxDecoration(
color: Colors.cyan[500],
borderRadius: BorderRadius.circular(10),
),
child: Center(
child: ElevatedButton(
onPressed: () {
print(fieldState.getil());
},
child: Text(
"Accedi",
style: TextStyle(
color: Colors.white, fontSize: 15, fontWeight: FontWeight.bold),
),
),
),
);
}
}
I have to get Email and Password from InputField in InputWrapper and put inside Button Class in InputWrapper

You should Lift your state up. This is a general advice in flutter, the state variables should be contained in a stateful widget which is common to every widget you want to share the variables to.
In your case something like this:
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
class Signup extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: Container(
width: double.infinity,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter, colors: [Colors.green, Colors.greenAccent])),
child: Column(
children: [
SizedBox(
height: 80,
),
Header(),
Expanded(
child: Container(
decoration: BoxDecoration(
color: Colors.green[300],
borderRadius: BorderRadius.only(
topLeft: Radius.circular(60), topRight: Radius.circular(60))),
child: InputWrapper(),
),
),
],
),
),
);
}
}
class InputWrapper extends StatefulWidget {
InputWrapper({Key? key}) : super(key: key);
#override
_InputWrapperState createState() => _InputWrapperState();
}
class _InputWrapperState extends State<InputWrapper> {
String email = '';
String password = '';
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(30),
child: Column(
children: <Widget>[
SizedBox(
height: 20,
),
Container(
decoration:
BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(10)),
child: InputField(
email: email,
password: password,
onEmailChanged: (value) => setState(() => email = value),
onPasswordChanged: (value) => setState(() => password = value),
),
),
SizedBox(
height: 20,
),
RichText(
text: TextSpan(
text: "Password dimenticata?",
style: TextStyle(color: Colors.grey),
recognizer: TapGestureRecognizer()
..onTap = () {
print("Cliccato");
})),
SizedBox(
height: 20,
),
Button(password: password),
SizedBox(
height: 20,
),
Container(
decoration: BoxDecoration(
color: Colors.green[500], borderRadius: BorderRadius.circular(50)),
child: RichText(
text: TextSpan(
text: "Non sei registrato? Clicca qua",
style: TextStyle(color: Colors.black),
recognizer: TapGestureRecognizer()
..onTap = () {
Navigator.of(context).push(
PageRouteBuilder(
opaque: false,
pageBuilder: (BuildContext context, _, __) {
return Registration();
},
),
);
print("Cliccato");
},
),
),
),
],
),
);
}
}
class InputField extends StatelessWidget {
final String email;
final String password;
final void Function(String) onEmailChanged;
final void Function(String) onPasswordChanged;
const InputField({
Key? key,
required this.email,
required this.password,
required this.onEmailChanged,
required this.onPasswordChanged,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(
padding: EdgeInsets.all(10),
decoration:
BoxDecoration(border: Border(bottom: BorderSide(color: Color(4294638330)))),
child: TextField(
onChanged: onEmailChanged,
decoration: InputDecoration(
hintText: "Enter your email",
hintStyle: TextStyle(color: Colors.grey),
border: InputBorder.none,
),
),
),
Container(
padding: EdgeInsets.all(10),
decoration:
BoxDecoration(border: Border(bottom: BorderSide(color: Color(4294638330)))),
child: TextField(
onChanged: onPasswordChanged,
decoration: InputDecoration(
hintText: "Enter your password",
hintStyle: TextStyle(color: Colors.grey),
border: InputBorder.none,
),
),
),
],
);
}
}
class Button extends StatelessWidget {
final String password;
const Button({
Key? key,
required this.password,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
height: 50,
margin: EdgeInsets.symmetric(horizontal: 50),
decoration: BoxDecoration(
color: Colors.cyan[500],
borderRadius: BorderRadius.circular(10),
),
child: Center(
child: ElevatedButton(
onPressed: () {
print(password);
},
child: Text(
"Accedi",
style: TextStyle(color: Colors.white, fontSize: 15, fontWeight: FontWeight.bold),
),
),
),
);
}
}

Related

Flutter TextField selection highlighter controls appear too high

Screenshot of the issue and code in use below, the selection controls are above the textfield for some bizarre reason.
var textField = TextField(
selectionHeightStyle: BoxHeightStyle.max,
scrollPadding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom + 20 * 4),
textInputAction: TextInputAction.done,
keyboardType: TextInputType.numberWithOptions(signed: true, decimal: true),
decoration: InputDecoration(
border: InputBorder.none,
),
controller: textEditingController,
onTap: () {
Future.delayed(const Duration(milliseconds: 800), () {
textEditingController.selectAll();
});
},
onSubmitted: (newText) {
if (newText.length == 0) {
callback(0, true);
} else {
callback(int.parse(newText), true);
}
},
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headline4!.copyWith(
fontWeight: FontWeight.w700,
fontSize: 16.0,
color: WWColors.pinkBrandColor(),
),
);
return Padding(
padding: padding,
child: Container(alignment: Alignment.center, child: textField),
);
In answer to my own question, this in the TextField attributes did the job in my case:
decoration: InputDecoration(
isDense: true, // important line
contentPadding: EdgeInsets.fromLTRB(0, 5, 0, 5),
border: InputBorder.none,
),
Hi you can try create a custom widget for it to make the customisation as you required below is the simple example for the mentioned implementation.
class CounterWidget extends StatefulWidget {
final double width;
final double height;
final double spaceWidth;
final Color controlColor;
final Color valueColor;
final Function(int count) callback;
const CounterWidget({
Key? key,
required this.title,
required this.callback,
required this.controlColor,
required this.valueColor,
this.width = 50,
this.height = 30,
this.spaceWidth = 5,
}) : super(key: key);
final String title;
#override
State<CounterWidget> createState() => _CounterWidgetState();
}
class _CounterWidgetState extends State<CounterWidget> {
int count = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Row(
children: [
//Incrementor
InkWell(
onTap: () {
setState(() {
count++;
//Callback method to expose the count to the higher hier archy.
widget.callback(count);
});
},
child: Container(
decoration: BoxDecoration(
color: widget.controlColor,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(widget.height / 0.1),
bottomLeft: Radius.circular(widget.height / 0.1),
),
),
child: const Center(
child: Icon(
Icons.add,
color: Colors.white,
),
),
width: widget.width,
height: widget.height,
),
),
SizedBox(width: widget.spaceWidth),
Container(
color: widget.valueColor,
width: widget.width,
height: widget.height,
child: Center(
child: Text(
count.toString(),
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
),
),
SizedBox(width: widget.spaceWidth),
InkWell(
onTap: () {
if (count > 0) {
setState(() {
count--;
widget.callback(count);
});
}
},
child: Container(
width: widget.width,
height: widget.height,
decoration: BoxDecoration(
color: widget.controlColor,
borderRadius: BorderRadius.only(
topRight: Radius.circular(widget.height / 0.1),
bottomRight: Radius.circular(widget.height / 0.1),
),
),
child: const Center(
child: Icon(
Icons.remove,
color: Colors.white,
),
),
),
),
],
),
);
}
}

setState not updating the value in the screen using Flutter desktop

So I'm trying to update the value of the drop down list using the setState, but when I select a value from the list, the value on the screen won't be able to change
import 'package:demo_app_admin/Custom/custom_Font.dart';
import 'package:flutter/material.dart';
import '/Custom/Custom_Raised_Bottun.dart';
import '/Custom/Header.dart';
import '/Custom/inputField.dart';
class LoginView extends StatefulWidget {
#override
_LoginViewState createState() => _LoginViewState();
}
class _LoginViewState extends State<LoginView> {
#override
Widget build(BuildContext context) {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final isKeyboard = MediaQuery.of(context).viewInsets.bottom != 0;
String _dropdownvalue = "Global admin";
List<String> _items = <String> ["Global admin", "Institution admin"];
return Scaffold(
body: Container(
width: double.infinity,
decoration: BoxDecoration(
gradient: LinearGradient(begin: Alignment.topCenter, colors: [
Colors.teal[700]!,
Colors.teal[200]!,
Colors.teal[400]!
]),
),
child: Column(
children: <Widget>[
const SizedBox(
height: 80,
),
if (!isKeyboard)
Header(
padding: const EdgeInsets.all(20),
crossAxisAlignment: CrossAxisAlignment.start,
head: "Welcome",
headTextStyle:
const TextStyle(color: Colors.white, fontSize: 40),
sizedBoxHeight: 10,
subtitle: "Sign In to Your Admin Account",
subtitleTextStyle:
const TextStyle(color: Colors.white, fontSize: 18),
),
Expanded(
child: Container(
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(60),
topRight: Radius.circular(60),
)),
child: Padding(
padding: const EdgeInsets.all(30),
child: SingleChildScrollView(
reverse: true,
padding: EdgeInsets.all(32),
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
const SizedBox(
height: 40,
),
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10)),
child: Column(
children: <Widget>[
InputField(
labelText: 'Email',
padding: EdgeInsets.all(10),
borderSide: BorderSide(color: Colors.grey),
hintText: "Enter your email",
color: Colors.grey,
inputBorder: InputBorder.none,
obscureText: false,
enableSuggestion: true,
autoCorrect: true,
onSaved: (value) {},
// (value){controller.email = value!;},
validator: (value) {
if (value == null) {
print("ERROR");
}
},
),
InputField(
labelText: 'Password',
padding: EdgeInsets.all(10),
borderSide: BorderSide(color: Colors.grey),
hintText: "Enter your password",
color: Colors.grey,
inputBorder: InputBorder.none,
obscureText: true,
enableSuggestion: false,
autoCorrect: false,
onSaved: (value) {},
// (value){ controller.password = value!;},
validator: (value) {
if (value == null) {
print("ERROR");
}
},
),
],
),
),
const SizedBox(
height: 40,
),
here is the issue
DropdownButton<String>(
value: _dropdownvalue,
icon: Icon(Icons.keyboard_arrow_down),
items: _items.map((String _items) {
return DropdownMenuItem<String>(
value: _items,
child: CustomFont(text: _items),
);
}).toList(),
onChanged: (value) {
setState(() => _dropdownvalue = value!);
}),
const SizedBox(
height: 40,
),
CustomRaisedButton(
width: 200,
height: 50.0,
margin: const EdgeInsets.symmetric(horizontal: 50),
color: Colors.teal.shade500,
borderRadius: BorderRadius.circular(10),
text: "LOGIN",
textColor: Colors.white,
fontSize: 17,
fontWeight: FontWeight.bold,
function: () {}
// {
// _formKey.currentState?.save();
// if(_formKey.currentState?.validate() !=null){
// controller.signInWithEmailAndPassword();
// }
// },
),
SizedBox(
height: 10,
),
],
),
),
),
),
))
],
),
),
);
}
}
The issue is here, you are declaring variables inside build. Therefore, variables get reset to default value on every build. Means setState.
Declare variables outside the build method.
class _LoginViewState extends State<LoginView> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
String _dropdownvalue = "Global admin";
List<String> _items = <String>["Global admin", "Institution admin"];
#override
Widget build(BuildContext context) {
final isKeyboard = MediaQuery.of(context).viewInsets.bottom != 0;
return Scaffold(
More about StatefulWidget.

my provider is not found, when I use selector

I run the below code using consumer and provider and it worked smoothly but when I add selector it geive me an error,
the error:
Error: Could not find the correct Provider above this Selector<SignInUpProvider, int> Widget
This happens because you used a BuildContext that does not include the provider
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'providers/sign_in_up_provider.dart';
import 'utilities/myColors.dart' ;
class SigInUpPage extends StatefulWidget {
const SigInUpPage({Key? key}) : super(key: key);
#override
_SigInUpPageState createState() => _SigInUpPageState();
}
class _SigInUpPageState extends State<SigInUpPage> {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(create: (context)=> SignInUpProvider(),
child: const SignInUpScreen(),);
}
}
class SignInUpScreen extends StatefulWidget {
const SignInUpScreen({Key? key}) : super(key: key);
#override
_SignInUpScreenState createState() => _SignInUpScreenState();
}
class _SignInUpScreenState extends State<SignInUpScreen> {
// determine the sign in or sign up screen!!
// 0 = sign up , 1 = sign in
// sign up contents
// final GlobalKey<FormState> _keySignUp = GlobalKey<FormState>();
final TextEditingController _nameSignUp = TextEditingController();
final TextEditingController _passSignup = TextEditingController();
final TextEditingController _emailSignUp = TextEditingController();
// sign in contents
final GlobalKey<FormState> _keySignIn = GlobalKey<FormState>();
final TextEditingController _emailSignIn = TextEditingController();
final TextEditingController _passSifnIn = TextEditingController();
#override
void dispose() {
_nameSignUp.dispose();
_passSifnIn.dispose();
_passSignup.dispose();
_emailSignIn.dispose();
_emailSignUp.dispose();
// TODO: implement dispose
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
color: Colors.white,
child: Stack(
children: [
// dummy design
firstScreen(context),
// dummy design
secondScreen(context),
// sign in screen
thirdScreen(context),
],
),
),
);
}
// first background in stack
Widget firstScreen(BuildContext context){
return
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
color:MyColors.blueColor(),
);
}
// second background in stack
Widget secondScreen(BuildContext context){
return Align(
alignment: Alignment.bottomRight,
child: Container(
decoration: BoxDecoration(
color: MyColors.purple(),
borderRadius: const BorderRadius.only(bottomLeft:Radius.circular(1000),
topLeft: Radius.circular(1000)
)
),
width: MediaQuery.of(context).size.width * 0.5,
height: MediaQuery.of(context).size.height,
),
);
}
// sign in up screen // the white box
Widget thirdScreen(BuildContext context){
return Align(alignment: Alignment.bottomCenter,
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Container(
margin: EdgeInsets.only(bottom: MediaQuery.of(context).size.height*0.1),
width: MediaQuery.of(context).size.width*0.7,
height: MediaQuery.of(context).size.height*0.7,
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(50))),
child: Selector<SignInUpProvider, int>(
selector: (context, userState) => userState.getUserState,
builder: (context, state, widget){
return Form(
key: _keySignIn,
child: (state == 0 )?
Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children:
[
logo(context),
nameBox(context),
emailBox(context),
passText(context),
signButton(context),
// this to change between sign in and sign up
changeState(context),
],
):
Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children:
[
logo(context),
emailBox(context),
passText(context),
signButton(context),
// this to change between sign in and sign up
changeState(context),
],
),
);
}
),
),
),
);
}
// the logo inside the white box
Widget logo(context) {
return Container(
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(50))
),
width: MediaQuery.of(context).size.width*0.7,
height: MediaQuery.of(context).size.height*0.1,
child: const Align(
alignment: Alignment.center,
child: Text("mekyajat",style: TextStyle(
fontStyle: FontStyle.italic,
fontSize: 16,
color: Color.fromRGBO(249, 229, 230, 1),
),)),
);
}
// name box
Widget nameBox(context){
return Container(
width: MediaQuery.of(context).size.width*0.55,
height: MediaQuery.of(context).size.height*0.1,
decoration: const BoxDecoration(
color: Colors.white70,
),
child: TextFormField(
controller:_nameSignUp ,
decoration: const InputDecoration(
icon: Icon(Icons.person),
hintText: "name",
hintStyle: TextStyle(
color: Colors.black12,
fontSize: 14
),
),
textAlign: TextAlign.center,
validator: (value){
if( value.toString().length < 8 ){
Fluttertoast.showToast(msg: "please insert your name \n more than 8 charecters",
gravity: ToastGravity.CENTER,
toastLength: Toast.LENGTH_SHORT,
backgroundColor: Colors.redAccent,
textColor: Colors.white,
fontSize: 16
);
} return null ;
},
),
);
}
Widget emailBox(BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width*0.55,
height: MediaQuery.of(context).size.height*0.1,
decoration: const BoxDecoration(
color: Colors.white70,
),
child: TextFormField(
controller:(context.read<SignInUpProvider>().getUserState
== 0) ? _emailSignUp : _emailSignIn ,
decoration: const InputDecoration(
icon: Icon(Icons.email_outlined),
hintText: "E-mail #",
hintStyle: TextStyle(
color: Colors.black12,
fontSize: 14
),
),
textAlign: TextAlign.center,
validator: (value){
if( value.toString().length < 10 ){
Fluttertoast.showToast(msg: "please insert your email \n ",
gravity: ToastGravity.CENTER,
toastLength: Toast.LENGTH_SHORT,
backgroundColor: Colors.redAccent,
textColor: Colors.white,
fontSize: 16
);
}
else if (!containSymbol(value.toString(), "#")){
return "please insert # symbol";
}
return null ;
},
),
);
}
Widget passText(BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width*0.55,
height: MediaQuery.of(context).size.height*0.1,
decoration: const BoxDecoration(
color: Colors.white70,
),
child: TextFormField(
controller:(context.read<SignInUpProvider>().getUserState ==0)? _passSignup :_passSifnIn ,
decoration: const InputDecoration(
icon: Icon(Icons.password_sharp),
hintText: "password",
hintStyle: TextStyle(
color: Colors.black12,
fontSize: 14
),
),
textAlign: TextAlign.center,
validator: (value){
if( value.toString().length < 8 ){
Fluttertoast.showToast(msg: "please insert your password \n more than 8 charecters",
gravity: ToastGravity.CENTER,
toastLength: Toast.LENGTH_SHORT,
backgroundColor: Colors.redAccent,
textColor: Colors.white,
fontSize: 16
);
} return null ;
},
),
);
}
Widget signButton(BuildContext context) {
return Selector<SignInUpProvider, int>(
selector: (context,userState)=> userState.getUserState,
builder: (context, currentState, widget){
return InkWell(
child: Container(
alignment: Alignment.center,
width: MediaQuery.of(context).size.width*0.40,
height: MediaQuery.of(context).size.height*0.06,
child: (currentState == 0 )?
const Text("SIGN UP", textAlign: TextAlign.center,style: TextStyle(color: Colors.white),):
const Text("SIGN IN",textAlign: TextAlign.center, style: TextStyle(color: Colors.white),),
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(25)),
gradient: LinearGradient(colors: [
MyColors.blueColor(),
MyColors.purple(),
]),
),
),
onTap: (){},
);
},
);
}
Widget changeState(BuildContext context) {
return Consumer<SignInUpProvider>(
builder: (context, userSt , widget){
return InkWell(
child: SizedBox(
width: MediaQuery.of(context).size.width*0.55,
height: MediaQuery.of(context).size.height*0.05,
child:(userSt.userState == 0)?
const Text("sign in",
textAlign: TextAlign.right,
style: TextStyle(color:Color.fromRGBO(205, 221, 232, 1),fontSize: 12,
),) :
const Text("sign up",
textAlign: TextAlign.right,
style: TextStyle(
color:Color.fromRGBO(205, 221, 232, 1),fontSize: 12,
),)
),
onTap: (){
userSt.changeUserState(userSt.userState);
// SignInUpProvider().changeUserState(userState);
// signProvider.changeUserState(signProvider.userState);
},
);
},
);
}
}
// provide this function with one char and one string
// this run to see if the string contains char or not
bool containSymbol(String fullString , String char){
bool _result = false ;
List<String> _chars = [];
int _stringLingth = fullString.length;
int _keyLoop = 0 ;
while (_keyLoop < _stringLingth){
_chars.add(fullString[_keyLoop]);
_keyLoop++;
}
for(int x = 0 ; x < _chars.length; x++){
if(_chars[x] == char){
_result = true;
break;
}
}
return _result;
}
1 - move up your ChangeNotifierProvider step above in the widget tree for example in the routes you can wrap the SigInUpPage like this :
ChangeNotifierProvider<SignInUpProvider>(
create: (_) => SignInUpProvider(),
child: SigInUpPage(),
),
2 - don't pass the context as a parameter to the other screens,use a builder in each screen like this for the second screen:
class secondScreen extends StatelessWidget {
const secondScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Align(
alignment: Alignment.bottomCenter,
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Container(
margin: EdgeInsets.only(bottom: MediaQuery.of(context).size.height*0.1),
width: MediaQuery.of(context).size.width*0.7,
height: MediaQuery.of(context).size.height*0.7,
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(50))),
child: Selector<SignInUpProvider, int>(
selector: (context, userState) => userState.getUserState,
builder: (context, state, widget){
return Form(
key: _keySignIn,
child: (state == 0 )?
Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children:
[
logo(context),
nameBox(context),
emailBox(context),
passText(context),
signButton(context),
// this to change between sign in and sign up
changeState(context),
],
):
Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children:
[
logo(context),
emailBox(context),
passText(context),
signButton(context),
// this to change between sign in and sign up
changeState(context),
],
),
);
}
),
),
),
);
}
}
this should work

Latest document not listed in firestore

I am currently doing a chat app using flutter. I have 2 users and when one users start to chat with other user ,a document will be added in the "Chats" collection. If "user 1" starts a chat, a document of unique ID will be added in the collection. But the problem is, this document is not listed when I use .get() method...Please check what is the problem...
Here is my code:
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:nebula_chat_app/backend/pics.dart';
import 'package:nebula_chat_app/main.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:nebula_chat_app/backend/FireBase.dart';
class InChat extends StatefulWidget {
final String secondUserId;
final String SeconduserName;
const InChat({Key key, this.secondUserId,this.SeconduserName}) : super(key: key);
#override
_InChatState createState() => _InChatState(secondUserId,SeconduserName);
}
class _InChatState extends State {
var messages;
String docu;
List ko;
Future> offlinemessage;
final String SecondUserId;
final String SeconduserName;
String typeMessage;
ScrollController _controller2;
TextEditingController controller2;
_InChatState(this.SecondUserId,this.SeconduserName);
#override
void initState() {
controller2 = TextEditingController();
addUser();
_controller2 = ScrollController();
database.collection("Chats").get().then((value) {
var usersinChat = value.docs.map((e) => e.id).toList();
print(usersinChat);
docu = usersinChat.singleWhere((element) => ((element == auth.currentUser.uid.toString() + SecondUserId) || (element == SecondUserId + auth.currentUser.uid.toString())),orElse: ()
=> auth.currentUser.uid.toString() + SecondUserId
);
}).then((value) {
messages = database.collection("Chats").doc(docu).collection("Messages").snapshots();
print("_________________$docu");
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(icon: Icon(Icons.arrow_back_ios_sharp,color: Colors.white,), onPressed: () => Navigator.pop(context)),
title: Text(SeconduserName,style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: GFS(25, context),
color: Colors.white
),),
actions: [
IconButton(icon: Icon(Icons.search,color: Colors.white,), onPressed: null)
],
),
body: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
color: Theme.of(context).primaryColorLight,
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
height: MediaQuery.of(context).size.height*0.75,
width: MediaQuery.of(context).size.width,
child: StreamBuilder(
stream: messages,
builder: (context, snapshot){
if(!snapshot.hasData) return Center(child: CircularProgressIndicator(),);
else
return ListView.builder(
controller: _controller2,
itemCount: snapshot.data.docs.length,
itemBuilder: (context,int index) {
if (!snapshot.hasData) return SizedBox();
else {
if (snapshot.data.docs[index]["from"] == SecondUserId){
print("Second ======> $SecondUserId");
if(_keyboardIsVisible()){
SchedulerBinding.instance.addPostFrameCallback((timeStamp) {_controller2.animateTo(_controller2.position.maxScrollExtent,duration: Duration(milliseconds: 500), curve: Curves.fastOutSlowIn ); });
}
return ReceiveContainer(
text: snapshot.data.docs[index]["message"].toString());
}
else{
return SendContainer(
text: snapshot.data.docs[index]["message"].toString(), status: "seen",);
}
}
}
);
},
)
),
Container(
height: MediaQuery.of(context).size.height*0.1,
width: MediaQuery.of(context).size.width,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
height: MediaQuery.of(context).size.height*0.07,
alignment: Alignment.center,
width: MediaQuery.of(context).size.width*0.75,
decoration: BoxDecoration(
color: Theme.of(context).cardColor,
boxShadow: [BoxShadow(color: Colors.black26,spreadRadius: 1.0,blurRadius: 3.0)],
borderRadius: BorderRadius.circular(40.0)
),
child: Padding(
padding: EdgeInsets.only(left:MediaQuery.of(context).size.width*0.07),
child: TextField(
controller: controller2,
style: TextStyle(
color: Colors.black,
),
decoration: InputDecoration(
focusColor: Colors.black,
hintText: 'Type here',
border: InputBorder.none,
focusedBorder: InputBorder.none,
focusedErrorBorder: InputBorder.none,
disabledBorder: InputBorder.none,
enabledBorder: InputBorder.none,
errorBorder: InputBorder.none,
hintStyle: TextStyle(
color: Colors.black26,
fontSize: GFS(20, context)
)
),
onSubmitted: (text) {
setState(() {
controller2.text = text;
});
},
),
),
),
Container(
height: MediaQuery.of(context).size.height*0.07,
width: MediaQuery.of(context).size.width*0.2,
alignment: Alignment.center,
decoration: BoxDecoration(
color: Theme.of(context).cardColor,
shape: BoxShape.circle,
boxShadow: [BoxShadow(color: Colors.black26,spreadRadius: 1.0,blurRadius: 3.0)],
),
child: InkWell(
onTap: () {
database.collection("Chats").doc(docu).collection("Messages").doc(Timestamp.now().millisecondsSinceEpoch.toString()).set(
{
"from":auth.currentUser.uid.toString(),
"message": controller2.text,
"timestamp" : Timestamp.now().millisecondsSinceEpoch
});
setState(() {
controller2.text = "";
});
SchedulerBinding.instance.addPostFrameCallback((timeStamp) {_controller2.animateTo(_controller2.position.maxScrollExtent,duration: Duration(milliseconds: 500), curve: Curves.fastOutSlowIn ); });
},
child: SizedBox(
width:MediaQuery.of(context).size.width*0.1,
height:MediaQuery.of(context).size.height*0.035,
child: SvgPicture.asset(sendIcon,fit: BoxFit.contain,)),
),
)
],
),
) ///Typing Container
],
),
),
),
);
}
bool _keyboardIsVisible() {
return !(MediaQuery.of(context).viewInsets.bottom == 0.0);
}
void checkCommon() {
}
}
class ReceiveContainer extends StatelessWidget {
final String text;
const ReceiveContainer({Key key, this.text}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
alignment: Alignment.centerLeft,
constraints: BoxConstraints(
minHeight: MediaQuery.of(context).size.height*0.1,
),
child: Padding(
padding: EdgeInsets.symmetric(vertical: MediaQuery.of(context).size.height*0.02,horizontal:MediaQuery.of(context).size.width*0.05 ),
child: Container(
constraints: BoxConstraints(
minWidth: MediaQuery.of(context).size.width*0.1,
maxWidth: MediaQuery.of(context).size.width*0.5,
minHeight: MediaQuery.of(context).size.height*0.06,
),
decoration: BoxDecoration(
color:Theme.of(context).cardColor,
borderRadius: BorderRadius.circular(20.0),
boxShadow: [BoxShadow(color: Colors.black26,spreadRadius: 1.0,blurRadius: 2.0)]
),
child: Padding(
padding: EdgeInsets.all(MediaQuery.of(context).size.width*0.4*0.1),
child: Text(text,style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: GFS(19, context),
color:Theme.of(context).textTheme.headline1.color
),),
),
),
),
);
}
}
class SendContainer extends StatelessWidget {
final String text;
final String status;
const SendContainer({Key key, this.text,this.status}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
constraints: BoxConstraints(
minHeight: MediaQuery.of(context).size.height*0.1,
),
child: Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Container(
height: MediaQuery.of(context).size.height*0.03,
width: MediaQuery.of(context).size.width*0.1,
child: checkStatus(status)
),
Padding(
padding: EdgeInsets.only(top: MediaQuery.of(context).size.height*0.02,bottom: MediaQuery.of(context).size.height*0.02,left:MediaQuery.of(context).size.width*0.05 ,right:MediaQuery.of(context).size.width*0.02 ),
child: Container(
constraints: BoxConstraints(
minWidth: MediaQuery.of(context).size.width*0.1,
maxWidth: MediaQuery.of(context).size.width*0.5,
minHeight: MediaQuery.of(context).size.height*0.06,
),
decoration: BoxDecoration(
color:Theme.of(context).primaryColorDark,
borderRadius: BorderRadius.circular(20.0),
boxShadow: [BoxShadow(color: Colors.black26,spreadRadius: 1.0,blurRadius: 2.0)]
),
child: Padding(
padding: EdgeInsets.all(MediaQuery.of(context).size.width*0.4*0.1),
child: Text(text,style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: GFS(19, context),
color: Colors.white
),),
),
),
),
],
),
),
);
}
checkStatus(statusss) {
{
if(statusss == 'delivered') return SvgPicture.asset(doubleCheckIcon,fit: BoxFit.contain,color: Colors.black,);
else if (statusss == 'Not delivered') return SvgPicture.asset(checkIcon,fit: BoxFit.contain,color: Colors.black,);
else if (statusss == 'seen') return SvgPicture.asset(doubleCheckIcon,fit: BoxFit.contain,color: Colors.green,);
}
}
}

Flutter customize dropdown + TextFormField

How do I achieve the following look for a Row which consists of a dropdown and a TextFormField?
I am able to customize the TextFormField using the following code:
final phoneNumberBox = DecoratedBox(
decoration: const BoxDecoration(color: Color(0x2B8E8E93),
borderRadius:BorderRadius.only(
topRight: const Radius.circular(32),
bottomRight: const Radius.circular(32))),
child: phoneNumber,
);
final phoneNumber =
TextFormField(
keyboardType: TextInputType.phone,
autofocus: false,
controller: _phoneNumberController,
// validator: Validator.validateField,
decoration: InputDecoration(
contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
border: OutlineInputBorder(borderRadius: new BorderRadius.only(
topRight: const Radius.circular(32),
bottomRight: const Radius.circular(32))),
),
);
However I cant figure out how to change the DropDown
far from perfect, but as an option
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(body: Content()),
);
}
}
class Content extends StatefulWidget {
#override
_ContentState createState() => _ContentState();
}
class _ContentState extends State<Content> {
final List<String> _items = ['+1', '+42', '+666', '+17', '+228'];
TextEditingController _phoneNumberController = TextEditingController();
String _value;
#override
void initState() {
super.initState();
_value = _items.first;
}
#override
Widget build(BuildContext context) {
return Center(
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 32),
height: 56,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(28),
color: Colors.grey[200],
),
child: Row(
children: <Widget>[
DropdownButtonHideUnderline(
child: Container(
padding: const EdgeInsets.fromLTRB(32, 8, 16, 8),
child: DropdownButton<String>(
value: _value,
items: _items.map((value) {
return DropdownMenuItem<String>(child: Text(value), value: value);
}).toList(),
onChanged: _onDropDownChanged,
),
),
),
Container(width: 1, color: Colors.grey[300]),
Expanded(
child: TextFormField(
keyboardType: TextInputType.phone,
autofocus: false,
controller: _phoneNumberController,
decoration: InputDecoration(
contentPadding: const EdgeInsets.fromLTRB(16, 16, 8, 16),
border: InputBorder.none,
suffixIcon: Padding(
child: Icon(Icons.cancel, color: Colors.grey[400]),
padding: const EdgeInsets.only(right: 16),
),
),
),
),
],
),
),
);
}
void _onDropDownChanged(String value) {
setState(() {
_value = value;
});
}
}