Error when focussing on next Focus in Flutter - flutter

If I click away from a TextField and then back on it and want to focus on the next TextField (using FocusScope.of(context).nextFocus()) by hitting enter on the software keyboard I get this error:
Exception has occurred.
_AssertionError ('package:flutter/src/widgets/focus_manager.dart': Failed assertion: line 790 pos 7: 'context != null': Tried to get the bounds of a focus node that didn't have its context set yet.
The context needs to be set before trying to evaluate traversal policies. Setting the context is typically done with the attach method.)
This is my code:
import 'package:quizlet/api/convert_json.dart';
import 'package:quizlet/style.dart';
class CreateQuiz extends StatefulWidget {
const CreateQuiz({super.key});
#override
State<CreateQuiz> createState() => _CreateQuizState();
}
class _CreateQuizState extends State<CreateQuiz> {
int wordCount = 3;
List errorDefinitions = [false, false, false];
List errorAnswers = [false, false, false];
bool errorTitle = false;
bool errorDescription = false;
final List definitions = [
TextEditingController(),
TextEditingController(),
TextEditingController()
];
final List answers = [
TextEditingController(),
TextEditingController(),
TextEditingController()
];
final title = TextEditingController();
final description = TextEditingController();
#override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
final brightness = MediaQuery.of(context).platformBrightness;
bool darkMode = brightness == Brightness.dark;
final hintColor = darkMode ? Colors.white : Colors.black;
return Scaffold(
appBar: AppBar(
title: const Text("Create Quiz"),
actions: [
TextButton(
style: TextButton.styleFrom(
foregroundColor: Colors.white,
),
onPressed: () {
onPressed();
},
child: Text(
"Done",
style: TextStyle(fontSize: height / 55),
),
),
],
),
body: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
FocusScope.of(context).requestFocus(FocusNode());
},
child: Padding(
padding: const EdgeInsets.all(10.0),
child: ListView(
children: [
SizedBox(
height: height / 40,
),
TextField(
onSubmitted: (value) {
FocusScope.of(context).nextFocus();
},
onChanged: (value) {
setState(() {
errorTitle = false;
});
},
textInputAction: TextInputAction.next,
onEditingComplete: () {},
keyboardType: TextInputType.multiline,
controller: title,
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(10.0),
hintStyle: TextStyle(
color: errorTitle ? Colors.red : hintColor,
),
hintText: errorTitle ? "Title can't be blank" : "Title",
border: const OutlineInputBorder(),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: errorTitle ? Colors.red : color1,
width: 2.0,
),
),
),
),
const SizedBox(
height: 5,
),
TextField(
onSubmitted: (value) {
FocusScope.of(context).nextFocus();
},
onChanged: (value) {
setState(() {
errorDescription = false;
});
},
textInputAction: TextInputAction.newline,
onEditingComplete: () {},
controller: description,
maxLines: null,
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(10.0),
hintText: errorDescription
? "Description can't be blank"
: "Description",
hintStyle: TextStyle(
color: errorDescription ? Colors.red : hintColor,
),
border: const OutlineInputBorder(),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: errorDescription ? Colors.red : color1,
width: 2.0,
),
),
),
),
SizedBox(
height: height / 20,
),
ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: wordCount,
itemBuilder: (BuildContext context, int i) {
return Column(
children: [
TextField(
onSubmitted: (value) {
FocusScope.of(context).nextFocus();
},
onChanged: (value) {
setState(() {
errorDefinitions[i] = false;
});
},
textInputAction: TextInputAction.next,
onEditingComplete: () {},
autocorrect: false,
controller: definitions[i],
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(10.0),
hintStyle: TextStyle(
color: errorDefinitions[i] ? Colors.red : hintColor,
),
hintText: errorDefinitions[i]
? "Definition can't be blank"
: "Definition",
border: const OutlineInputBorder(),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: errorDefinitions[i] ? Colors.red : color1,
width: 2.0,
),
),
),
),
const SizedBox(
height: 5,
),
TextField(
onSubmitted: (value) {
setState(() {
if (definitions[i].text != "" &&
answers[i].text != "") {
if (i + 2 >= wordCount) {
wordCount++;
definitions.add(TextEditingController());
answers.add(TextEditingController());
errorAnswers.add(false);
errorDefinitions.add(false);
}
FocusScope.of(context).nextFocus();
}
});
},
onChanged: (value) {
setState(() {
errorAnswers[i] = false;
});
},
textInputAction: TextInputAction.next,
onEditingComplete: () {},
autocorrect: false,
controller: answers[i],
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(10.0),
hintStyle: TextStyle(
color: errorAnswers[i] ? Colors.red : hintColor,
),
hintText: errorAnswers[i]
? "Answer can't be blank"
: "Answer",
border: const OutlineInputBorder(),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: errorAnswers[i] ? Colors.red : color1,
width: 2.0,
),
),
),
),
SizedBox(
height: height / 50,
),
],
);
},
),
],
),
),
),
);
}```

Related

How to get data in a Flutter-ListView?

I'm building a form for shipping and am able to add as many items as possible. (Adding a Widget in a ListView every time a button is pressed)
My question is, once the form widgets are created and filled, how do I get the information from each TextFormField in each Widget?
Once the information is retrieved I will send it to Firebase.
Here's the code I Have:
import 'package:flutter/material.dart';
import 'package:flutter_login_test/helpers/constants.dart';
class AddItemsToRequest extends StatefulWidget {
const AddItemsToRequest({Key? key}) : super(key: key);
#override
State<AddItemsToRequest> createState() => _AddItemsToRequestState();
}
class _AddItemsToRequestState extends State<AddItemsToRequest> {
List<TextEditingController> controllers = [];
List<Widget> fields = [];
RegExp regExp = RegExp('[aA-zZ]');
int quantity = 0;
double weight = 0;
double height = 0;
Widget itemForm() {
return Column(children: [
Container(
decoration:
BoxDecoration(color: grey, border: Border.all(color: black)),
width: double.infinity,
child: const Center(
child: Text('Package details',
style: TextStyle(
fontWeight: FontWeight.bold,
backgroundColor: grey,
fontSize: 24)),
)),
Row(
children: [
Flexible(
child: TextFormField(
onChanged: (value) {
quantity = value as int;
},
keyboardType: TextInputType.number,
validator: (value) => value!.isEmpty || value is int
? 'Quantity cannot be empty'
: null,
autovalidateMode: AutovalidateMode.onUserInteraction,
decoration: const InputDecoration(
errorStyle: TextStyle(color: Colors.redAccent),
border: OutlineInputBorder(
borderSide: BorderSide(),
borderRadius: BorderRadius.all(
Radius.circular(0.0),
),
),
fillColor: Color.fromARGB(255, 238, 238, 238),
filled: true,
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blueAccent, width: 2.5),
),
hintText: "Quantity : "),
),
),
Flexible(
child: TextFormField(
onChanged: (value) {
weight = value as double;
},
keyboardType: TextInputType.number,
validator: (value) => value!.isEmpty || regExp.hasMatch(value)
? 'Weight cannot be empty'
: null,
autovalidateMode: AutovalidateMode.onUserInteraction,
decoration: const InputDecoration(
errorStyle: TextStyle(color: Colors.redAccent),
border: OutlineInputBorder(
borderSide: BorderSide(),
borderRadius: BorderRadius.all(
Radius.circular(0.0),
),
),
fillColor: Color.fromARGB(255, 238, 238, 238),
filled: true,
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blueAccent, width: 2.5),
),
hintText: "Weight : "),
),
),
Flexible(
child: TextFormField(
onChanged: (value) {
height = value;
},
validator: (value) => value!.isEmpty ? 'Height cannot be empty' : null,
autovalidateMode: AutovalidateMode.onUserInteraction,
decoration: const InputDecoration(
errorStyle: TextStyle(color: Colors.redAccent),
border: OutlineInputBorder(
borderSide: BorderSide(),
borderRadius: BorderRadius.all(
Radius.circular(0.0),
),
),
fillColor: Color.fromARGB(255, 238, 238, 238),
filled: true,
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blueAccent, width: 2.5),
),
hintText: "Height : "),
),
),
],
),
]);
}
Widget _addTile() {
return ElevatedButton(
child: const Icon(Icons.add),
onPressed: () async {
final controller = TextEditingController();
final field = itemForm();
setState(() {
controllers.add(controller);
fields.add(field);
});
});
}
Widget _listView() {
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: fields.length,
itemBuilder: (context, index) {
final item = fields[index];
return Dismissible(
key: ObjectKey(item),
onDismissed: (direction) {
// Remove the item from the data source.
setState(() {
fields.removeAt(index);
});
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(content: Text('Package removed')));
},
background: Container(
color: const Color.fromARGB(255, 210, 31, 19),
child: const Center(
child: Text(
'Remove ',
style: TextStyle(
color: white, fontWeight: FontWeight.bold, fontSize: 32),
),
)),
child: Container(
width: double.infinity,
margin: const EdgeInsets.all(5),
child: fields[index],
),
);
},
);
}
Widget _okButton() {
return ElevatedButton(
onPressed: () {
for (var element in fields) {
print(quantity);
}
Navigator.of(context).pop();
print('ok');
},
child: const Text("OK"),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(backgroundColor: blue),
body: Column(
mainAxisSize: MainAxisSize.max,
children: [
Flexible(child: _addTile()),
SizedBox(
height: MediaQuery.of(context).size.height - 200,
child: _listView()),
Flexible(child: _okButton()),
],
),
);
}
}
I think you are expecting this answer. iterate your list of texteditingcontroller and get the text stored in that controllers one by one.
for (int i = 0; i < controllers.length; i++) {
var data = controllers[i].text;
//print or add data to any other list and insert to another list and save to database
}

Conditional statement for DropdownButtonFormFields in registeration form

Still a newbie with flutter and was wondering if someone could help me with a problem I'm having. I am trying to create a registeration form with email, password, password confirmation, a county and a zip code. (County and zip code forms are the drop down button form fields) I have successfully coded all else except for the zip code drop down. I would need it to be conditional on the county selection. (In a way that if I select a specific county in cali, it would only display that selected county's zip codes and nothing else). Also if someone would know a quick fix to make the dropdown button form fields empty unless clicked on. My current adaptation on it isn't very functional, since you can just leave the option unanswered, when it's supposed to be mandatory. Thank you in advance :)
Existing code below
(I only have the string for one county zip codes) (Also deleted the irrelevant firebase related code for this post)
class RegisterPage extends StatefulWidget {
const RegisterPage({Key? key}) : super(key: key);
#override
State<RegisterPage> createState() => _RegisterPageState();
}
class _RegisterPageState extends State<RegisterPage> {
// dropdown area
_MyFormStateArea(){
selectedArea = dropdownListArea[0];
}
var selectedArea = '';
final dropdownListArea = <String>['', 'LA', 'San Francisco'...'Santa Barbara'];
// dropdown zipcode
_MyFormStateZip(){
selectedZip = dropdownListZip[0];
}
var selectedZip = '';
final dropdownListZip = <String>['', '90001', '90002', '90003',..., '91609'];
// editing Controller
final emailEditingController = new TextEditingController();
final passwordEditingController = new TextEditingController();
final confirmPasswordEditingController = new TextEditingController();
#override
Widget build(BuildContext context) {
// email field
final emailField = TextFormField(
autofocus: false,
controller: emailEditingController,
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value!.isEmpty) {
return ("Please enter email.");
}
// reg expression for email validation
if (!RegExp("^[a-zA-Z0-9+_.-]+#[a-zA-Z0-9.-]+.[a-z]")
.hasMatch(value)) {
return ("Please enter a working email.");
}
return null;
},
onSaved: (value) {
emailEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.mail_outline_outlined),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "Email",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)
),
),
);
// password field
final passwordField = TextFormField(
autofocus: false,
controller: passwordEditingController,
obscureText: true,
validator: (value) {
RegExp regex = new RegExp(r'^.{6,}$');
if (value!.isEmpty) {
return ("A password required.");
}
if(!regex.hasMatch(value)) {
return ("Please enter other password (Min. 6 characters)");
}
},
onSaved: (value) {
passwordEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.lock_outlined),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "Password",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
));
// confirm password field
final confirmPasswordField = TextFormField(
autofocus: false,
controller: confirmPasswordEditingController,
obscureText: true,
validator: (value)
{
if(confirmPasswordEditingController.text != passwordEditingController.text)
{
return "Passwords don't match";
}
return null;
},
onSaved: (value) {
confirmPasswordEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.lock_outlined),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "Password again",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)
),
),
);
// area dropdown
final areaField = DropdownButtonFormField(
value: selectedArea,
items: dropdownListArea.map((e) =>
DropdownMenuItem(value: e, child: Text(e),)).toList(),
onChanged: (String? value) {
setState(() {
if (value != null) {
selectedArea = value;
}
});
},
decoration: InputDecoration(
labelText: 'County',
prefixIcon: Icon(Icons.location_city_outlined),
contentPadding: EdgeInsets.fromLTRB(20, 10, 0, 10),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
)
);
// zip code field
final zipCodeField = DropdownButtonFormField(
value: selectedZip,
items: dropdownListZip.map((e) =>
DropdownMenuItem(value: e, child: Text(e),)).toList(),
onChanged: (String? value) {
setState(() {
if (value != null) {
selectedZip = value;
}
});
},
decoration: InputDecoration(
labelText: 'Zip Code',
prefixIcon: Icon(Icons.location_on_outlined),
contentPadding: EdgeInsets.fromLTRB(20, 10, 0, 10),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
)
);
// sign up button
final signUpButton = Material(
elevation: 5,
borderRadius: BorderRadius.circular(30),
color: Colors.white,
child: MaterialButton(
padding: EdgeInsets.fromLTRB(20, 15, 20, 15),
minWidth: MediaQuery.of(context).size.width,
onPressed: () {
signUp(emailEditingController.text, passwordEditingController.text);
},
child: Text("Sign Up", textAlign: TextAlign.center,
style: TextStyle(fontSize: 20,
color: Colors.lightBlue[900],
fontWeight: FontWeight.bold)
),
),
);
return Scaffold(
backgroundColor: Color(0xFFAED8E6),
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => FrontPage()));
},
icon: Icon(Icons.arrow_back),
color: Colors.lightBlue[900],
),
),
body: Center(
child: SingleChildScrollView(
child: Container(
color: Color(0xFFAED8E6),
child: Padding(
padding: const EdgeInsets.fromLTRB(36, 20, 36, 30),
child: Form(
key: _formKey,
child:
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(
height: 170,
child: Image.asset("assets/AR_logoBold.png",
fit: BoxFit.contain
)),
SizedBox(height: 40,),
emailField,
SizedBox(height: 25,),
passwordField,
SizedBox(height: 25,),
confirmPasswordField,
SizedBox(height: 25,),
areaField,
SizedBox(height: 25,),
zipCodeField,
SizedBox(height: 35,),
signUpButton,
SizedBox(height: 15,),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("You already own an account? "),
GestureDetector(onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => LoginPage()));
},
child: Text("Login",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
color: Colors.lightBlue[900])
),)
],
)
],
)),
),
),
),
),
);
}
}
First you should initalize the selectedArea and selectedZip with the first Entry of your List: = dropdownListZip.first and the first entry should not be an empty String
To get only zips that belong to the choosen area you need to know them. At the moment you have two independent lists.
Better you use a map like:
Map<String, List<String>> zipmap = Map('LA': ['9000','9001','9002], 'San Francisco': ['9003', '9004']);
Than you can only display zips that belong to the area quite easy.
Take a look at: Flutter Documentation for Map
Map<String, List<String>> zipmap = Map('LA': ['9000','9001','9002], 'San Francisco': ['9003', '9004']);
final areaField = DropdownButtonFormField(
value: selectedArea,
items: zipmap.keys.toList().map((e) =>
DropdownMenuItem(value: e, child: Text(e),)).toList(),
onChanged: (String? value) {
setState(() {
if (value != null) {
selectedArea = value;
}
});
},
decoration: InputDecoration(
labelText: 'County',
prefixIcon: Icon(Icons.location_city_outlined),
contentPadding: EdgeInsets.fromLTRB(20, 10, 0, 10),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
)
);
// zip code field
final zipCodeField = DropdownButtonFormField(
value: selectedZip,
items: zipmap[selectedArea].map((e) =>
DropdownMenuItem(value: e, child: Text(e),)).toList(),
onChanged: (String? value) {
setState(() {
if (value != null) {
selectedZip = value;
}
});
},
decoration: InputDecoration(
labelText: 'Zip Code',
prefixIcon: Icon(Icons.location_on_outlined),
contentPadding: EdgeInsets.fromLTRB(20, 10, 0, 10),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10)),
)
);

Flutter - Text forms not moving above the keyboard upon opening

I am fairly new to flutter and dart as a whole and i have been creating an application that interacts with firebase, this is the code for my registration screen. When clicking on a text input field the keyboard ends up blocking the forms and you cannot see what you are entering... I have tried many things such as singlechildscroll view and resizeToAvoidBottomInset and nothing seems to be affecting it. Anyone have any idea?
Register page:
class RegistrationPage extends StatefulWidget{
const RegistrationPage({Key? key}) : super(key: key);
#override
_RegistrationPageState createState() => _RegistrationPageState();
}
class _RegistrationPageState extends State<RegistrationPage> {
final _auth = FirebaseAuth.instance;
//our form key
final _formKey = GlobalKey<FormState>();
//editing controllers
final firstNameEditingController = new TextEditingController();
final lastNameEditingController = new TextEditingController();
final emailEditingController = new TextEditingController();
final passwordEditingController = new TextEditingController();
final confirmPasswordEditingController = new TextEditingController();
final cityEditingController = new TextEditingController();
#override
Widget build(BuildContext context) {
//firstname Field
final firstNameField = TextFormField(
autofocus: false,
controller: firstNameEditingController,
keyboardType: TextInputType.name,
validator: (value)
{
RegExp regEx = new RegExp(r'^.{2,}$');
if(value!.isEmpty)
{
return("First Name cannot be empty");
}
if(!regEx.hasMatch(value))
{
return("Enter valid name(min 2 characters)");
}
return null;
},
onSaved: (value) {
firstNameEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.face),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "First name",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
)
));
//Last name Field
final lastNameField = TextFormField(
autofocus: false,
controller: lastNameEditingController,
keyboardType: TextInputType.name,
validator: (value)
{
RegExp regEx = new RegExp(r'^.{2,}$');
if(value!.isEmpty)
{
return("Last Name cannot be empty");
}
return null;
},
onSaved: (value) {
lastNameEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.face),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "Last name",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
)
));
//email Field
final emailField = TextFormField(
autofocus: false,
controller: emailEditingController,
keyboardType: TextInputType.text,
validator: (value)
{
if(value!.isEmpty)
{
return("Please enter your email");
}
//email validation
if(!RegExp("^[a-zA-Z0-9+_.-]+#[a-zA-Z0-9.-]+.[a-z]").hasMatch(value))
{
return("Please enter a valid email");
}
},
onSaved: (value) {
emailEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.account_circle),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "Email address",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
)
));
//City
final cityField = TextFormField(
autofocus: false,
controller: cityEditingController,
keyboardType: TextInputType.text,
validator: (value)
{
RegExp regEx = new RegExp(r'^.{2,}$');
if(value!.isEmpty)
{
return("City cannot be empty");
}
return null;
},
onSaved: (value) {
cityEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.location_on),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "City",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
)
));
//password Field
final passwordField = TextFormField(
autofocus: false,
controller: passwordEditingController,
obscureText: true,
validator: (value)
{
RegExp regEx = new RegExp(r'^.{6,}$');
if(value!.isEmpty)
{
return("Password is required!");
}
if(!regEx.hasMatch(value))
{
return("Enter valid password(Min. 6 characters)");
}
},
onSaved: (value) {
passwordEditingController.text = value!;
},
textInputAction: TextInputAction.next,
decoration: InputDecoration(
prefixIcon: Icon(Icons.lock),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "Password",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
)
)
);
//Confirm password Field
final confirmPasswordField = TextFormField(
autofocus: false,
controller: confirmPasswordEditingController,
obscureText: true,
validator: (value)
{
if (confirmPasswordEditingController.text != passwordEditingController.text){
return "Passwords do not match";
}
return null;
},
onSaved: (value) {
confirmPasswordEditingController.text = value!;
},
textInputAction: TextInputAction.done,
decoration: InputDecoration(
prefixIcon: Icon(Icons.lock),
contentPadding: EdgeInsets.fromLTRB(20, 15, 20, 15),
hintText: "Confirm Password",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
)
)
);
final registerButton = Material(
elevation: 5,
borderRadius: BorderRadius.circular(30),
color: Colors.pink,
child: MaterialButton(
padding: EdgeInsets.fromLTRB(20, 15, 20, 15),
minWidth: MediaQuery.of(context).size.width,
onPressed: () {
signUp(emailEditingController.text, passwordEditingController.text);
},
child: Text("Register", textAlign:TextAlign.center,
style: TextStyle(
fontSize: 20, color: Colors.white, fontWeight: FontWeight.bold),
),
)
);
return Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.pink),
onPressed:(){
Navigator.of(context).pop();
},
)
),
body: Center(
child: new SingleChildScrollView(
reverse: true,
child: Container(
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(36.0),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(
height: 180,
child: Image.asset(
"assets/logo.png",
fit: BoxFit.contain,
)),
SizedBox(height: 30),
firstNameField,
SizedBox(height: 10),
lastNameField,
SizedBox(height: 10),
emailField,
SizedBox(height:10),
cityField,
SizedBox(height: 10),
passwordField,
SizedBox(height: 10),
confirmPasswordField,
SizedBox(height: 10),
registerButton,
],
),
),
)
)
)
)
);
Main.dart
Future<void> main() async { //asynchronous programming, waits for events to happen before producing a result
WidgetsFlutterBinding.ensureInitialized(); //in this case initializes the Firebase waits for a callback
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatelessWidget { //Used to build application
const MyApp({Key? key}) : super(key: key); //Anything in here runs when the app starts
ThemeData _appTheme() { //The login screen is first to load but this is not in place of main as it is bad practise
final ThemeData base = ThemeData.light(); //Will be used for implementation of light and dark theme
return base.copyWith(
colorScheme: base.colorScheme.copyWith(
primary: travelBlue,
onPrimary: Colors.white,
secondary: travelBlue,
error: travelErrorRed,
),
);
}
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp( //Runs when main.dart is executed
title: 'Login',
theme: _appTheme(),
home: LoginPage(),
);
}
}
try wrapping your column with padding
Padding(
padding: MediaQuery.of(context).viewInsets,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
// your entire form widgets here
]
)
)

How to show country code in the container

I'm working on phone number textfield, so for i got this package, and i want its CustomDecoration style, but i'm not getting it. here is my code.
Widget phonetextformfieldCustomwithouticon(context, width, controller, height) {
return Container(
width: width,
child: InternationalPhoneNumberInput(
inputDecoration: InputDecoration(
contentPadding:EdgeInsets.symmetric(vertical: 20.0, horizontal: 10.0),
},
),
);
}
updated:
I want country should have some padding, becuase it starts from the leftmost, and when i add validation in it, redner flow
Container(
width: MediaQuery.of(context).size.width * 0.9,
height: 55.0,
decoration: BoxDecoration(
border: Border.all(color: HexColor("#6e6b7b")),
color: Colors.white,
borderRadius: BorderRadius.all(
Radius.circular(10),
),
),
child: InternationalPhoneNumberInput(
inputDecoration: InputDecoration(
contentPadding:EdgeInsets.symmetric(vertical: 20.0, horizontal: 10.0),
labelText: "Phone number",
labelStyle: GoogleFonts.montserrat(color: HexColor("#6e6b7b")),
hintStyle: GoogleFonts.montserrat(),
hintText: "Enter a phone number",
border: InputBorder.none,
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
width: 0.0,
))),
// enabledBorder: InputBorder.none,
onInputChanged: (PhoneNumber number) {
print(number.phoneNumber);
},
onInputValidated: (bool value) {
print(value);
},
selectorConfig: SelectorConfig(
selectorType: PhoneInputSelectorType.DIALOG,
),
ignoreBlank: false,
autoValidateMode: AutovalidateMode.disabled,
selectorTextStyle: TextStyle(color: Colors.black),
// initialValue: number,
textFieldController: contactNo,
formatInput: false,
keyboardType: TextInputType.numberWithOptions(
signed: true, decimal: true),
inputBorder: InputBorder.none,
onSaved: (PhoneNumber number) {
print('On Saved: $number');
},
),
),
here is the output:
Try below code hope its helpful to you.refer package here and example here
create variables:
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
final TextEditingController controller = TextEditingController();
String initialCountry = 'NG';
PhoneNumber number = PhoneNumber(isoCode: 'NG');
Create one function for getting number and dispose your controller
void getPhoneNumber(String phoneNumber) async {
PhoneNumber number =
await PhoneNumber.getRegionInfoFromPhoneNumber(phoneNumber, 'US');
setState(() {
this.number = number;
});
}
#override
void dispose() {
controller?.dispose();
super.dispose();
}
Your widget:
Container(
padding: EdgeInsets.all(7),
color: Colors.blue,
child: Card(
child: Form(
key: formKey,
child: Container(
padding: EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
InternationalPhoneNumberInput(
onInputChanged: (PhoneNumber number) {
print(number.phoneNumber);
},
onInputValidated: (bool value) {
print(value);
},
selectorConfig: SelectorConfig(
selectorType: PhoneInputSelectorType.BOTTOM_SHEET,
),
ignoreBlank: false,
autoValidateMode: AutovalidateMode.disabled,
selectorTextStyle: TextStyle(color: Colors.black),
initialValue: number,
textFieldController: controller,
formatInput: false,
keyboardType: TextInputType.numberWithOptions(
signed: true, decimal: true),
inputBorder: InputBorder.none,
onSaved: (PhoneNumber number) {
print('On Saved: $number');
},
),
],
),
),
),
),
),
Your result screen on your need->
I've just written this:
InternationalPhoneNumberInput(
onInputChanged: (val) {},
inputDecoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
width: 0.0,
),
),
enabledBorder: InputBorder.none,
),
),
and it seems like these:
But I couldn't test it on android. Can you try this?

Show/Hide Passwords in Flutter's TextFormField

I'm working on a TextFormField to accept passwords. I have set the suffix icon to have IconButton child to detect on click events and to toggle the obscuretext attribute of the TextFormField. The callback function for the iconButton gets called but the TextFormField doesn't get repainted. Any ideas on how to solve this?
static Widget buildTextFormField(String id,
FormFieldValidator<String> validateField,
FormFieldSetter<String> saveField,
InputDecoration decoration,
EdgeInsetsGeometry paddingInfo,
EdgeInsetsGeometry marginInfo,
TextInputType keyboardType,
{bool obscureField:false, double width:328.0,
TextEditingController controller}
){
return Container(
padding: paddingInfo,
margin: marginInfo,
width: width,
child: TextFormField(
key: Key(id),
obscureText: obscureField,
validator: validateField,
onSaved: saveField,
keyboardType: keyboardType,
decoration: decoration,
controller: controller,
),
);
}
InputDecoration passwordDecoration = InputDecoration(
hintText: 'Password',
labelText: 'Enter your password',
suffixIcon:
IconButton(
icon: Icon(
_passwordVisible ? Icons.visibility : Icons.visibility_off,
semanticLabel: _passwordVisible ? 'hide password' : 'show password',
),
onPressed: () {
setState(() {
_passwordVisible ^= true;
//print("Icon button pressed! state: $_passwordVisible"); //Confirmed that the _passwordVisible is toggled each time the button is pressed.
});
}),
labelStyle: TextStyle(
fontFamily: 'Roboto Medium',
fontSize: 12.0,
color: Color(0x99000000),
letterSpacing: 0.4,
),
);
final passwordPaddingInfo = const EdgeInsets.only(top: 15.0, bottom:15.0,
left: 22.0, right:25.0);
this._passwordField = AdministrationComponents.
buildTextFormField('passwordField', validatePassword,
(value) => _password = value, passwordDecoration, passwordPaddingInfo,
null, null, controller:_passwordController,
obscureField: !_passwordVisible);
Try to this
bool _showPassword = false;
void _togglevisibility() {
setState(() {
_showPassword = !_showPassword;
});
}
Textform field code
child: TextFormField(
controller: _passwordController,
obscureText: !_showPassword,
cursorColor: Colors.red,
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
hintText: "Password",
border: InputBorder.none,
suffixIcon: GestureDetector(
onTap: () {
_togglevisibility();
},
child: Icon(
_showPassword ? Icons.visibility : Icons
.visibility_off, color: Colors.red,),
),
),
),
Show/Hide Passwords in Flutter's TextFormField
Step 1:
bool _obscureText = true;
Step 2:
void _toggle() {
setState(() {
_obscureText = !_obscureText;
});
}
Step 3:
TextField(
controller: password,
style: TextStyle(fontSize: 16.0),
obscureText: _obscureText,
decoration: new InputDecoration(
border: InputBorder.none,
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
errorBorder: InputBorder.none,
disabledBorder: InputBorder.none,
hintText: "Password",
suffixIcon: InkWell(
onTap: _toggle,
child: Icon(
_obscureText
? FontAwesomeIcons.eye
: FontAwesomeIcons.eyeSlash,
size: 15.0,
color: Colors.black,
),
),
),
),
Thanks #ShyjuM and # diegoveloper! I see what I was doing wrong - I was calling the buildTextFormField in the constructor of my State class and not in the build method. Moving the call to buildTextFormField inside the build method fixed it. Thanks again for all of your help!
You have some errors in your code.
Replace this :
_passwordVisible > Icons.visibility : Icons.visibility_off,
and
_passwordVisible ^= true;
By this:
_passwordVisible ? Icons.visibility : Icons.visibility_off,
and
_passwordVisible = !_passwordVisible;
This is the Password dart i use
import 'package:flutter/material.dart';
class LoginPass extends StatefulWidget {
LoginPass(this.controllerUpass);
final Function controllerUpass;
#override
_LoginPassState createState() => _LoginPassState();
}
class _LoginPassState extends State<LoginPass> {
bool _isHidden = true;
#override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.fromLTRB(0, 30, 0, 10),
child: Container(
height: 35,
child: Center(
child: Padding(
padding: const EdgeInsets.only(left: 20),
child: TextField(
obscureText: _isHidden,
onChanged: (value) {
widget.controllerUpass(value);
},
decoration: InputDecoration(
hintText: 'Password',
border: InputBorder.none,
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
errorBorder: InputBorder.none,
disabledBorder: InputBorder.none,
suffixIcon: GestureDetector(
onTap: () {
setState(() {
_isHidden = !_isHidden;
});
},
child: _isHidden
? Icon(
Icons.remove_red_eye_sharp,
color: Colors.blue,
)
: Icon(
Icons.remove_red_eye,
color: Colors.red,
),
)),
),
),
),
decoration: BoxDecoration(
boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.black26,
spreadRadius: 1,
blurRadius: 3,
offset: Offset(0, 3),
),
],
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(3)),
),
),
);
}
}
In Main call
LoginPass(controllerUpass),