Validate Elevated Button in Flutter - flutter

I'm making an app using Flutter which calculates motor vehicle tax.
It calculates it perfectly fine when I enter the cost of vehicle.
But I want to add a validation to it. When I don't enter any cost of vehicle and keeps it empty and then click the calculate button, I want it show - please enter the cost.
How do I add this validation as this is not a form.
Here is the code of that part:
TextField(
controller: costController,
decoration: const InputDecoration(labelText: "Cost of Vehicle"),
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
],
),
const SizedBox(
height: 20,
),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Theme.of(context).primaryColor,
),
onPressed: () {
setState(() {
toPrint = calc(
dropDownValue!,
int.parse(costController.text),
).toString();
});
},
child: const Text("Calculate")),
const SizedBox(
height: 20,
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: Colors.lightGreenAccent[100],
border: const Border(
bottom: BorderSide(color: Colors.grey),
)),
child: Text("Tax : $toPrint "),
),

Wrap the column with a Form widget add avalidator to the textfield
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
const appTitle = 'Form Validation Demo';
return MaterialApp(
title: appTitle,
home: Scaffold(
appBar: AppBar(
title: const Text(appTitle),
),
body: const MyCustomForm(),
),
);
}
}
// Create a Form widget.
class MyCustomForm extends StatefulWidget {
const MyCustomForm({super.key});
#override
MyCustomFormState createState() {
return MyCustomFormState();
}
}
// Create a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
// Create a global key that uniquely identifies the Form widget
// and allows validation of the form.
//
// Note: This is a GlobalKey<FormState>,
// not a GlobalKey<MyCustomFormState>.
final _formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
// Build a Form widget using the _formKey created above.
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
controller: costController,
decoration: const InputDecoration(labelText: "Cost of Vehicle"),
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
],
// The validator receives the text that the user has entered.
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Theme.of(context).primaryColor,
),
onPressed: () {
if (_formKey.currentState!.validate()) {
setState(() {
toPrint = calc(
dropDownValue!, int.parse(costController.text),
).toString();
});
}
},
child: const Text("Calculate")),
const SizedBox(
height: 20,
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: Colors.lightGreenAccent[100],
border: const Border(
bottom: BorderSide(color: Colors.grey),
)),
child: Text("Tax : $toPrint "),
),
],
),
);
}
}

Use Form Widget and Convert TextField to TextFormField like that.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class FormWidget extends StatefulWidget {
const FormWidget({Key? key}) : super(key: key);
#override
State<FormWidget> createState() => _FormWidgetState();
}
class _FormWidgetState extends State<FormWidget> {
final TextEditingController costController = TextEditingController();
final _formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
return Scaffold(
key: _formKey,
body: Column(
children: [
Form(
child: TextFormField(
validator: (value) {
if (value.isEmpty) {
return "Please enter the cost.";
}
return null;
},
controller: costController,
decoration: const InputDecoration(labelText: "Cost of Vehicle"),
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly
],
),
),
const SizedBox(
height: 20,
),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Theme.of(context).primaryColor,
),
onPressed: () {
if(_formKey.currentState.validate()){
//do your setState stuff
setState(() {
});
}
},
child: const Text("Calculate")),
const SizedBox(
height: 20,
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: Colors.lightGreenAccent[100],
border: const Border(
bottom: BorderSide(color: Colors.grey),
)),
child: Text("Tax : "),
),
],
),
);
}
}

Related

Adding values from multiple textFields

I have a list of tiles created with the 'tolist' method, each has a textField and controller.I want to get the sum of the values of all textFields into a variable and display as text.``
here is my code: `
class MyHomePage extends StatefulWidget {
const MyHomePage({
Key? key,
}) : super(key: key);
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> myList = [
'Materials',
'Labour',
'Plant and Equipment',
'Subcontractor'
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
),
body: SingleChildScrollView(
child: Column(
children: [
ExpansionTile(
maintainState: true,
title: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: const [
Text('Test Code'),
Text('sum of all here',//sum of all values from each textfield here
style: TextStyle(fontSize: 16),),
],
),
children: myList.map((cost) {
return MyListTile(cost);
}).toList(),
),
],
),
));
}
}
and MyListTile code :``
class MyListTile extends StatefulWidget {
String title;
MyListTile(this.title) : super();
#override
State<MyListTile> createState() => _MyListTileState();
}
class _MyListTileState extends State<MyListTile> {
final TextEditingController _myController = TextEditingController();
double materialCost = 0.0;
#override
Widget build(BuildContext context) {
return ListTile(
subtitle: Row(
children: [
Container(
margin: const EdgeInsets.only(top: 5, bottom: 5, right: 0, left: 0),
child: SizedBox(
height: 35,
width: 150,
child: TextField(
textAlignVertical: TextAlignVertical.center,
controller: _myController,
showCursor: true,
keyboardType: TextInputType.number,
decoration: InputDecoration(
contentPadding: const EdgeInsets.only(left: 10),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15)),
disabledBorder: const OutlineInputBorder(),
filled: true,
labelText: 'Cost sum',
labelStyle: TextStyle(color: Colors.grey[500]),
hintText: 'Enter Cost',
hintStyle: TextStyle(color: Colors.grey[500]),
suffixIcon: InkWell(
child: const Icon(
Icons.clear,
),
onTap: () {
_myController.clear();
},
),
// isCollapsed: true,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15))),
),
),
),
Container(
margin: const EdgeInsets.all(3),
padding: const EdgeInsets.all(3),
decoration: BoxDecoration(
border: Border.all(color: Colors.white10, width: 1),
borderRadius: BorderRadius.circular(12)),
child: InkWell(
onTap: () {
setState(() {
materialCost = double.parse(_myController.text);
});
},
child: const Icon(
Icons.done,
),
),
)
],
),
trailing: Column(
children: [
Container(
margin: const EdgeInsets.all(3),
padding: const EdgeInsets.all(3),
decoration: BoxDecoration(
color: Colors.white, borderRadius: BorderRadius.circular(10)),
child: Text(
materialCost.toString(),
style: const TextStyle(
// color: mainColorShade,
fontSize: 14,
fontWeight: FontWeight.bold),
),
)
],
),
title: Text(
widget.title,
),
);
;
}
}
I have tried to find a solution from allover the internet and I can not get any
example
create textControllers for each of your textfields and pass it to your textfield inside your listTile:
class MyHomePage extends StatefulWidget {
...
}
class _MyHomePageState extends State<MyHomePage> {
List<String> myList = [
'Materials',
'Labour',
'Plant and Equipment',
'Subcontractor'
];
// look here: list of controllers for your need change it for your liking
List<TextEditingController> controllers = [
TextEditingController(),
TextEditingController(),
TextEditingController(),
TextEditingController(),
];
// look here: local state to store your sum of textfields
String sum = "";
#override
void initState() {
super.initState();
// look here: this will change sum value whenever either of the textfield's value changed
for (var i = 0; i < myList.length; i++) {
controllers[i].addListener(() {
setState(() {
sum = getSum(controllers);
});
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
),
body: SingleChildScrollView(
child: Column(
children: [
ExpansionTile(
maintainState: true,
title: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Test Code'),
// look here: this is your sum text
Text(sum,style: TextStyle(fontSize: 16),),
],
),
children: [
// look here: pass the controllers to your mylistTile widgets
for (var i = 0; i < myList.length; i++)
MyListTile(
title: cost,
controller: controllers[i],
),
],
),
],
),
));
}
// if you want to change the sum result, change it here
String getSum(List<TextEditingController> controllers) {
return controllers.map((e) => "${e.text} ").toString();
}
}
Don't forget to do this in your MyListTile widget, otherwise you can't pass the controllers
class MyListTile extends StatefulWidget {
MyListTile({
required this.title,
required this.controller
}) : super();
final String title;
final TextEditingController controller;
#override
State<MyListTile> createState() => _MyListTileState();
}
Use widget.controller in your MyListTile instead of _myController
class _MyListTileState extends State<MyListTile> {
final TextEditingController _myController = TextEditingController();
double materialCost = 0.0;
#override
Widget build(BuildContext context) {
return ListTile(
subtitle: Row(
children: [
Container(
margin: const EdgeInsets.only(top: 5, bottom: 5, right: 0, left: 0),
child: SizedBox(
height: 35,
width: 150,
child: TextField(
textAlignVertical: TextAlignVertical.center,
// look here:
controller: widget.controller,
...
// rest of your code here

I can't change my widget's visibility with using mobx

I'm trying to change my second TextField's visibility in my other Auth class but I'm using mobx. I tried this version. But I can't solve my problem anyway.
If I declare my otpvisibility variable in SignInView class, I need to use setstate when i change the value of this variable in the Auth class. But i can't use setstate because I am using mobx. On the other hang if I declare otpvisibility variable in my mobx class, changes won't effect.
class SignInView extends StatelessWidget {
final BuildContext context;
SignInView({required this.context, Key? key}) : super(key: key);
TextEditingController phonecontroller = TextEditingController();
TextEditingController otpcontroller = TextEditingController();
Auth auth = Auth();
SignInViewModel svm = SignInViewModel();
#override
Widget build(BuildContext context) {
return Scaffold(
body: buildbody,
);
}
Widget get buildbody {
double screenWidth = MediaQuery.of(context).size.width;
return Observer(builder: (_) {
return SizedBox(
width: screenWidth,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
"Welcome to Whatsapp Clone, Let's begin!",
style: TextStyle(color: Colors.green, fontSize: 20),
),
const SizedBox(height: 30),
Container(
padding: const EdgeInsets.all(8),
height: 80,
child: TextField(
controller: phonecontroller,
decoration: const InputDecoration(
border: OutlineInputBorder(borderSide: BorderSide()),
),
keyboardType: TextInputType.phone,
textInputAction: TextInputAction.done,
onSubmitted: (String value) {
if (phonecontroller.text != '') {
if (svm.otpVisibility) {
svm.otpvisiblty(context);
auth.verifyotp(context, otpcontroller.text);
} else {
print('otpvisible false');
auth.loginWithPhone(
context: context, phone: phonecontroller.text);
}
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content:
Text('Please enter your phone number')));
}
},
)),
Visibility(
visible: svm.otpVisibility,
child: Container(
padding: const EdgeInsets.all(8),
height: 80,
child: TextField(
controller: otpcontroller,
decoration: const InputDecoration(
border: OutlineInputBorder(
borderSide: BorderSide(),
),
),
keyboardType: TextInputType.number,
maxLength: 6,
),
),
),
TextButton(
onPressed: () {
print(phonecontroller.text);
if (phonecontroller.text != '') {
if (svm.otpVisibility) {
svm.otpvisiblty(context);
auth.verifyotp(context, otpcontroller.text);
} else {
print('otpvisible false');
auth.loginWithPhone(
context: context, phone: phonecontroller.text);
}
} else {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Please enter your phone number')));
}
},
child: const Text(
'Verify',
style: TextStyle(color: Colors.green),
),
)
],
),
),
);
});
}
}

How to create contact list using Flutter?

I was create an dynamic contact list.
When I enter the number in add contact textfield. Automatically another text field will open. When I erase the text field the below the empty will delete automatically.
I tried several ways but id didn't work.
In my code I used text field on changed method when I enter the number it open the new contact field every number I added, I want only one contact field.
import 'package:flutter/material.dart';
class Contactadd extends StatefulWidget {
const Contactadd({Key? key}) : super(key: key);
#override
_ContactaddState createState() => _ContactaddState();
}
class _ContactaddState extends State<Contactadd> {
String dropdownValue = "Mobile";
List<Widget> cardList = [];
Widget card1() {
return Container(
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: const Color(0xFFE8DBDB),
borderRadius: BorderRadius.circular(20)),
child: Row(
children: [
const SizedBox(
width: 10,
),
dropdown(),
Container(
height: 40,
width: 200,
margin: const EdgeInsets.all(5),
child: TextField(
keyboardType: TextInputType.number,
// controller: dropdownController,
decoration: const InputDecoration(
contentPadding: EdgeInsets.only(left: 10),
border: InputBorder.none),
onChanged: (_) {
String dataa = _.toString();
if (dataa.length == 1) {
print(_ + "=================");
cardList.add(_card());
setState(() {});
} else if (dataa.length < 1) {
cardList.removeLast();
}
},
// addCardWidget,
),
),
],
),
);
}
Widget _card() {
return Container(
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: const Color(0xFFDE6868),
borderRadius: BorderRadius.circular(20)),
child: Row(
children: [
const SizedBox(
width: 10,
),
dropdown(),
Container(
height: 40,
width: 200,
margin: const EdgeInsets.all(5),
child: TextFormField(
keyboardType: TextInputType.number,
decoration: const InputDecoration(
contentPadding: EdgeInsets.only(left: 10),
border: InputBorder.none),
onChanged: (_) {
String dataa = _.toString();
if (dataa.isEmpty) {
print("true");
} else {
print("false");
}
if (dataa.length == 1 || dataa.length == 0) {
print(_ + "=================");
cardList.add(_card());
setState(() {});
} else {
cardList.removeLast();
}
})),
],
),
);
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text("Contact List"),
),
body: SingleChildScrollView(
child: Column(
children: [
card1(),
Container(
height: 430,
width: MediaQuery.of(context).size.width,
child: ListView.builder(
itemCount: cardList.length,
itemBuilder: (context, index) {
return _card();
}),
),
],
),
),
),
);
}
}
The complete code this will help you to create view like your requirment
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Contactadd(),
);
}
}
class Contactadd extends StatefulWidget {
#override
_ContactaddState createState() => _ContactaddState();
}
class _ContactaddState extends State<Contactadd> {
Map<int, dynamic> contactMap = new Map();
#override
void initState() {
contactMap.addAll(
{0: 1},
);
super.initState();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text("Contact List"),
),
body: Column(
children: [
for (var i = 0; i < contactMap.length; i++) ...[
Container(
margin: EdgeInsets.all(10),
child: TextField(
onChanged: (value) {
if (value.toString().isEmpty) {
contactMap.removeWhere((key, value) => key == i + 1);
} else {
contactMap.addAll(
{i + 1: 1},
);
}
setState(() {});
},
keyboardType: TextInputType.number,
autocorrect: true,
decoration: InputDecoration(
hintStyle: TextStyle(color: Colors.grey),
filled: true,
contentPadding: EdgeInsets.only(bottom: 0.0, left: 8.0),
fillColor: Colors.white70,
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4.0)),
borderSide:
BorderSide(color: Colors.lightBlueAccent, width: 1),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4.0)),
borderSide: BorderSide(color: Colors.lightBlueAccent),
),
),
),
),
],
],
),
),
);
}
}

How can I make a number counter app using textfield in flutter?

import 'package:flutter/material.dart';
void main() => runApp(Spent());
class Spent extends StatefulWidget {
#override
SpentState createState() => SpentState();
}
class SpentState extends State<Spent> {
final _controller = TextEditingController();
String name = '';
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Container (
padding: const EdgeInsets.all(30.0),
child: Container(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(name),
TextFormField(
textInputAction: TextInputAction.done,
controller: _controller,
decoration: InputDecoration(
fillColor: Colors.black,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(),
),
),
keyboardType: TextInputType.number
),
FlatButton(
child: Text("Enter"),
onPressed: () {
setState(() {
name = _controller.text;
});
},
)
]
)
),
)
)
)
);
}
}
Like so, I have a TextFormField. What I want my application to do is subtract the number that is currently existing using textfield. So for example if I have the number 5000, the user would type 2000 and press enter. This would make the number to 3000. How can I make this?
Here's a possible solution with basic error checking.
class SpentState extends State<Spent> {
final _controller = TextEditingController();
double value = 5000;
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Container(
padding: const EdgeInsets.all(30.0),
child: Container(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(value.toString()),
TextFormField(
textInputAction: TextInputAction.done,
controller: _controller,
decoration: InputDecoration(
fillColor: Colors.black,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(),
),
),
keyboardType: TextInputType.number),
FlatButton(
child: Text("Enter"),
onPressed: () {
//check if we can parse it
if (double.tryParse(_controller.text) == null)
return; //can't parse it
double enteredValue =
double.parse(_controller.text);
setState(() {
value -= enteredValue;
});
},
)
])),
))));
}
}

Flutter customize dropdown + TextFormField

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