W/GooglePlayServicesUtil(16928): Google Play Store is missing. flutter - flutter

i am trying to get user location but get the google play store service is missing while i dont use any google apps or service in my app. help
i get this error everytime, i try to get my current location
i marked it by ----->
it should give me the latitude and longitude
W/GooglePlayServicesUtil(16928): Google Play Store is missing. flutter
here is my main code i am trying to click on prefixicon to get my location
import 'package:flutter/material.dart';
import 'package:project/screens/sign_page.dart';
import 'package:project/screens/home_screen.dart';
import 'package:geolocator/geolocator.dart';
//textediting controller needed to be added
// Define a custom Form widget.
class MyCustomForm extends StatefulWidget {
const MyCustomForm({Key? key}) : super(key: key);
#override
MyCustomFormState createState() {
return MyCustomFormState();
}
}
// Define a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
final _formKey = new GlobalKey<FormState>();
getcurrentlocation() async {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
var latitude = position.latitude;
var longitude = position.longitude;
print(latitude);
print(longitude);
}
TextEditingController name = TextEditingController();
TextEditingController phone = TextEditingController();
TextEditingController address = TextEditingController();
#override
Widget build(BuildContext context) {
return Material(
child: Form(
key: _formKey,
child: SafeArea(
child: Column(
children: [
Container(
height: MediaQuery.of(context).size.height * 0.15,
width: double.infinity,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/background.png"),
fit: BoxFit.cover)),
padding: EdgeInsets.only(top: 47, left: 20),
child: Text(
"Personal info",
style: TextStyle(
fontSize: 45,
fontWeight: FontWeight.bold,
color: Colors.white),
),
),
SizedBox(
height: 20,
),
Container(
alignment: Alignment.topLeft,
padding: EdgeInsets.only(left: 29),
child: Text(
"Name",
style: TextStyle(fontSize: 18, color: Colors.black),
),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 25, vertical: 20),
child: TextFormField(
keyboardType: TextInputType.name,
controller: name,
onFieldSubmitted: (value) {},
validator: (value) {
if (value!.isEmpty) {
return 'Enter a valid Name!';
}
return null;
},
decoration: InputDecoration(
filled: true,
isDense: true, // Added this
contentPadding: EdgeInsets.symmetric(vertical: 22),
fillColor: Color.fromRGBO(238, 247, 246, 1),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.white, width: 2),
),
hintText: '',
),
),
),
Container(
alignment: Alignment.topLeft,
padding: EdgeInsets.only(left: 29),
child: Text(
"Address",
style: TextStyle(fontSize: 18, color: Colors.black),
),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 25, vertical: 20),
child: TextFormField(
keyboardType: TextInputType.text,
controller: address,
onFieldSubmitted: (value) {},
validator: (value) {
if (value!.isEmpty) {
return 'Enter a valid address!';
}
return null;
},
decoration: InputDecoration(
prefixIcon: IconButton(
onPressed: () async {
getcurrentlocation(); **----->here!**
},
icon: Icon(Icons.location_on),
),
isDense: true, // Added this
contentPadding: EdgeInsets.symmetric(vertical: 22),
filled: true,
fillColor: Color.fromRGBO(238, 247, 246, 1),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.white, width: 2),
),
hintText: '',
),
),
),
Container(
alignment: Alignment.topLeft,
padding: EdgeInsets.only(left: 29),
child: Text(
"Phone Number",
style: TextStyle(fontSize: 18, color: Colors.black),
),
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 25, vertical: 15),
child: TextFormField(
keyboardType: TextInputType.number,
controller: phone,
onFieldSubmitted: (value) {},
validator: (value) {
if (value!.isEmpty) {
return 'Enter a valid phone number!';
}
return null;
},
decoration: InputDecoration(
isDense: true, // Added this
contentPadding: EdgeInsets.symmetric(vertical: 22),
filled: true,
fillColor: Color.fromRGBO(238, 247, 246, 1),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.white, width: 2),
),
hintText: '',
),
),
),
Expanded(child: Text("")),
FlatButton(
height: 50,
minWidth: 300,
onPressed: () {
if (_formKey.currentState!.validate()) {
Navigator.push(context,
MaterialPageRoute(builder: (_) => homeScreen()));
// If the form is valid, display a snackbar. In the real world,
// you'd often call a server or save the information in a database.
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("")),
);
}
},
color: const Color.fromRGBO(0, 168, 165, 1),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
child: const Text(
"Continue",
style: TextStyle(color: Colors.white, fontSize: 19),
),
),
SizedBox(
height: 20,
)
],
),
// Add TextFormFields and ElevatedButton here.
)));
}
}

I think you run application with emulator without Playstore.
Google core needs google play installed on your virtual device to get ads maps and core functionality that include google play SDK.
you just need to create an emulator with google play as shown in the image below one with the google play icon.
I hope this answer will help you..

Related

Background orange text removal from button in Dart

Need to change orange color behind button to white. Dont
know where it comes from the code. Brown text is fine but behind orange one needs it to be removed. Maybe some container is taking a style. Tried removing elevated
button.style from shadow color but still not going. Please help with this. Thanks.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:matab/services/authentication_service.dart';
import 'package:matab/ui/general_widgets/generate_error_snackbar.dart';
import 'package:matab/ui/pages/onBoarding/login_page.dart';
import 'package:simple_gradient_text/simple_gradient_text.dart';
import '../styles.dart';
class SignupTextFields extends StatefulWidget {
const SignupTextFields({Key? key}) : super(key: key);
#override
State<SignupTextFields> createState() => _SignupTextFieldsState();
}
class _SignupTextFieldsState extends State<SignupTextFields> {
TextEditingController nameController = TextEditingController();
TextEditingController phoneController = TextEditingController();
TextEditingController userCnicController = TextEditingController();
TextEditingController passwordController = TextEditingController();
TextEditingController emailController = TextEditingController();
TextEditingController confirmPasswordController = TextEditingController();
bool _passwordVisible = false;
#override
Widget build(BuildContext context) {
Authentication authentication = Authentication();
return Padding(
padding: const EdgeInsets.all(10),
child: ListView(
children: <Widget>[
Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(10),
child: Text(
'SignUP'.tr,
style: const TextStyle(
fontWeight: FontWeight.bold, fontSize: 30),
)),
Container(
padding: const EdgeInsets.all(10),
child: TextField(
controller: nameController,
decoration: InputDecoration(
border: const OutlineInputBorder(),
labelText: 'Name'.tr,
),
),
),
Container(
padding: const EdgeInsets.all(10),
child: TextField(
controller: phoneController,
inputFormatters: [
FilteringTextInputFormatter.allow(
RegExp('[0-9]'),
),
],
maxLength: 11,
keyboardType: TextInputType.number,
decoration: InputDecoration(
border: const OutlineInputBorder(),
labelText: 'Phone'.tr,
),
),
),
Container(
padding: const EdgeInsets.all(10),
child: TextField(
controller: emailController,
decoration: InputDecoration(
border: const OutlineInputBorder(),
labelText: 'Email'.tr,
),
),
),
Container(
padding: const EdgeInsets.all(10),
child: TextField(
controller: userCnicController,
inputFormatters: [
FilteringTextInputFormatter.allow(
RegExp('[0-9]'),
),
],
maxLength: 13,
keyboardType: TextInputType.number,
decoration: InputDecoration(
border: const OutlineInputBorder(),
labelText: 'UserCNIC'.tr,
),
),
),
Container(
padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
child: TextFormField(
keyboardType: TextInputType.text,
controller: passwordController,
obscureText:
!_passwordVisible, //This will obscure text dynamically
decoration: InputDecoration(
border: const OutlineInputBorder(),
labelText: 'Password'.tr,
suffixIcon: IconButton(
icon: ImageIcon(
const AssetImage("assets/visibilty.png"),
color: greyColor,
),
onPressed: () {
// Update the state i.e. toogle the state of passwordVisible variable
setState(() {
_passwordVisible = !_passwordVisible;
});
},
),
),
),
),
Container(
padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
child: TextFormField(
keyboardType: TextInputType.text,
controller: confirmPasswordController,
obscureText:
!_passwordVisible, //This will obscure text dynamically
decoration: InputDecoration(
border: const OutlineInputBorder(),
labelText: 'Confirm Password'.tr,
suffixIcon: IconButton(
icon: ImageIcon(
const AssetImage("assets/visibilty.png"),
color: greyColor,
),
onPressed: () {
// Update the state i.e. toogle the state of passwordVisible variable
setState(() {
_passwordVisible = !_passwordVisible;
});
},
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(20.0, 10, 20, 0),
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(colors: gradientColors),
borderRadius:
const BorderRadius.all(Radius.circular(7.0))),
height: 50,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.transparent,
shadowColor: Colors.transparent,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(82.0)),
),
),
child: Text('Register'.tr),
onPressed: () {
if (nameController.text.isNotEmpty) {
if (phoneController.text.isNotEmpty) {
if (userCnicController.text.trim().length != 13) {
generateError(
"Error".tr, "CNICMustBe13DigitsLong".tr);
} else {
if (emailController.text.isNotEmpty) {
authentication.signUp(
nameController.text,
phoneController.text,
int.tryParse(
userCnicController.text.trim()) ??
0, //cnic never replaced with 0 we have already checked for null
emailController.text,
passwordController.text,
confirmPasswordController.text);
} else {
generateError(
"EmailEmpty".tr, "YouMustProvideEmail".tr);
}
}
} else {
generateError(
"PhoneCannotEmpty".tr, "EnterPhoneTryAgain".tr);
}
} else {
generateError(
"NameCannotBeEmpty".tr, "EnterNameAndTryAgain".tr);
}
},
)),
),
Row(
children: <Widget>[
Text(
'Already have an Account?'.tr,
style: TextStyle(fontSize: 20.0, color: greyColor),
),
TextButton(
child: GradientText(
'Login'.tr,
style: const TextStyle(
fontSize: 20.0,
),
gradientType: GradientType.radial,
radius: 2.5,
colors: gradientColors,
),
onPressed: () {
Get.off(const LoginPage());
},
),
],
mainAxisAlignment: MainAxisAlignment.center,
),
],
));
}
}
For the top container, it is having Radius.circular(7.0) But for Elevated button it is Radius.circular(82.0).
You need to provide same radius on both.
Padding(
padding: const EdgeInsets.fromLTRB(20.0, 10, 20, 0),
child: Container(
decoration: BoxDecoration(
gradient:
LinearGradient(colors: [Colors.red, Colors.black54]),
borderRadius: BorderRadius.all(Radius.circular(82.0)),
),
height: 50,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.transparent,
shadowColor: Colors.transparent,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(82.0)),
),
),
child: Text('Register'),
onPressed: () {},
)),
),
don't use shadowColor: Colors.transparent, instead use
shadowColor: Colors.white,
because the default color of your app is orange so if you do Colors.transparent it'll call default color in some cases. Also you have to remove the parent Contanier from the ElevatedButton because it is taking the background surface and changing it to orange color

Flutter - Cursor keep blinking after change Form input

I have a regular form on my APP, and when i load de screen no input is focused and no input has the cursor blinking...
Although, when run throw the inputs and fill them, or not, the cursor keeps blinking as i show on the image above:
The picture only show 3, but all of them are blinking. My point is that i need to keep only the focused input with the cursor blinking.
Heres the Form Code:
class RegisterView extends StatefulWidget {
const RegisterView({Key? key}) : super(key: key);
#override
State<RegisterView> createState() => _RegisterViewState();
}
class _RegisterViewState extends State<RegisterView> {
final _formKey = GlobalKey<FormState>();
final FocusScopeNode _node = FocusScopeNode();
String name = '';
String email = '';
String nif = '';
String password = '';
String _errorMessage = '';
TextEditingController nameCtrl = TextEditingController();
TextEditingController emailCtrl = TextEditingController();
TextEditingController nifCtrl = TextEditingController();
TextEditingController passwordCtrl = TextEditingController();
#override
void dispose() {
// TODO: implement dispose
_node.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
UserProvider userProvider =
Provider.of<UserProvider>(context, listen: false);
return Scaffold(
appBar: AppBar(
leading: const CustomBackButton(),
title: const Text('Register',
style: TextStyle(
color: kPrimaryColor,
fontSize: 16.0,
fontWeight: FontWeight.bold)),
centerTitle: true,
),
body: GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(FocusNode());
},
child: SingleChildScrollView(
child: Form(
key: _formKey,
child: FocusScope(
node: _node,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: Column(
children: [
const Padding(
padding: EdgeInsets.symmetric(vertical: 15.0),
child: Text(
'Please set your personal data:',
style:
TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
),
Padding(
padding: const EdgeInsets.only(bottom: 10.0),
child: Row(
children: [
Text(_errorMessage,
style: const TextStyle(color: Colors.red)),
],
),
),
TextFormField(
controller: nameCtrl,
keyboardType: TextInputType.number,
decoration: InputDecoration(
filled: true,
fillColor: Colors.grey[250],
contentPadding: const EdgeInsets.all(10.0),
hintText: 'Name',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(
color: kPrimaryColor,
width: 2,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(
color: kPrimaryColor,
width: 2,
),
),
),
onChanged: (String data) {
setState(() {
name = data;
});
},
onEditingComplete: _node.nextFocus,
),
const SizedBox(height: 15),
TextFormField(
controller: emailCtrl,
keyboardType: TextInputType.number,
decoration: InputDecoration(
filled: true,
fillColor: Colors.grey[250],
contentPadding: const EdgeInsets.all(10.0),
hintText: 'Email',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(
color: kPrimaryColor,
width: 2,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(
color: kPrimaryColor,
width: 2,
),
),
),
onChanged: (String data) {
setState(() {
email = data;
});
},
validator: (String? value) {
if (value!.isEmpty) {
return 'Required';
} else if (!emailRegex.hasMatch(value)) {
return 'Please set a valid email';
}
},
onEditingComplete: _node.nextFocus,
),
const SizedBox(height: 15),
TextFormField(
controller: nifCtrl,
keyboardType: TextInputType.number,
decoration: InputDecoration(
filled: true,
fillColor: Colors.grey[250],
contentPadding: const EdgeInsets.all(10.0),
hintText: 'NIF',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(
color: kPrimaryColor,
width: 2,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(
color: kPrimaryColor,
width: 2,
),
),
),
onChanged: (String data) {
setState(() {
nif = data;
});
},
onEditingComplete: _node.nextFocus,
),
const SizedBox(height: 15),
TextFormField(
controller: passwordCtrl,
keyboardType: TextInputType.number,
decoration: InputDecoration(
filled: true,
fillColor: Colors.grey[250],
contentPadding: const EdgeInsets.all(10.0),
hintText: 'Password',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(
color: kPrimaryColor,
width: 2,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: const BorderSide(
color: kPrimaryColor,
width: 2,
),
),
),
onChanged: (String data) {
setState(() {
password = data;
});
},
validator: (String? value) {
if (value!.isEmpty) {
return 'Campo obrigatório';
} else if (value.length < 6) {
return 'Password deve conter pelo menos 6 caracteres';
}
},
onEditingComplete: _node.nextFocus,
),
const SizedBox(height: 15),
RoundedButton(
bgColor: kPrimaryColor,
padding: const EdgeInsets.symmetric(
vertical: 10.0, horizontal: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
userProvider.isLoading
? const SpinKitFadingCircle(
color: Colors.white,
size: 25.0,
)
: const Text(
'Save',
style: TextStyle(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.w700,
),
),
],
),
onPressed: () {
if (_formKey.currentState!.validate()) {
print('Ok to register');
}
},
)
],
),
),
),
),
),
),
);
}
}

mutation graphql using flutter forms not working

trying to use mutation on forms but got this error while addins runmutation and queryresult result in builder ().all i get is dead code in vscode
The argument type 'Widget Function(MultiSourceResult Function(Map<String, dynamic>, {Object? optimisticResult}), QueryResult<Object?>)' can't be assigned to the parameter type 'Widget Function(MultiSourceResult<Object?> Function(Map<String, dynamic>, {Object? optimisticResult}), QueryResult
import 'dart:io';
import 'package:country_code_picker/country_code_picker.dart';
import 'package:project/API/Api.dart';
import 'package:project/screens/form_info.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import '../API/querys.dart';
import '../API/mutations.dart';
class Sign_Number extends StatefulWidget {
Sign_Number({Key? key}) : super(key: key);
#override
State<Sign_Number> createState() => _Sign_NumberState();
}
class _Sign_NumberState extends State<Sign_Number> {
var PhoneNumber = "";
void _onCountryChange(CountryCode countryCode) {
this.PhoneNumber = countryCode.toString();
print("new country selected: " + countryCode.toString());
}
TextEditingController phoneNumberhere = TextEditingController();
TextEditingController password = TextEditingController();
void initState() {
super.initState();
_onCountryChange(CountryCode());
this.PhoneNumber = "+20";
}
var _formKey1 = new GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return GraphQLProvider(
client: client,
child: MaterialApp(
home: Container(
height: double.infinity,
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
stops: [0.5, 0.5],
colors: <Color>[Color.fromRGBO(0, 37, 43, 1), Colors.white],
tileMode:
TileMode.clamp, // clamp the gradient over the canvas
),
),
child: Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: Colors.transparent,
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Container(Image(
// height: MediaQuery.of(context).size.height *0.5,
// width: 250,
// image: AssetImage('assets/images/2.jpg')),
// ),
Container(
height: 300,
width: 300,
child: const Image(
image: AssetImage(
'assets/images/2.jpg',
),
fit: BoxFit.cover,
),
),
const SizedBox(
//Use of SizedBox
height: 30,
),
Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
child: Row(
children: [
const SizedBox(
width: 47,
),
const Text("Enter mobile number for login",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold)),
],
)),
const SizedBox(
//Use of SizedBox
height: 20,
),
Mutation(
options: new MutationOptions(
document: gql(insertUser()),
/// Tell the GraphQL client to fetch the data from
/// the network only and don't cache it
fetchPolicy: FetchPolicy.noCache,
/// Whenever the [Form] closes, this tells the previous [route]
/// whether it needs to rebuild itself or not
onCompleted: (data) =>
Navigator.pop(context, data != null),
),
builder: (QueryResult, RunMutation) {
return Form(
key: _formKey1,
child: Container(
height: 100,
padding: const EdgeInsets.symmetric(
horizontal: 30),
child: Column(children: [
TextFormField(
controller: phoneNumberhere,
autocorrect: true,
keyboardType:
TextInputType.number,
onFieldSubmitted: (value) {},
validator: (value) {
if (value!.isEmpty) {
return 'Enter a valid Phone Number!';
}
return null;
},
decoration: InputDecoration(
prefixIcon: CountryCodePicker(
onChanged: _onCountryChange,
// Initial selection and favorite can be one of code ('IT') OR dial_code('+39')
initialSelection: '+20',
favorite: ['+20', 'EG'],
textStyle: const TextStyle(
color: Colors.black),
showFlag: true,
),
contentPadding:
const EdgeInsets.all(10),
hintText:
'Enter valid phone number...',
hintStyle: const TextStyle(
color: Colors.black),
filled: true,
fillColor: const Color.fromRGBO(
227, 227, 226, 0.2),
enabledBorder:
const OutlineInputBorder(
borderRadius:
BorderRadius.all(
Radius.circular(
12.0)),
borderSide: BorderSide(
color: Colors.white,
width: 2),
),
focusedBorder:
const OutlineInputBorder(
borderRadius:
BorderRadius.all(
Radius.circular(
10.0)),
borderSide: BorderSide(
color: Colors.white),
),
),
),
const SizedBox(
//Use of SizedBox
height: 10,
),
SizedBox(
height: 50,
child: TextFormField(
autofocus: false,
obscureText: true,
controller: password,
autocorrect: true,
keyboardType: TextInputType
.visiblePassword,
onFieldSubmitted: (value) {},
validator: (value) {
if (value!.isEmpty) {
return 'Enter a valid password!';
}
return null;
},
decoration: InputDecoration(
contentPadding:
const EdgeInsets.all(10),
hintText: 'Enter Password.',
hintStyle: const TextStyle(
color: Colors.black),
filled: true,
fillColor:
const Color.fromRGBO(
227, 227, 226, 0.2),
enabledBorder:
const OutlineInputBorder(
borderRadius:
BorderRadius.all(
Radius.circular(
12.0)),
borderSide: BorderSide(
color: Colors.white,
width: 2),
),
focusedBorder:
const OutlineInputBorder(
borderRadius:
BorderRadius.all(
Radius.circular(
10.0)),
borderSide: BorderSide(
color: Colors.white),
),
),
),
),
const SizedBox(
//Use of SizedBox
height: 5,
),
const Text(
"forgot your password?",
style: TextStyle(
color: Color.fromRGBO(
218, 218, 218, 1),
fontSize: 10),
textAlign: TextAlign.left,
),
])));
const SizedBox(
//Use of SizedBox
height: 50,
);
FlatButton(
height: 50,
minWidth: 300,
onPressed: () {
if (_formKey1.currentState!.validate()) {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) =>
MyCustomForm()));
// If the form is valid, display a snackbar. In the real world,
// you'd often call a server or save the information in a database.
ScaffoldMessenger.of(context)
.showSnackBar(
SnackBar(
content:
Text(phoneNumberhere.text)),
);
}
},
color: const Color.fromRGBO(0, 168, 165, 1),
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(10)),
child: const Text(
"Continue",
style: TextStyle(
color: Colors.white, fontSize: 19),
),
);
},
),
],
)
])))));
}
}```

How to visible/hide password in flutter?

I have created a login screen for my app but in password field I want a functionality like when I type password its been in * format and in right side a icon on when user click on it, password will be visible, I created a code for it but when I click on password field that icon getting invisible and when password field loose focus that icon appearing again, then how to always show that icon even password field is in focus?
I have provided a snapshot to easily understand the problem.
Here are my login screen code....
import 'package:flutter/material.dart';
import 'package:email_validator/email_validator.dart';
import 'package:secret_keeper/screens/home_screen/Home.dart';
import 'package:secret_keeper/screens/home_screen/passwords/PasswordsNavigation.dart';
import 'package:secret_keeper/screens/signup_page/SignupPage.dart';
class LoginPage extends StatefulWidget{
#override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
String _emailID, _password = "",_email = "abc#gmail.com", _pass = "Try.t.r.y#1";
bool _obscureText = true;
final _formKey = GlobalKey<FormState>();
void _toggle(){
setState(() {
_obscureText = !_obscureText;
});
}
void validateLogin(){
if(_formKey.currentState.validate()){
_formKey.currentState.save();
if(_emailID == _email && _password == _pass){
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => Home()));
}
}
}
Widget emailInput(){
return TextFormField(
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: "Email ID",
labelStyle: TextStyle(fontSize: 14,color: Colors.grey.shade400),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide(
color: Colors.grey.shade300,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide(
color: Colors.red,
)
),
),
validator: (email) {
if (email.isEmpty)
return 'Please Enter email ID';
else if (!EmailValidator.validate(email))
return 'Enter valid email address';
else
return null;
},
onSaved: (email)=> _emailID = email,
textInputAction: TextInputAction.next,
);
}
Widget passInput(){
return TextFormField(
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: "Password",
labelStyle: TextStyle(fontSize: 14,color: Colors.grey.shade400),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide(
color: Colors.grey.shade300,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide(
color: Colors.red,
)
),
suffixIcon: IconButton(
icon: Icon(
_obscureText ? Icons.visibility : Icons.visibility_off,
),
onPressed: _toggle,
),
),
validator: (password){
Pattern pattern =
r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!##\$&*~]).{8,}$';
RegExp regex = new RegExp(pattern);
if (password.isEmpty){
return 'Please Enter Password';
}else if (!regex.hasMatch(password))
return 'Enter valid password';
else
return null;
},
onSaved: (password)=> _password = password,
textInputAction: TextInputAction.done,
obscureText: _obscureText,
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomPadding: false,
backgroundColor: Colors.white,
body: SafeArea(
child: Container(
padding: EdgeInsets.only(left: 16,right: 16),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(height: 50,),
Text("Welcome,",style: TextStyle(fontSize: 26,fontWeight: FontWeight.bold),),
SizedBox(height: 6,),
Text("Sign in to continue!",style: TextStyle(fontSize: 20,color: Colors.grey.shade400),),
],
),
Column(
children: <Widget>[
emailInput(),
SizedBox(height: 16,),
passInput(),
SizedBox(height: 12,),
Align(
alignment: Alignment.topRight,
child: Text("Forgot Password ?",style: TextStyle(fontSize: 14,fontWeight: FontWeight.w600),),
),
SizedBox(height: 30,),
Container(
height: 50,
width: double.infinity,
child: FlatButton(
onPressed: validateLogin,
padding: EdgeInsets.all(0),
child: Ink(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [
Color(0xffff5f6d),
Color(0xffff5f6d),
Color(0xffffc371),
],
),
),
child: Container(
alignment: Alignment.center,
constraints: BoxConstraints(maxWidth: double.infinity,minHeight: 50),
child: Text("Login",style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold),textAlign: TextAlign.center,),
),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
),
),
SizedBox(height: 16,),
Container(
height: 50,
width: double.infinity,
child: FlatButton(
onPressed: (){},
color: Colors.indigo.shade50,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.asset("assets/images/facebook.png",height: 18,width: 18,),
SizedBox(width: 10,),
Text("Connect with Facebook",style: TextStyle(color: Colors.indigo,fontWeight: FontWeight.bold),),
],
),
),
),
SizedBox(height: 16,),
Container(
height: 50,
width: double.infinity,
child: FlatButton(
onPressed: (){},
color: Colors.indigo.shade50,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.asset("assets/images/facebook.png",height: 18,width: 18,),
SizedBox(width: 10,),
Text("Connect with Facebook",style: TextStyle(color: Colors.indigo,fontWeight: FontWeight.bold),),
],
),
),
),
],
),
Padding(
padding: EdgeInsets.only(bottom: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Don't have an account?",style: TextStyle(fontWeight: FontWeight.bold),),
SizedBox(width: 5,),
GestureDetector(
onTap: (){
Navigator.push(context, MaterialPageRoute(builder: (context){
return SignupPage();
}));
},
child: Text("Sign up",style: TextStyle(fontWeight: FontWeight.bold,color: Colors.red),),
)
],
),
)
],
),
),
),
),
);
}
}
Full Example.main login here is:
take a boolean param for detecting if text is obscure or not
change suffix icon based on that boolean value
change the boolean value on suffix item click
below i gave a full example for the task.
bool _passwordInVisible = true; //a boolean value
TextFormField buildPasswordFormField() {
return TextFormField(
obscureText: _passwordInVisible,
onSaved: (newValue) => registerRequestModel.password = newValue,
onChanged: (value) {
if (value.isNotEmpty) {
removeError(error: kPassNullError);
} else if (value.length >= 8) {
removeError(error: kShortPassError);
}
return null;
},
validator: (value) {
if (value.isEmpty) {
addError(error: kPassNullError);
return "";
} else if (value.length < 8) {
addError(error: kShortPassError);
return "";
}
return null;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: "Password",
hintText: "Enter your password",
contentPadding: new EdgeInsets.symmetric(vertical: 5.0, horizontal: 15.0),
floatingLabelBehavior: FloatingLabelBehavior.always,
suffixIcon: IconButton(
icon: Icon(
_passwordInVisible ? Icons.visibility_off : Icons.visibility, //change icon based on boolean value
color: Theme.of(context).primaryColorDark,
),
onPressed: () {
setState(() {
_passwordInVisible = !_passwordInVisible; //change boolean value
});
},
),
),
);
}
Here two scenarios come
If you want your suffix icon color constant like always grey, you can give color property of icon, like :
button for password show hide
var passShowButton = GestureDetector(
onLongPressEnd: outContact,
onTapDown: inContact, //call this method when incontact
onTapUp:
outContact, //call this method when contact with screen is removed
child: Icon(
getXHelper.isEmailPasswordUpdate.isTrue
? AppIcons.hidePassword
: AppIcons.hidePassword,
size: 18,
color:Colors.grey
),
);
TextField
TextField(
obscureText: getXHelper.isPassInvisible ,
autocorrect: false,
textAlignVertical: TextAlignVertical.bottom,
decoration: InputDecoration(
enabled: true,
errorBorder: UnderlineInputBorder(
borderSide: BorderSide(color: AppColors.primary)),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: AppColors.primary)),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: AppColors.primary)),
border: UnderlineInputBorder(
borderSide: BorderSide(color: AppColors.primary)),
fillColor: Colors.white,
filled: true,
isDense: true,
prefixIconConstraints: BoxConstraints(maxHeight: 18, minHeight: 18),
hintText: "Password",
prefixIcon: Padding(
padding: const EdgeInsets.only(top: 0, right: 12, bottom: 0),
child: Icon(Icons.lock, size: 18, color: Colors.grey),
),
suffixIcon: passShowButton,
),
cursorColor: Colors.black,
style: TextStyle(
color: Colors.black, fontFamily: AppFontFamily.fontFamily),
)
If you want your suffix icon color of your app-Primary Color, will change color when textfield focus, like :
Password show hide button
var passShowButton = GestureDetector(
onLongPressEnd: outContact,
onTapDown: inContact, //call this method when incontact
onTapUp:
outContact, //call this method when contact with screen is removed
child: Icon(
getXHelper.isEmailPasswordUpdate.isTrue
? AppIcons.hidePassword
: AppIcons.hidePassword,
size: 18,
),
);
TextField(
obscureText: getXHelper.isPassInvisible ,
autocorrect: false,
textAlignVertical: TextAlignVertical.bottom,
decoration: InputDecoration(
enabled: true,
errorBorder: UnderlineInputBorder(
borderSide: BorderSide(color: AppColors.primary)),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: AppColors.primary)),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: AppColors.primary)),
border: UnderlineInputBorder(
borderSide: BorderSide(color: AppColors.primary)),
fillColor: Colors.white,
filled: true,
isDense: true,
prefixIconConstraints: BoxConstraints(maxHeight: 18, minHeight: 18),
hintText: "Password",
prefixIcon: Padding(
padding: const EdgeInsets.only(top: 0, right: 12, bottom: 0),
child: Icon(Icons.lock, size: 18),
),
suffixIcon: passShowButton,
),
cursorColor: Colors.black,
style: TextStyle(
color: Colors.black, fontFamily: AppFontFamily.fontFamily),
)
you can put text field and icon button in a stack
replace this code with your password textfield.
you can change icon button position to what you want.
Stack(
children: [
TextFormField(
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: "Password",
labelStyle:
TextStyle(fontSize: 14, color: Colors.grey.shade400),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide(
color: Colors.grey.shade300,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: BorderSide(
color: Colors.red,
)),
),
validator: (password) {
Pattern pattern =
r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!##\$&*~]).{8,}$';
RegExp regex = new RegExp(pattern);
if (password.isEmpty) {
return 'Please Enter Password';
} else if (!regex.hasMatch(password))
return 'Enter valid password';
else
return null;
},
onSaved: (password) => _password = password,
textInputAction: TextInputAction.done,
obscureText: _obscureText,
),
Positioned(
top: 2,
right: 10,
child: IconButton(
icon: Icon(
_obscureText ? Icons.visibility : Icons.visibility_off,
),
onPressed: () {
setState(() {
_obscureText = !_obscureText;
});
}),
),
],
),
I just copied and run your code and it works just fine. The icon was visible when the password field had focus. You should maybe check your flutter version or it might probably be your emulator device.
flutter --version
Flutter 1.22.3 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 8874f21e79 (2 weeks ago) • 2020-10-29 14:14:35 -0700
Engine • revision a1440ca392
Tools • Dart 2.10.3
Actually, the suffix icon is visible but when i click on TextFormField then the icon color is changing to white so simply in icon field i added a color property and give a black color to icon so even textfield is in focus its color remain black.

Upload data to Firebase database

On trying to upload data to the firebase realtime database error comes.
After filling the form data when the save button is pressed.The uploadPic function is called that upload the text from textfield to the firebase, the error message comes on the console of Android Studio.
The screenshot of the error is in the link below.
Code is also mentioned below,
The uploadPic function is at line 72
Code:
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:image_picker/image_picker.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:udharibook/Screens/dashboard.dart';
class UserProfile extends StatefulWidget {
#override
_UserProfileState createState() => _UserProfileState();
}
class _UserProfileState extends State<UserProfile> {
var _formKey = GlobalKey<FormState>();
TextEditingController nameController;
TextEditingController phoneController;
TextEditingController emailController;
TextEditingController addressController;
var profileImage =
'https://firebasestorage.googleapis.com/v0/b/udhari-book.appspot.com/o/DefaultImage.png?alt=media&token=06bddd3e-7f11-476b-a982-dfb21096f9c7';
File _image;
String fileName;
static var userId;
FirebaseAuth _auth = FirebaseAuth.instance;
DatabaseReference DBRef =
FirebaseDatabase.instance.reference().child('Users');
void initState() {
super.initState();
_auth.currentUser().then((curUser) {
userId = curUser.uid;
print('Current user id:' + userId);
DBRef.child(curUser.uid).once().then((DataSnapshot user) {
if (user != null) {
setState(() {
//Provide the initial value of the user in the text field
phoneController = TextEditingController(text: curUser.phoneNumber);
profileImage = user.value['ProfileImage'];
nameController = TextEditingController(text: user.value['Name']);
emailController = TextEditingController(text: user.value['Email']);
addressController =TextEditingController(text: user.value['Address']);
});
}
});
});
}
#override
Widget build(BuildContext context) {
Future getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
_image = image;
fileName = phoneController.text;
StorageReference firebaseStorageRef =
FirebaseStorage.instance.ref().child('Images/$fileName');
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
StorageTaskSnapshot imgSnapshot = await uploadTask.onComplete;
if (imgSnapshot.error == null) {
profileImage = await imgSnapshot.ref.getDownloadURL();
}
setState(() {
print('Image uploaded successfully');
});
}
Future uploadPic(BuildContext context) async {
print('The user name is: '+nameController.text);
DBRef.child(userId).set({
'User Id': userId,
'Name': nameController.text,
'Mobile': fileName,
'Email':emailController.text,
'Address': addressController.text,
'ProfileImage': profileImage,
});
setState(() {
print('Data uploaded Successfully');
//DashboardPage(userName: nameController.text,imgUrl: imgUrl,);
});
}
return Scaffold(
appBar: AppBar(
title: Text('User Profile'),
backgroundColor: Color.fromRGBO(162, 42, 43, 1.0),
),
body: Builder(
builder: (context) => SingleChildScrollView(
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
SizedBox(
height: 10.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
//Profile Image widget
Align(
alignment: Alignment.center,
child: CircleAvatar(
radius: 70,
backgroundColor: Colors.white,
child: ClipOval(
child: SizedBox(
height: 120.0,
width: 120.0,
child: _image != null
? Image.file(_image, fit: BoxFit.fill)
: Image.network(
profileImage,
fit: BoxFit.fitWidth,
),
),
),
),
),
//Camera Icon Widget
Padding(
padding: EdgeInsets.only(),
child: IconButton(
icon: Icon(Icons.camera_alt),
onPressed: () {
getImage();
}),
)
],
),
//Name TextField
Padding(
padding: EdgeInsets.only(top: 20.0, left: 10.0, right: 10.0),
child: TextFormField(
controller: nameController,
validator: (input) {
if (input.isEmpty) return 'Please enter Name';
},
decoration: InputDecoration(
contentPadding: new EdgeInsets.symmetric(vertical: 5.0,horizontal: 20.0),
labelText: 'Full Name',
labelStyle:
TextStyle(fontFamily: 'Exo2', color: Colors.grey),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0)),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0),
borderSide: BorderSide(
color: Color.fromRGBO(162, 42, 43, 1.0)))),
),
),
//Mobile Text Field
Padding(
padding:
EdgeInsets.only(top: 15.0, left: 10.0, right: 10.0),
child: SizedBox(
height: 40.0,
child: TextField(
controller: phoneController,
enabled: false,
keyboardType: TextInputType.phone,
decoration: InputDecoration(
contentPadding: new EdgeInsets.symmetric(vertical: 5.0,horizontal: 20.0),
labelText: 'Mobile Number',
labelStyle: TextStyle(
fontFamily: 'Exo2', color: Colors.grey),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0)),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0),
borderSide: BorderSide(
color: Color.fromRGBO(162, 42, 43, 1.0)))),
),
)),
//Email Text Field
Padding(
padding: EdgeInsets.only(top: 15.0, left: 10.0, right: 10.0),
child: TextFormField(
controller: emailController,
validator: (input) {
if (input.isNotEmpty && input.contains('#') == false)
return 'Please enter correct Email Id';
else if (input.isEmpty) return 'Please enter Email Id';
},
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
contentPadding: new EdgeInsets.symmetric(vertical: 5.0,horizontal: 20.0),
labelText: 'Email Id',
labelStyle:
TextStyle(fontFamily: 'Exo2', color: Colors.grey),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0)),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0),
borderSide: BorderSide(
color: Color.fromRGBO(162, 42, 43, 1.0)))),
),
),
//Address Text Field
Padding(
padding: EdgeInsets.only(
top: 15.0, left: 10.0, right: 10.0, bottom: 30.0),
child: TextFormField(
maxLines: 3,
maxLengthEnforced: true,
controller: addressController,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Address (Optional)',
labelStyle:
TextStyle(fontFamily: 'Exo2', color: Colors.grey),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0)),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0),
borderSide: BorderSide(
color: Color.fromRGBO(162, 42, 43, 1.0)))),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
//Save Button
SizedBox(
width: 130.0,
height: 50.0,
child: RaisedButton(
color: Color.fromRGBO(162, 42, 43, 1.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0)),
onPressed: () {
if (_formKey.currentState.validate()) {
uploadPic(context);
} else
setState(() {});
},
elevation: 4.0,
splashColor: Colors.blueGrey,
child: Text(
'Save',
style: TextStyle(
color: Colors.white,
fontSize: 22.0,
fontFamily: 'Exo2'),
),
)),
//Cancel Button
SizedBox(
width: 130.0,
height: 50.0,
child: RaisedButton(
color: Color.fromRGBO(162, 42, 43, 1.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0)),
onPressed: () {
Navigator.of(context).pop();
},
elevation: 4.0,
splashColor: Colors.blueGrey,
child: Text(
'Cancel',
style: TextStyle(
color: Colors.white,
fontSize: 22.0,
fontFamily: 'Exo2'),
),
))
],
)
],
),
),
),
),
);
}
}
Replace this :
TextEditingController nameController;
TextEditingController phoneController;
TextEditingController emailController;
TextEditingController addressController;
With this:
TextEditingController nameController = TextEditingController();
TextEditingController phoneController = TextEditingController();
TextEditingController emailController = TextEditingController();
TextEditingController addressController = TextEditingController();
And also replace this
onPressed: () {
if (_formKey.currentState.validate()) {
uploadPic(context);
}
else
setState(() {});
},
with this:
OnPressed: () {
setState(() {
if (_formKey.currentState.validate()) {
uploadPic(context);
} //else
});
},