How to create contact list using Flutter? - 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),
),
),
),
),
],
],
),
),
);
}
}

Related

Update value TextField using TextEditingController

I want to update value in TextField but it become like this
And this my issue code
Widget build(BuildContext context) {
final certificatesData = Provider.of < Certificates > (context);
final cerData = certificatesData.certData;
if (cerData != null) {
print("test in");
inspectionTypeDis = cerData['inspectionType'];
_clientDataL = clientDis;
if (_clientDataL != null) {
getClientEmailL(_clientDataL);
}
}
if (emailClientDataL != null) {
_emailClientDataL = clientEmailDis;
}
return Form(
key: _formKey,
child: AlertDialog(
title: Container(
color: Color.fromARGB(255, 75, 185, 159),
child: Text('Edit',
textAlign: TextAlign.center, style: TextStyle(color: Color.fromARGB(255, 250, 251, 250))),
padding: const EdgeInsets.all(17),
margin: const EdgeInsets.all(0),
),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: < Widget > [
SizedBox(
width: 630,
height: 100,
child: ListView(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
children: < Widget > [
Container(
width: 310,
height: 20,
// color: Colors.purple[600],
child: ListTile(
title: Text('Inspection Type'),
subtitle: TextField(
controller: TextEditingController(text: inspectionTypeDis),
onChanged: (text) {
inspectionTypeDis = text;
},
decoration: const InputDecoration(
border: OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(4))),
),
),
),
),
),
]),
],
));
}
Detail Code
class EditCertificateInspection extends StatefulWidget with InputValidationMixin {
EditCertificateInspection({
Key key
}): super(key: key);
#override
_EditCertificateInspection createState() => _EditCertificateInspection();
}
class InputValidationMixin {}
class _EditCertificateInspection extends State < EditCertificateInspection > {
final navigatorKey = GlobalKey < NavigatorState > ();
final _formKey = GlobalKey < FormState > ();
Widget build(BuildContext context) {
final certificatesData = Provider.of < Certificates > (context);
final cerData = certificatesData.certData;
if (cerData != null) {
print("test in");
inspectionTypeDis = cerData['inspectionType'];
_clientDataL = clientDis;
if (_clientDataL != null) {
getClientEmailL(_clientDataL);
}
}
if (emailClientDataL != null) {
_emailClientDataL = clientEmailDis;
}
return Form(
key: _formKey,
child: AlertDialog(
title: Container(
color: Color.fromARGB(255, 75, 185, 159),
child: Text('Edit',
textAlign: TextAlign.center, style: TextStyle(color: Color.fromARGB(255, 250, 251, 250))),
padding: const EdgeInsets.all(17),
margin: const EdgeInsets.all(0),
),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: < Widget > [
SizedBox(
width: 630,
height: 100,
child: ListView(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
children: < Widget > [
Container(
width: 310,
height: 20,
child: ListTile(
title: Text('Inspection Type'),
subtitle: TextField(
controller: TextEditingController(text: inspectionTypeDis),
onChanged: (text) {
inspectionTypeDis = text;
},
decoration: const InputDecoration(
border: OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(4))),
),
),
),
),
),
]),
],
));
},
}
I will suggest creating a state variable for TextEditingController for statefulwidget and to set the text. use
TextEditingController.fromValue(TextEditingValue(text: inspectionTypeDis));
Widget structure can be
final TextEditingController controller = TextEditingController();
#override
Widget build(BuildContext context) {
return Consumer<Certificates>(builder: (context, value, child) {
final cerData = value....;
if (cerData != null) {
// your logic
controller.text = "";
}
return TextFormField(
controller: controller,
);
});
}
What you could to is to change your TextField for a TextFormField with an initialValue.
TextFormField(
initialValue: cerData['inspectionType'],
onChanged: (text) {
inspectionTypeDis = text;
},
decoration: const InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4))),
),
EDIT
Here is a fully example using a StatefulWidget using the snippet I provide above.
class Test extends StatefulWidget {
const Test({Key? key}) : super(key: key);
#override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
String _inspectionTypeDis = 'initialValue';
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
TextFormField(
initialValue: _inspectionTypeDis,
onChanged: (text) {
_inspectionTypeDis = text;
},
decoration: const InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(4))),
),
),
TextButton(
child: const Text('Print value'),
onPressed: () => print(_inspectionTypeDis)),
],
),
);
}
}

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

Validate Elevated Button in 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 : "),
),
],
),
);
}
}

Why is my TextField and List not showing when both are together in flutter

I have just started learning flutter this week!, After following a 5 hour video I decided that I would be a good Idea to work on a to do list using my knowledge. I have been having some problems with the layout order because I am used to react native and html. So I have a TextField in which a user can type the a task and then submit it so that it can appear on a list of the added tasks which is below this textfield. In the process I realized that the code is not displaying anything. The code just shows something if the TextField is removed or the list is removed but it looks that they cant be in the same page. How can I fix that problem?
My current code which doesnt display anything (main.dart)
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
List<String> _toDoItems = [];
void _addToDoItem(String task) {
if(task.length > 0) {
setState(() {
_toDoItems.add(task);
});
}
}
Widget _buildToDoItem(String toDoText) {
return ListTile(
title: Text(toDoText)
);
}
Widget _buildToDoList() {
return ListView.builder(
itemBuilder: (context, index) {
if (index < _toDoItems.length) {
return _buildToDoItem(_toDoItems[index]);
}
},
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(50),
child: AppBar(
centerTitle: true,
backgroundColor: Colors.red,
title: Text('To Do List', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold,),),
)
),
backgroundColor: Colors.white,
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
margin: EdgeInsets.all(22),
child: TextField(
autofocus: true,
onSubmitted: (val) {
_addToDoItem(val);
},
),
), _buildToDoList(),
],
),
),
);
}
}
Now the following code is the one that does display the list but not the TextField
body: _buildToDoList(),
code that does display the TextField but not the List
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
margin: EdgeInsets.all(22),
child: TextField(
autofocus: true,
onSubmitted: (val) {
_addToDoItem(val);
},
decoration: InputDecoration(
hintText: 'Add a tak here...',
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.red, width: 2),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.red, width: 1.5),
),
),
),
), // the list widget here is removed so that the text field could appear
],
),
for button next to text field:
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
margin: EdgeInsets.all(22),
child: Row(children: [
TextField(
autofocus: true,
onSubmitted: (val) {
_addToDoItem(val);
},
decoration: InputDecoration(
hintText: 'Add a tak here...',
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.red, width: 2),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.red, width: 1.5),
),
),
),
RaisedButton(
child: Text('ADD'),
onPressed: null,
),
],)
),
_buildToDoList(),
],
),
You can copy paste run full code below
You can wrap ListView with Expanded
code snippet
Widget _buildToDoList() {
return Expanded(
child: ListView.builder(
itemBuilder: (context, index) {
if (index < _toDoItems.length) {
return _buildToDoItem(_toDoItems[index]);
}
},
),
);
}
working demo
full code
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
List<String> _toDoItems = [];
void _addToDoItem(String task) {
if (task.length > 0) {
setState(() {
_toDoItems.add(task);
});
}
}
Widget _buildToDoItem(String toDoText) {
return ListTile(title: Text(toDoText));
}
Widget _buildToDoList() {
return Expanded(
child: ListView.builder(
itemBuilder: (context, index) {
if (index < _toDoItems.length) {
return _buildToDoItem(_toDoItems[index]);
}
},
),
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(50),
child: AppBar(
centerTitle: true,
backgroundColor: Colors.red,
title: Text(
'To Do List',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
)),
backgroundColor: Colors.white,
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
margin: EdgeInsets.all(22),
child: TextField(
autofocus: true,
onSubmitted: (val) {
_addToDoItem(val);
},
),
),
_buildToDoList(),
],
),
),
);
}
}
full code 2
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
List<String> _toDoItems = [];
void _addToDoItem(String task) {
if (task.length > 0) {
setState(() {
_toDoItems.add(task);
});
}
}
Widget _buildToDoItem(String toDoText) {
return ListTile(title: Text(toDoText));
}
Widget _buildToDoList() {
return Expanded(
child: ListView.builder(
itemBuilder: (context, index) {
if (index < _toDoItems.length) {
return _buildToDoItem(_toDoItems[index]);
}
},
),
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(50),
child: AppBar(
centerTitle: true,
backgroundColor: Colors.red,
title: Text(
'To Do List',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
)),
backgroundColor: Colors.white,
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
margin: EdgeInsets.all(22),
child: Row(
children: [
Expanded(
flex: 1,
child: TextField(
autofocus: true,
onSubmitted: (val) {
_addToDoItem(val);
},
decoration: InputDecoration(
hintText: 'Add a tak here...',
enabledBorder: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(12.0)),
borderSide: BorderSide(color: Colors.red, width: 2),
),
focusedBorder: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(12.0)),
borderSide:
BorderSide(color: Colors.red, width: 1.5),
),
),
),
),
Expanded(
flex: 1,
child: RaisedButton(
child: Text('ADD'),
onPressed: null,
),
),
],
)),
_buildToDoList(),
],
),
),
);
}
}

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;
});
},
)
])),
))));
}
}