I made a widget consisting of a ListView with three TextFields per item like this.
The widget can contain N addresses as the contact has. When the contact finishes entering their addresses I want to click the save button in appBar to get all the input values from each item of ListView and put in JSON. Something like this:
[
{"Place": "Office", "Street": "Street Name", "PostalCode": "56789"},
{"Place": "Home", "Street": "Street Home", "PostalCode": "57689"},
{"Second Home": "Office", "Street": "Street 2th", "PostalCode": "45342"},
]
This is the code of the widget:
class TestPage2 extends StatefulWidget {
#override
_TestPage2State createState() => _TestPage2State();
}
class _TestPage2State extends State<TestPage2> {
List<Widget> lwidgets = [];
#override
void initState() {
lwidgets.insert(
lwidgets.length,
_Contacts(
indice: 0, onDeleteContact: (int i) => {deleteItemFromList(i)}));
lwidgets.insert(lwidgets.length, _AddElement(() => {addItemToList()}));
super.initState();
}
void addItemToList() {
setState(() {
lwidgets.insert(
lwidgets.length - 1,
_Contacts(
indice: lwidgets.length - 1,
onDeleteContact: (int i) => {deleteItemFromList(i)}));
});
}
void deleteItemFromList(int i) {
setState(() {
lwidgets.removeAt(i);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('CONTACTS'),
leading: Icon(Icons.arrow_left),
actions: <Widget>[
FlatButton(
onPressed:
() {}, // I want get all values contained of lwidgets. What do i need to do???
child: Text(
'SAVE',
style: TextStyle(color: Colors.white),
),
)
],
),
backgroundColor: Color(0xFFE5E5EA),
body: Column(
children: <Widget>[
Text('ADRESSES'),
Container(
height: 200,
child: ListView.builder(
itemCount: lwidgets.length,
itemBuilder: (BuildContext context, int index) {
return lwidgets[index];
},
physics: NeverScrollableScrollPhysics(),
),
),
],
));
}
}
This is the code of contact info widget:
class _Contacts extends StatelessWidget {
final int indice;
final Function(int) onDeleteContact;
const _Contacts({this.indice = 0, this.onDeleteContact});
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(
height: 40,
color: Colors.white,
child: Row(
children: <Widget>[
IconButton(
icon: Icon(Icons.remove_circle),
iconSize: 24,
color: Color(0xFFFF3B30),
onPressed: () {
onDeleteContact(indice);
},
),
Container(
width: 100,
child: TextField(
decoration: InputDecoration(
hintText: 'Place',
border: InputBorder.none,
),
style: TextStyle(fontFamily: 'Lekton'),
),
),
_VerticalDivider(),
Container(
width: 100,
child: TextField(
decoration: InputDecoration(
hintText: 'Street',
border: InputBorder.none,
),
style: TextStyle(fontFamily: 'Lekton'),
),
),
_VerticalDivider(),
Container(
width: 100,
child: TextField(
decoration: InputDecoration(
hintText: 'Postal Code',
border: InputBorder.none,
),
style: TextStyle(fontFamily: 'Lekton'),
),
),
],
),
),
_HorizontalDivider(),
],
);
}
I will be grateful for any help
Related
I want to create a widget like this.
This contains the Textfield, Once type something in the field, It will be sorting the list and show the results below the field. The result list shown below can also have a checkbox field to select multiple items from the result.
Is there any built-in flutter widget that can be useful for this case?
Or any other package to achieve this.
Following is the screenshot for reference.
I tried with RawAutoComplete widget.
Here is the code.
class SearchBarDemo extends StatelessWidget {
const SearchBarDemo({super.key});
static List<String> suggestons = [
"USA",
"UK",
"Uganda",
"Uruguay",
"United Arab Emirates"
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: RawAutocomplete(
optionsBuilder: (textEditingValue) {
if (textEditingValue.text == '') {
return const Iterable<String>.empty();
} else {
List<String> matches = <String>[];
matches.addAll(suggestons);
matches.retainWhere((s) {
return s
.toLowerCase()
.contains(textEditingValue.text.toLowerCase());
});
return matches;
}
},
fieldViewBuilder:
(context, textEditingController, focusNode, onFieldSubmitted) {
return TextField(
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(7),
),
hintText: 'Search',
contentPadding: EdgeInsets.symmetric(
vertical: 8,
horizontal: 4), // EdgeInsets.only(top: 8, left: 5),
prefixIcon: Container(
margin: EdgeInsets.symmetric(vertical: 8, horizontal: 4),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
border: Border(
right: BorderSide(
color: Colors.grey.shade400,
),
),
),
child: Icon(
Icons.search,
color: Colors.grey.shade400,
),
),
),
controller: textEditingController,
focusNode: focusNode,
onSubmitted: (String value) {},
);
},
onSelected: (selection) {},
optionsViewBuilder: (context, onSelected, options) {
return Material(
child: SingleChildScrollView(
child: Column(
children: options.map((opt) {
return InkWell(
onTap: () {
onSelected(opt);
},
child: Column(
children: [
Container(
height: 50,
width: 250,
alignment: Alignment.topLeft,
child: Card(
child: SizedBox(
child: ListTile(
title: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(
opt,
style: TextStyle(fontSize: 12),
),
Transform.scale(
scale: 0.8,
child: Checkbox(
value: false,
onChanged: (val) {},
),
),
],
),
),
),
),
),
],
),
);
}).toList(),
),
),
);
},
),
);
}
}
Output of the above code is:
It covers the whole screen and show the result content in center.
You can customize the filter logic. Also you may like SearchDelegate-class
class SearchBarDemo extends StatefulWidget {
const SearchBarDemo({super.key});
#override
State<SearchBarDemo> createState() => _SearchBarDemoState();
}
class _SearchBarDemoState extends State<SearchBarDemo> {
static List<String> suggestons = [
"USA",
"UK",
"Uganda",
"Uruguay",
"United Arab Emirates"
];
List<String> filterItems = [];
List<String> checkedItems = [];
late final TextEditingController controller = TextEditingController()
..addListener(() {
/// filter logic will be here
final text = controller.text.trim();
filterItems = suggestons
.where(
(element) => element.toLowerCase().startsWith(text.toLowerCase()))
.toList();
setState(() {});
});
#override
void dispose() {
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
CupertinoTextField(
controller: controller,
),
Expanded(
child: ListView.builder(
itemCount: filterItems.length,
itemBuilder: (context, index) {
final bool isChecked =
checkedItems.contains(filterItems[index]);
return CheckboxListTile(
value: isChecked,
title: Text("${filterItems[index]}"),
onChanged: (value) {
if (isChecked) {
checkedItems.remove(filterItems[index]);
} else {
checkedItems.add(filterItems[index]);
}
setState(() {});
},
);
}),
),
],
));
}
}
I'm trying to search item from ListView but I can't seem to find a way. What I want is when I type in the contact name from my contact list, then the specific contact appears on the page.
Here is my search code:
Row(
children: [
Icon(
Icons.search,
color: Color(0xff99999B),
size: 20,
),
Expanded(
child: TextField(
cursorColor: Colors.grey,
onChanged: (value) {
setState(() {
contactList = contactList.where((element) => element.contains(value)).toList();
});
},
decoration: InputDecoration(
hintText: 'Search contact...',
hintStyle: TextStyle(
color: Color(0xff99999B),
fontSize: 12
...
And my ListView code:
Container(
child: ListView.builder(
itemCount: contactList.length,
itemBuilder:(BuildContext context,index)=>
Column(
children: [
Container(
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: 250
),
child: Text(contactList[index].userName!,
...
Is there any solutions?
var contactList = ["asi", "adi", "java", "c++", "Kotlin", "Dart", "Flutter"];
var contactList2 = [];
consider create two list keep the original list and manage the secondlist for filtering .look below example
Your widget like
Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(
onPressed: () {},
icon: const Icon(Icons.add),
),
],
),
body: Column(
children: [
Container(
height: 50,
child: Row(children: [
Icon(
Icons.search,
color: Color(0xff99999B),
size: 20,
),
Expanded(
child: TextField(
cursorColor: Colors.grey,
onChanged: (value) {
setState(() {
contactList2 = contactList
.where((element) => element
.toLowerCase()
.contains(value.toLowerCase()))
.toList();
});
},
decoration: InputDecoration(
hintText: 'Search contact...',
hintStyle: TextStyle(
color: Color(0xff99999B), fontSize: 12))))
]),
),
Flexible(
child: ListView.builder(
itemCount: contactList2.length,
itemBuilder: (BuildContext context, index) => ListTile(
title: Text(
contactList2[index],
style:
TextStyle(color: Color(0xff99999B), fontSize: 25),
),
)),
)
],
),
);
SAmpleCode DArtpad live code check here
import 'package:flutter/material.dart';
//import 'package:pucon/home.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Parent(),
);
}
}
class Parent extends StatefulWidget {
#override
State<Parent> createState() => _ParentState();
}
var contactList = ["Asif", "adi", "java", "c++", "Kotlin", "Dart", "Flutter"];
var contactList2 = [];
class _ParentState extends State<Parent> {
Widget build(context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(
onPressed: () {},
icon: const Icon(Icons.add),
),
],
),
body: Column(
children: [
Container(
height: 50,
child: Row(children: [
Icon(
Icons.search,
color: Color(0xff99999B),
size: 20,
),
Expanded(
child: TextField(
cursorColor: Colors.grey,
onChanged: (value) {
setState(() {
contactList2 = contactList
.where((element) => element
.toLowerCase()
.contains(value.toLowerCase()))
.toList();
});
},
decoration: InputDecoration(
hintText: 'Search contact...',
hintStyle: TextStyle(
color: Color(0xff99999B), fontSize: 12))))
]),
),
Flexible(
child: ListView.builder(
itemCount: contactList2.length,
itemBuilder: (BuildContext context, index) => ListTile(
title: Text(
contactList2[index],
style:
TextStyle(color: Color(0xff99999B), fontSize: 25),
),
)),
)
],
),
);
}
}
Here is my code
TextField(
controller: commentController,
maxLines: 3,
selectionHeightStyle: BoxHeightStyle.tight,
decoration: new InputDecoration(
hintText: 'Write a Comment',
hintStyle: new TextStyle(
color: Colors.grey,
),
prefixIcon: InkWell(
child: Icon(Icons.camera_alt),
onTap: () {
chooseImage();
},
),
suffixIcon: InkWell(
child: Icon(
Icons.send,
),
onTap: () {
if (filePickedName == 'nofile') {
insertMethod();
commentController.clear();
_fleshScreen();
getCommentData();
} else {
upload();
commentController.clear();
_fleshScreen();
getCommentData();
}
},
)),
style: new TextStyle(
color: Colors.black,
),
),
I want to create as this box with ImageView
facebook comment multimedia box
let me give you a widget for that
class CommentBox extends StatefulWidget {
final Widget image;
final TextEditingController controller;
final BorderRadius inputRadius;
final Function onSend,onImageRemoved;
const CommentBox({Key key, this.image, this.controller, this.inputRadius, this.onSend , this.onImageRemoved }) : super(key: key);
#override
_CommentBoxState createState() => _CommentBoxState();
}
class _CommentBoxState extends State<CommentBox> {
Widget image;
#override
void initState() {
image = widget.image;
super.initState();
}
#override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Divider(
height: 1,
color: Colors.grey[300],
thickness: 1,
),
const SizedBox(height: 20),
if (image != null)
_removable(
context,
_imageView(context),
),
if(widget.controller!=null) TextFormField(
controller: widget.controller,
decoration: InputDecoration(
suffixIcon: IconButton(
icon: Icon(Icons.send,color: Theme.of(context).primaryColor,),
onPressed: widget.onSend,
),
filled: true,
border: OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: widget.inputRadius ?? BorderRadius.circular(32),
),
),
),
],
);
}
Widget _removable(BuildContext context, Widget child) {
return Stack(
alignment: Alignment.topRight,
children: [
child,
IconButton(
icon: Icon(Icons.clear),
onPressed: () {
setState(() {
image = null;
widget.onImageRemoved();
});
},
)
],
);
}
Widget _imageView(BuildContext context) {
return Padding(
padding: EdgeInsets.all(16),
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: image,
),
);
}
}
USE IT LIKE ANY WIDGET
MaterialApp(
home: Scaffold(
body: SafeArea(
child: Column(
children: [
SizedBox(height: 128,),
Spacer(),
CommentBox(
image: Image.asset(
"assets/svg/barber.svg",
height: 64,
width: 64,
),
controller: TextEditingController(),
onImageRemoved: (){
//on image removed
},
onSend: (){
//on send button pressed
},
),
],
),
),
),
)
Very new flutter. I know how to add one title to the list. I want to add 2 or more title to the list.
I defined 2 lists as list and subtitle. I think I'm making a mistake giving the index number.
I can't solve how to use lists in ListView.builder.
How can I do about this?
main.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'harf_buyuklugu.dart';
void main() => runApp(defectList());
class todolist extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: "PROGRAM",
home: Iskele(),
);
}
}
class Iskele extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Program'),
),
body: AnaEkran(),
);
}
}
class AnaEkran extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Icerik();
}
}
class Icerik extends StatefulWidget {
#override
_IcerikState createState() => _IcerikState();
}
class _IcerikState extends State<Icerik> {
TextEditingController _title_Textfield = TextEditingController();
TextEditingController _subtitleTextfield = TextEditingController();
List<String> title = [];
List<String> subtitle = [];
elemanEkle() {
setState(() {
title.add(_title_Textfield.text);
_title_Textfield.clear();
});
}
elemanCikar() {
title.clear();
_subtitleTextfield.clear();
setState(() {});
}
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(left: 25, right: 25, top: 25),
child: TextField(
maxLength: 100,
controller: _title_Textfield,
inputFormatters: [BuyukHarfTxt()],
minLines: 1,
maxLines: 3,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(60),
),
),
hintText: "Add somethings...",
labelText: "Title",
suffixIcon: IconButton(
onPressed: () => _title_Textfield.clear(),
icon: Icon(Icons.clear),
),
),
),
),
Padding(
padding: const EdgeInsets.only(left: 25, right: 25, top: 25),
child: TextField(
controller: _subtitleTextfield,
inputFormatters: [BuyukHarfTxt()],
minLines: 1,
maxLines: 3,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(60),
),
),
hintText: "Add somethings...",
labelText: "Subtitle",
suffixIcon: IconButton(
onPressed: () => _subtitleTextfield.clear(),
icon: Icon(Icons.clear),
),
),
),
),
Row(
children: [
IconButton(
onPressed: elemanEkle,
icon: Icon(Icons.save),
color: Colors.amber,
iconSize: 50,
),
IconButton(
onPressed: elemanCikar,
icon: Icon(Icons.delete_forever_rounded),
color: Colors.amber,
iconSize: 50,
),
],
),
Flexible(
child: ListView.builder(
itemCount: title.length,
itemBuilder: (context, indeksNumarasi) => ListTile(
title: Text(
'${title[indeksNumarasi]} (${subtitle[indeksNumarasi]})',
),
),
),
)
], //children
),
);
}
}
harf_buyuklugu.dart
import 'package:flutter/services.dart';
class BuyukHarfTxt extends TextInputFormatter {
#override
TextEditingValue formatEditUpdate(
TextEditingValue txtEski, TextEditingValue txtYeni) {
return txtYeni.copyWith(
text: txtYeni.text.toUpperCase(),
);
}
}
Result image
I want this
I have made some changes to your code and commented the changes, Now it works
Copy Paste this code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'harf_buyuklugu.dart';
void main() => runApp(defectList());
class todolist extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: "PROGRAM",
home: Iskele(),
);
}
}
class Iskele extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Program'),
),
body: AnaEkran(),
);
}
}
class AnaEkran extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Icerik();
}
}
class Icerik extends StatefulWidget {
#override
_IcerikState createState() => _IcerikState();
}
class _IcerikState extends State<Icerik> {
TextEditingController _title_Textfield = TextEditingController();
TextEditingController _subtitleTextfield = TextEditingController();
List<String> title = [];
List<String> subtitle = [];
elemanEkle() {
setState(() {
title.add(_title_Textfield.text);
subtitle.add(_subtitleTextfield.text); //added this line other wise index error will come
_title_Textfield.clear();
_subtitleTextfield.clear();
});
}
elemanCikar() {
title.clear();
_subtitleTextfield.clear();
setState(() {});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(left: 25, right: 25, top: 25),
child: TextField(
maxLength: 100,
controller: _title_Textfield,
// inputFormatters: [BuyukHarfTxt()],
minLines: 1,
maxLines: 3,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(60),
),
),
hintText: "Add somethings...",
labelText: "Title",
suffixIcon: IconButton(
onPressed: () => _title_Textfield.clear(),
icon: Icon(Icons.clear),
),
),
),
),
Padding(
padding: const EdgeInsets.only(left: 25, right: 25, top: 25),
child: TextField(
controller: _subtitleTextfield,
// inputFormatters: [BuyukHarfTxt()],
minLines: 1,
maxLines: 3,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(60),
),
),
hintText: "Add somethings...",
labelText: "Subtitle",
suffixIcon: IconButton(
onPressed: () => _subtitleTextfield.clear(),
icon: Icon(Icons.clear),
),
),
),
),
Row(
children: [
IconButton(
onPressed: elemanEkle,
icon: Icon(Icons.save),
color: Colors.amber,
iconSize: 50,
),
IconButton(
onPressed: () {
elemanCikar();
},
icon: Icon(Icons.delete_forever_rounded),
color: Colors.amber,
iconSize: 50,
),
],
),
Flexible(
child: ListView.builder(
itemCount: title?.length ?? 0, //when list is null nothing will shows up (some null opeartions)
itemBuilder: (context, indeksNumarasi) => ListTile(
title: new Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'${title[indeksNumarasi]})',
),
Text("${subtitle[indeksNumarasi]}"),
],
),
subtitle: Container(height: 5, color: Colors.green),
),
),
)
], //children
),
),
);
}
}
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(),
],
),
),
);
}
}