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
});
},
Related
i'm trying to make a simple crud , now i'm trying to add "patient" to my db .
But i have a problem nothing register in the database ,
i initializedmy values ( i don't know if its corect im still beginner in dart ) but the only data i get in firestore is the initial values
here's my code , can you help me please ?
const kTextFieldDecoration = InputDecoration(
hintText: 'Enter a value',
hintStyle: TextStyle(color: Colors.grey),
contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(32.0)),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Color(0xff5AA7A7), width: 1.0),
borderRadius: BorderRadius.all(Radius.circular(32.0)),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Color(0xff5AA7A7), width: 2.0),
borderRadius: BorderRadius.all(Radius.circular(32.0)),
),
);
class Background extends StatefulWidget {
final Widget child;
const Background({
Key? key,
required this.child,
}) : super(key: key);
#override
_BackgroundState createState() => _BackgroundState();
}
class _BackgroundState extends State<Background>{
final _auth = FirebaseAuth.instance;
late XFile _image;
late String name;
late String birth ;
late int pass ;
late String? genre ;
TextEditingController dateinput = TextEditingController();
final List<String> genderItems = [
'Male',
'Female',
];
String? selectedValue;
final ImagePicker _picker = ImagePicker();
bool showSpinner = false;
void _showPicker(context) {
showModalBottomSheet(
context: context,
builder: (BuildContext bc) {
return SafeArea(
child: Container(
child: new Wrap(
children: <Widget>[
],
),
),
);
}
);
}
#override
void initState() {
genre = "None";
birth="None";
pass=0000;
name="null";
super.initState();
}
void addPatient() {
FirebaseFirestore.instance.collection("patient").add(
{
"name" : name,
"genre" : genre,
"birth" : birth,
"pass" : pass,
}).then((value){
print("Patient data Added");
});
}
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Scaffold(
resizeToAvoidBottomInset: false ,
backgroundColor: Colors.white,
body: ModalProgressHUD(
inAsyncCall: showSpinner,
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Container(
child : CircleAvatar(
radius: 70.0,
backgroundImage: AssetImage("assets/images/avatar.png"),
),
),
Container(
padding: EdgeInsets.only( left: 100.0),
child : Positioned(
bottom: 50.0,
right: 20.0,
child: InkWell(onTap: () {
_showPicker(context);
},
child: Icon(
Icons.camera_alt_outlined,
size:28.0,color:
Colors.teal,
),
), ), ), TextField(
keyboardType: TextInputType.text,
textAlign: TextAlign.center,
onChanged: (value) {
name = value;
},
decoration: kTextFieldDecoration.copyWith(
labelText: 'Name')),
TextField(
obscureText: true,
textAlign: TextAlign.center,
onChanged: (value) {
pass = value as int;
},
decoration: kTextFieldDecoration.copyWith(
labelText: 'Password',)),
Column(
children: [
DropdownButtonFormField(
decoration:
InputDecoration(
hintStyle: TextStyle(color: Colors.grey),
contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(32.0)),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Color(0xff5AA7A7), width: 1.0),
borderRadius: BorderRadius.all(Radius.circular(32.0)),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Color(0xff5AA7A7), width: 2.0),
borderRadius: BorderRadius.all(Radius.circular(32.0)),
),
labelText: 'Gender',
),
isExpanded: true,
icon: const Icon(
Icons.arrow_drop_down,
color: Colors.teal,
),
iconSize: 30,
items: genderItems
.map((item) =>
DropdownMenuItem<String>(
value: item,
child: Text(
item,
style: const TextStyle(
fontSize: 14,
),
),
))
.toList(),
validator: (value) {
if (value == null) {
return 'Please select gender.';
}
},
onChanged: (value) {
genre = value as String? ; //Do something when changing the item if you want.
},
onSaved: (value) {
selectedValue = value.toString();
},
),
],
),
TextField(
controller: dateinput,
obscureText: true,
textAlign: TextAlign.center,
onChanged: (value) {
birth = value ;
},
decoration: InputDecoration(
hintStyle: TextStyle(color: Colors.grey),
contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(32.0)),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Color(0xff5AA7A7), width: 1.0),
borderRadius: BorderRadius.all(Radius.circular(32.0)),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Color(0xff5AA7A7), width: 2.0),
borderRadius: BorderRadius.all(Radius.circular(32.0)),
),
//icon of text field
labelText: "Date of Birth" , //label text of field
),
onTap: () async {
DateTime? birth = await showDatePicker(
context: context, initialDate: DateTime.now(),
firstDate: DateTime(1900), //DateTime.now() - not to allow to choose before today.
lastDate: DateTime(2023),
);
if(birth != null ){
print(birth);
setState(() {
dateinput.text = birth as String;
});
}else{
print("Date is not selected");
}}, ),
RoundedButton(
colour: Color(0xff96D7C6),
title: 'Submit',
onPressed: () async {
setState(() {
showSpinner = true;
});
addPatient();
Navigator.pushNamed(context, 'patient_screen');
},),],),),), ), ); }}
this is the login screen I had Implemented using flutter. I want this screen to be scrollable. how can I do that? I have uploaded my login screen code for your reference. I have tried out my column wrap with a single-child scroll view. but it doesn't work. there are multiple columns, maybe I'm wrapping the wrong column. I appriciate your help on this.
class LoginScreen extends StatefulWidget {
const LoginScreen({Key? key}) : super(key: key);
#override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
#override
Widget build(BuildContext context) {
final Size = MediaQuery.of(context).size;
return GestureDetector(
onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
child: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Color.fromARGB(255, 3, 86, 124), Color(0xff141a3a)],
begin: Alignment.topRight,
end: Alignment.bottomLeft,
)),
child: Scaffold(
backgroundColor: Colors.transparent,
resizeToAvoidBottomInset: false,
body: Padding(
padding: const EdgeInsets.only(top: 40, left: 20, right: 20),
child: Column(
children: [
Expanded(
flex: 2,
child: Column(
children: [
// Spacer(flex: 1),
Image(
image: const AssetImage(
'assets/images/LogoVector.png',
),
height: Size.width / 2.9,
width: Size.width / 2.9,
),
SizedBox(height: 5),
Text(
"LOGIN",
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 30,
color: textWhite,
fontFamily: "Roboto"),
),
],
),
),
// const Spacer(flex: 1),
const Expanded(flex: 3, child: Center(child: LoginForm())),
],
),
),
),
),
);
}
}
class LoginForm extends StatefulWidget {
const LoginForm({Key? key}) : super(key: key);
#override
_LoginFormState createState() => _LoginFormState();
}
Map<String, String> loginUserData = {
'email': '',
'password': '',
'id': '',
'userName': '',
'token': '',
'userStatus': '',
};
class _LoginFormState extends State<LoginForm> {
TextEditingController emailEditingController = new TextEditingController();
TextEditingController passwordEditingController = new TextEditingController();
final _formKey = GlobalKey<FormState>();
String email = "";
String password = "";
String username = "";
bool isLoading = false;
bool typing = true;
bool _isObscure = true;
#override
Widget build(BuildContext context) {
final Size = MediaQuery.of(context).size;
return Form(
key: _formKey,
autovalidateMode: AutovalidateMode.disabled,
child: Column(
children: [
TextFormField(
controller: emailEditingController,
enabled: true,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: const BorderSide(
color: textWhite,
),
// borderSide: BorderSide.none
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: const BorderSide(color: textWhite),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: const BorderSide(color: Colors.red),
),
focusedErrorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: const BorderSide(color: Colors.red),
),
isDense: true,
contentPadding: EdgeInsets.fromLTRB(10, 30, 10, 0),
hintText: "Email/ Username",
hintStyle: TextStyle(
color: textWhite, fontFamily: "Roboto", fontSize: 14),
),
style: TextStyle(color: textWhite),
validator: (String? UserName) {
if (UserName != null && UserName.isEmpty) {
return "Email can't be empty";
}
return null;
},
onChanged: (String? text) {
email = text!;
// print(email);
},
onSaved: (value) {
loginUserData['email'] = value!;
},
),
SizedBox(
height: 10,
),
TextFormField(
controller: passwordEditingController,
obscureText: _isObscure,
enabled: true,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: const BorderSide(color: textWhite),
// borderSide: BorderSide.none
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30.0),
borderSide: const BorderSide(color: textWhite),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(color: Colors.red),
),
focusedErrorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(color: Colors.red),
),
isDense: true,
contentPadding: EdgeInsets.fromLTRB(10, 10, 10, 0),
suffixIcon: IconButton(
icon: Icon(
_isObscure ? Icons.visibility : Icons.visibility_off),
color: textWhite,
onPressed: () {
setState(() {
_isObscure = !_isObscure;
});
}),
hintText: "Password",
hintStyle: TextStyle(
color: textWhite,
fontFamily: "Roboto",
fontSize: 14,
)),
style: TextStyle(color: textWhite),
validator: (String? Password) {
if (Password != null && Password.isEmpty) {
return "Password can't be empty";
}
return null;
},
onChanged: (String? text) {
password = text!;
print(password);
},
onSaved: (value) {
loginUserData['password'] = value!;
},
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Expanded(
child: CheckboxListTile(
title: const Text(
"Remember Me",
style: TextStyle(
color: textWhite, fontFamily: "Roboto", fontSize: 14),
),
activeColor: buttontext,
// tileColor: buttontext,
value: checkedValue,
onChanged: (newValue) {
FocusManager.instance.primaryFocus?.unfocus();
setState(() {
if (isLoading != true) {
checkedValue = newValue!;
print(newValue);
}
});
},
contentPadding: EdgeInsets.only(left: 0, top: 0),
controlAffinity:
ListTileControlAffinity.leading, // <-- leading Checkbox
),
),
TextButton(
child: Text(
"Forget Password",
style: TextStyle(
color: textWhite, fontFamily: "Roboto", fontSize: 14),
),
onPressed: () {
Get.to(() => Forget_Screen());
},
)
],
),
SizedBox(height: 40),
isLoading
? SpinKitDualRing(
color: textWhite,
size: 40,
)
: GestureDetector(
child: MainButton("Login"),
onTap: () async {
FocusManager.instance.primaryFocus?.unfocus();
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
await LoginData();
// Get.to(BottomNavigation());
}
},
),
SizedBox(height: 15),
Container(
width: 275.0,
height: 40.0,
child: OutlinedButton(
onPressed: () {
Get.to(() => const Signup_Screen());
},
child: const Text(
'Signup',
style: TextStyle(
fontSize: 15, fontFamily: "Roboto", color: textWhite
//fontWeight: FontWeight.w500,
// color: Colors.black,
),
),
style: OutlinedButton.styleFrom(
side: const BorderSide(
width: 1.0,
color: textWhite,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
),
),
),
)
],
),
);
}
}
You should wrap everything under the Scaffold:
Scaffold(
backgroundColor: Colors.transparent,
resizeToAvoidBottomInset: false,
body: SingleChildScrollView(child: Padding(
padding: const EdgeInsets.only(top: 40, left: 20, right: 20),
child: Column(
........
I can not see you using the SingleChildScrollView in then code sample you have provided with.
But if you want to make the page scrollable, Wrap the child of the scaffold in the SingleChildScrollView
Scaffold(
body: SingleChildScrollView(
....
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),
),
);
},
),
],
)
])))));
}
}```
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..
I'm new to flutter and struggling to correct below error. No MaterialLocalizations found. error in code. am I missing a library? or any code ? how can I fix this. appriciate your help on this.
error suggesion >>> To introduce a MaterialLocalizations, either use a MaterialApp at the root of your application to include them automatically, or add a Localization widget with a MaterialLocalizations delegate.
createProfile.dart
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';
import 'package:http/http.dart' ;
import 'package:flutter/material.dart';
class CreateProfile extends StatefulWidget {
CreateProfile({required Key key}) : super(key: key);
#override
_CreateProfileState createState() => _CreateProfileState();
}
class _CreateProfileState extends State<CreateProfile> {
bool circular = false;
PickedFile? _imageFile;
final ImagePicker _picker = ImagePicker();
final _globalkey = GlobalKey<FormState>();
TextEditingController _name = TextEditingController();
TextEditingController _profession = TextEditingController();
TextEditingController _dob = TextEditingController();
TextEditingController _title = TextEditingController();
TextEditingController _about = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
body: Form(
key: _globalkey,
child: ListView(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30),
children: <Widget>[
imageProfile(),
SizedBox(
height: 20,
),
nameTextField(),
SizedBox(
height: 20,
),
professionTextField(),
SizedBox(
height: 20,
),
dobField(),
SizedBox(
height: 20,
),
titleTextField(),
SizedBox(
height: 20,
),
aboutTextField(),
SizedBox(
height: 20,
),
InkWell(
onTap: (){
if (_globalkey.currentState!.validate()){
print("validated");
}
},
child: Center(
child: Container(
width: 200,
height: 50,
decoration: BoxDecoration(
color: Colors.teal,
borderRadius: BorderRadius.circular(10),
),
child: Center(
child: circular
? CircularProgressIndicator()
: Text(
"Submit",
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
),
),
),
],
),
),
);
}
Widget imageProfile() {
return Center(
child: Stack(children: <Widget>[
CircleAvatar(
radius: 80.0,
backgroundImage: _imageFile == null
? AssetImage("assets/pic.jpg") as ImageProvider
: FileImage(File(_imageFile!.path)),
),
Positioned(
bottom: 20.0,
right: 20.0,
child: InkWell(
onTap: () {
showModalBottomSheet(
context: context,
builder: ((builder) => bottomSheet()),
);
},
child: Icon(
Icons.camera_alt,
color: Colors.teal,
size: 28.0,
),
),
),
]),
);
}
Widget bottomSheet() {
return Container(
height: 100.0,
width: MediaQuery.of(context).size.width,
margin: EdgeInsets.symmetric(
horizontal: 20,
vertical: 20,
),
child: Column(
children: <Widget>[
Text(
"Choose Profile photo",
style: TextStyle(
fontSize: 20.0,
),
),
SizedBox(
height: 20,
),
Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[
TextButton.icon(
icon: Icon(Icons.camera),
onPressed: () {
takePhoto(ImageSource.camera);
},
label: Text("Camera", ),
),
TextButton.icon(
icon: Icon(Icons.image),
onPressed: () {
takePhoto(ImageSource.gallery);
},
label: Text("Gallery"),
),
])
],
),
);
}
void takePhoto(ImageSource source) async {
final pickedFile = await _picker.pickImage(
source: source,
);
setState(() {
_imageFile = pickedFile as PickedFile;
});
}
//starting text fields
Widget nameTextField() {
return TextFormField(
controller: _name,
validator: (value) {
if (value!.isEmpty) return "Name can't be empty";
return null;
},
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.teal,
)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.orange,
width: 2,
)),
prefixIcon: Icon(
Icons.person,
color: Colors.green,
),
labelText: "Name",
helperText: "Name can't be empty",
hintText: "Anne Perera",
),
);
}
Widget professionTextField() {
return TextFormField(
controller: _profession,
validator: (value) {
if (value!.isEmpty) return "Profession can't be empty";
return null;
},
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.teal,
)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.orange,
width: 2,
)),
prefixIcon: Icon(
Icons.person,
color: Colors.green,
),
labelText: "Profession",
helperText: "Profession can't be empty",
hintText: "Full Stack Developer",
),
);
}
Widget dobField() {
return TextFormField(
controller: _dob,
validator: (value) {
if (value!.isEmpty) return "DOB can't be empty";
return null;
},
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.teal,
)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.orange,
width: 2,
)),
prefixIcon: Icon(
Icons.person,
color: Colors.green,
),
labelText: "Date Of Birth",
helperText: "Provide DOB on dd/mm/yyyy",
hintText: "01/01/2020",
),
);
}
Widget titleTextField() {
return TextFormField(
controller: _title,
validator: (value) {
if (value!.isEmpty) return "Title can't be empty";
return null;
},
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.teal,
)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.orange,
width: 2,
)),
prefixIcon: Icon(
Icons.person,
color: Colors.green,
),
labelText: "Title",
helperText: "It can't be empty",
hintText: "Flutter Developer",
),
);
}
Widget aboutTextField() {
return TextFormField(
controller: _about,
validator: (value) {
if (value!.isEmpty) return "About can't be empty";
return null;
},
maxLines: 4,
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.teal,
)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.orange,
width: 2,
)),
labelText: "About",
helperText: "Write about yourself",
hintText: "I am Ann Perera",
),
);
}
}
main.dart
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
if (USE_EMULATOR) {
_connectToFirebaseEmulator();
}
runApp(const MyApp());
}
Future _connectToFirebaseEmulator() async {
final fireStorePort = "8080";
final authPort = 9099;
final localHost = Platform.isAndroid ? '10.0.2.2' : 'localhost';
FirebaseFirestore.instance.settings = Settings(
host: "$localHost:$fireStorePort",
sslEnabled: false,
persistenceEnabled: false);
await FirebaseAuth.instance.useAuthEmulator('http://$localHost:', authPort);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return CupertinoApp(
home: CreateProfile(key: UniqueKey()),
debugShowCheckedModeBanner: false,
theme: CupertinoThemeData(
brightness: Brightness.light, primaryColor: Color(0xff08c187)),
);
}
}
The error basically says that to use material widgets in a cupertino app you will have to add this:
CupertinoApp(
localizationsDelegates: [
DefaultMaterialLocalizations.delegate,
DefaultCupertinoLocalizations.delegate,
DefaultWidgetsLocalizations.delegate,
],
),