I have a ListView and I want to navigate to the next page on the item click.
I need an index of the clicked item of my ListView.
I know this can be done using Controller. But I couldn't find any example.
When adding the onTap for your GestureRecognizer, (or button), your closure can capture the index passed through in the itemBuilder.
E.g.
body: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
child: Text(index.toString()),
onTap: () => Scaffold
.of(context)
.showSnackBar(SnackBar(content: Text(index.toString()))),
);
},
itemCount: 10));
This code will display a snack bar containing the index of the ListItem that you have tapped.
Once you have the index of the item, you can navigate to a new page using code provided by other answers to this question.
If you're using a ListView.builder, you can use a ListTile to add an onTap. This will make sure you have the material ripple effect.
ListView.builder(
itemBuilder: (_, i) {
return ListTile(
title: Text('$i'),
onTap: () {}, // Handle your onTap here.
);
},
)
There's an example in the Flutter documentation that's actually this very situation (navigation to next page on item click).
As others have said, use the onTap on the item in a ListView.builder. Just thought I'd post the link to the example in case someone else needed a more full explanation.
Send data to a new screen - flutter.io
...
final List<Todo> todos;
...
ListView.builder(
itemCount: todos.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(todos[index].title),
onTap: () {
//Go to the next screen with Navigator.push
},
);
},
);
Another alternative is to use InkWell. InkWell includes a nice ripple effect on tap, which GestureDetector does not have.
https://api.flutter.dev/flutter/material/InkWell-class.html
Use like this:
return Scaffold(
appBar: AppBar(title: Text("Hello World")),
body: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return InkWell(
child: Text(index.toString()),
onTap: () => Scaffold.of(context)
.showSnackBar(SnackBar(content: Text(index.toString()))),
);
},
itemCount: 10)
);
You should use the onPressed method in the item(s) you have in your ListView (or add a GestureDetector) then use Navigator, similar to the snippet below where AboutScreen is the next page you want to go to.
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => AboutScreen()),
);
}
With listview in you can useing GestureDetetor();
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return new GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => RoomDetail()));
},
child: Container(child:(Text("This is content you want")));
ListViewpage.dart
class sta extends StatefulWidget {
const sta({Key? key}) : super(key: key);
#override
State<sta> createState() => _staState();
}
var isShow = false;
var getdata = Diohelper.getdata();
class _staState extends State<sta> {
#override
Widget build(BuildContext context) {
List mwidge = [];
int index = 0;
getdata.forEach((element) {
element.index = index;
mwidge.add(ListTile(
onTap: () {
// on click listner for move to another widget or activity (android native)
Navigator.push(context,
MaterialPageRoute(builder: (context) =>
// here element passing to the detail page element contain index other details
DetailPage(element)));
},
hoverColor: Colors.amber,
title: Text(element.name.toString()),
trailing: element.isShow
? SizedBox(
width: 100,
height: 50,
child: OutlinedButton(
onPressed: () {
Scaffold.of(context).showSnackBar(
SnackBar(content: Text(element.name.toString())));
},
child: Text("Show")),
)
: Container(
width: 100,
),
));
index++;
});
return GestureDetector(
child: Center(
child: ListView(
children: [...mwidge],
),
),
);
}
}
DetailPage.dart
class DetailPage extends StatefulWidget {
productModel model;
DetailPage(this.model, {Key? key}) : super(key: key);
#override
_DetailPageState createState() => _DetailPageState();
}
class _DetailPageState extends State<DetailPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Container(
child: ListView(
children: [
Text("Name:" + widget.model.name.toString()),
Text("Category:" + widget.model.category.toString()),
Text("price:" + widget.model.price.toString())
],
),
));
}
}
FullCode:
import 'package:flutter/material.dart';
void main() =>
runApp(MaterialApp(home: Scaffold(appBar: AppBar(), body: sta())));
class sta extends StatefulWidget {
const sta({Key? key}) : super(key: key);
#override
State<sta> createState() => _staState();
}
var isShow = false;
var getdata = Diohelper.getdata();
class _staState extends State<sta> {
#override
Widget build(BuildContext context) {
List mwidge = [];
int index = 0;
getdata.forEach((element) {
element.index = index;
mwidge.add(ListTile(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => DetailPage(element)));
},
hoverColor: Colors.amber,
title: Text(element.name.toString()),
trailing: element.isShow
? SizedBox(
width: 100,
height: 50,
child: OutlinedButton(
onPressed: () {
Scaffold.of(context).showSnackBar(
SnackBar(content: Text(element.name.toString())));
},
child: Text("Show")),
)
: Container(
width: 100,
),
));
index++;
});
return GestureDetector(
child: Center(
child: ListView(
children: [...mwidge],
),
),
);
}
}
class DetailPage extends StatefulWidget {
productModel model;
DetailPage(this.model, {Key? key}) : super(key: key);
#override
_DetailPageState createState() => _DetailPageState();
}
class _DetailPageState extends State<DetailPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Container(
child: ListView(
children: [
Text("Name:" + widget.model.name.toString()),
Text("Category:" + widget.model.category.toString()),
Text("price:" + widget.model.price.toString())
],
),
));
}
}
class productModel {
String? name;
String? price;
String? category;
bool isShow = false;
int index = 0;
productModel({this.name, this.price, this.category, this.isShow = false});
productModel.fromJson(Map<String, dynamic> json) {
name = json['name'];
price = json['price'];
category = json['category'];
isShow = json['isShow'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['price'] = this.price;
data['category'] = this.category;
data['isShow'] = this.isShow;
return data;
}
}
class Diohelper {
static List<productModel> getdata() {
List<productModel> list = [];
list.add(productModel(name: "broast", price: "100", category: "chicken"));
list.add(productModel(name: "mandi", price: "100", category: "chicken"));
list.add(productModel(name: "mandi", price: "100", category: "veg"));
return list;
}
}
Dartpad or Live Code
Related
I am currently displaying my icons like this:
Widget _buildPopupDialog(BuildContext context) {
List<IconData> _iconsTable = [
Icons.feedback,
Icons.eco,
Icons.support,
Icons.call,
Icons.nature_people,
Icons.directions_bike,
];
return new AlertDialog(
content: SingleChildScrollView(
child: new Container(
child: GridView.count(
children: new List.generate(6, (int index) {
return new Positioned(
child: new DailyButton(iconData: _iconsTable[index]),
);
}),
),
),
),
However, I am wanting to get the icon data from cloud firestore. I am very new to using both flutter and firebase so I am very unsure how I would be able to do this. So far, I have tried this but iconData: Icons.iconsData obviously doesnt work:
class MyApp3 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage3(),
);
}
}
class MyHomePage3 extends StatefulWidget {
#override
_MyHomePageState3 createState() {
return _MyHomePageState3();
}
}
class _MyHomePageState3 extends State<MyHomePage3> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: _buildBody(context),
);
}
Widget _buildBody(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection('icons').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return LinearProgressIndicator();
return _buildList(context, snapshot.data.docs);
},
);
}
Widget _buildList(BuildContext context, List<DocumentSnapshot> snapshot) {
return ListView(
children: snapshot.map((data) => _buildListItem(context, data)).toList(),
);
}
Widget _buildListItem(BuildContext context, DocumentSnapshot data) {
final record3 = Record3.fromSnapshot(data);
var _iconsData = record3.name;
return Padding(
key: ValueKey(record3.name),
child: Container(
child: Card(
child: new MoodButton(
onTap: () => print("Mood"),
iconData: Icons.iconsData,
),
// trailing: Text(record3.votes.toString()),
// onTap: () => record3.reference.update({'votes': record3.votes+1})
),
),
);
}
}
class Record3 {
final String name;
final int votes;
final DocumentReference reference;
Record3.fromMap(Map<String, dynamic> map, {this.reference})
: assert(map['name'] != null),
assert(map['votes'] != null),
name = map['name'],
votes = map['votes'];
Record3.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data(), reference: snapshot.reference);
#override
String toString() => "Record<$name:$votes>";
}
Any help would be greatly appreciated!
If anyone is interested, I was able to figure it out:
Widget _buildListItem(BuildContext context, DocumentSnapshot data) {
final record3 = Record3.fromSnapshot(data);
int iconCode = record3.votes;
return Padding(
key: ValueKey(record3.name),
child: Container(
child: new Container(
child: new ListView(
scrollDirection: Axis.horizontal,
children: new List.generate(1, (int index) {
return new Positioned(
child: new MoodButton(
onTap: () => print("Mood"),
iconData: (IconData(iconCode, fontFamily: 'MaterialIcons')),
),
);
})),
),
),
);
flutter , I Want Change Qty List From StreamController ?
I want action ontap
IconButton Change data
Text(poduct[index].qty.toString()),
from StreamController
I don't want to use setState(() {});
import 'package:flutter/material.dart';
import 'dart:async';
void main() {
runApp(new MaterialApp(title: "Simple Material App", home: new MyHome()));
}
class MyHome extends StatefulWidget {
#override
MyHomeState createState() => new MyHomeState();
}
class Product {
String productName;
int qty;
Product({this.productName, this.qty});
}
class MyHomeState extends State<MyHome> {
List<Product> poduct = [Product(productName: "Nike",qty: 20),Product(productName: "Vans",qty: 30),];
var listPoduct = StreamController<List<Product>>();
#override
void initState() {
listPoduct.sink.add(poduct);
super.initState();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("test stream"),
),
body: Container(
padding: EdgeInsets.all(8.0),
child: StreamBuilder(
stream: listPoduct.stream,
builder: (context, snapshot) {
return ListView.builder(
itemCount: poduct.length,
padding: EdgeInsets.all(10),
itemBuilder: (BuildContext context, int index){
return Padding(
padding: const EdgeInsets.only(top: 20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(poduct[index].productName,style: TextStyle(fontSize: 24.0),),
new IconButton(icon: new Icon(Icons.remove), onPressed: (){
// How to Add ? listPoduct.sink ?
}),
Text(poduct[index].qty.toString()), /// <<< I Want Change Qty List Form StreamController
new IconButton(icon: new Icon(Icons.add), onPressed: (){
// How to Add ? listPoduct.sink ?
}),
Divider(),
],
),
);
},
);
}
),
));
}
}
I want action ontap
IconButton Change data
Text(poduct[index].qty.toString()),
from StreamController
I don't want to use setState(() {});
void main() {
runApp(new MaterialApp(title: "Simple Material App", home: new MyHome()));
}
class MyHome extends StatefulWidget {
#override
MyHomeState createState() => new MyHomeState();
}
class Product {
String productName;
int qty;
Product({this.productName, this.qty});
}
class MyHomeState extends State<MyHome> {
List<Product> poduct = [ // <<<<<<<< TYPO HERE
Product(productName: "Nike",qty: 20),
Product(productName: "Vans",qty: 30)];
var listPoduct = StreamController<List<Product>>();
#override
void initState() {
listPoduct.sink.add(poduct);
super.initState();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("test stream"),
),
body: Container(
padding: EdgeInsets.all(8.0),
child: StreamBuilder(
stream: listPoduct.stream,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length, // <<<<<<<< . note that listbuilder relies on snapshot not on your poduct property
padding: EdgeInsets.all(10),
itemBuilder: (BuildContext context, int index){
return Padding(
padding: const EdgeInsets.only(top: 20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(poduct[index].productName,style: TextStyle(fontSize: 24.0),), // <<<<<<<< you can also use here the snapshot.data
new IconButton(icon: new Icon(Icons.remove), onPressed: () {
_update(index, -1);
}),
Text(poduct[index].qty.toString()), // <<<<<<<< you can also use here the snapshot.data
new IconButton(icon: new Icon(Icons.add), onPressed: (){
_update(index, 1);
}),
Divider(),
],
),
);
},
);
} else {
return Container()
}
}
),
));
}
_update(int index, int difference) {
for (int i = 0; i < poduct.length; i++ ) {
if (i == index) {
poduct[i] =
Product(productName: poduct[i].productName,
qty: poduct[i].qty + difference);
}
}
listPoduct.add(poduct);
}
}
some helpful links:
StreamBuilder-class
Example
How do i create a gridview-layout with multi-select feature in Flutter, like android photo app? I was looking for an existing widget but couldn't find one.
What I have at the moment: a gridview-layout with n rows and 2 columns. The cells contain a GridTile-widget with some information and a header text. Now i want to have a functionality like in android photo app, after a long press on one of these tiles, a check-circle appears on the left top corner for all items.
Do i have to build this on my own, or is there an existing Flutter-widget which i didn't find so far?
I also don't know an existing widget, but perhaps this will help you:
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> _imageList = List();
List<int> _selectedIndexList = List();
bool _selectionMode = false;
#override
Widget build(BuildContext context) {
List<Widget> _buttons = List();
if (_selectionMode) {
_buttons.add(IconButton(
icon: Icon(Icons.delete),
onPressed: () {
_selectedIndexList.sort();
print('Delete ${_selectedIndexList.length} items! Index: ${_selectedIndexList.toString()}');
}));
}
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: _buttons,
),
body: _createBody(),
);
}
#override
void initState() {
super.initState();
_imageList.add('https://picsum.photos/800/600/?image=280');
_imageList.add('https://picsum.photos/800/600/?image=281');
_imageList.add('https://picsum.photos/800/600/?image=282');
_imageList.add('https://picsum.photos/800/600/?image=283');
_imageList.add('https://picsum.photos/800/600/?image=284');
}
void _changeSelection({bool enable, int index}) {
_selectionMode = enable;
_selectedIndexList.add(index);
if (index == -1) {
_selectedIndexList.clear();
}
}
Widget _createBody() {
return StaggeredGridView.countBuilder(
crossAxisCount: 2,
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
primary: false,
itemCount: _imageList.length,
itemBuilder: (BuildContext context, int index) {
return getGridTile(index);
},
staggeredTileBuilder: (int index) => StaggeredTile.count(1, 1),
padding: const EdgeInsets.all(4.0),
);
}
GridTile getGridTile(int index) {
if (_selectionMode) {
return GridTile(
header: GridTileBar(
leading: Icon(
_selectedIndexList.contains(index) ? Icons.check_circle_outline : Icons.radio_button_unchecked,
color: _selectedIndexList.contains(index) ? Colors.green : Colors.black,
),
),
child: GestureDetector(
child: Container(
decoration: BoxDecoration(border: Border.all(color: Colors.blue[50], width: 30.0)),
child: Image.network(
_imageList[index],
fit: BoxFit.cover,
),
),
onLongPress: () {
setState(() {
_changeSelection(enable: false, index: -1);
});
},
onTap: () {
setState(() {
if (_selectedIndexList.contains(index)) {
_selectedIndexList.remove(index);
} else {
_selectedIndexList.add(index);
}
});
},
));
} else {
return GridTile(
child: InkResponse(
child: Image.network(
_imageList[index],
fit: BoxFit.cover,
),
onLongPress: () {
setState(() {
_changeSelection(enable: true, index: index);
});
},
),
);
}
}
}
I used staggered grid view to show a grid and grid tiles with a header to have a space for the selection icon. Hope that helps!
This is a plugin from flutter package You can use this
https://pub.dev/packages/drag_select_grid_view
I want to build a checkbox with CheckboxListTile inside this widget dialog but when I tap the checkbox the checked on the checkbox doesn't change.
This is my code:
Future<Null> _showGroupDialog(BuildContext context) async {
await showDialog(
context: context,
builder: (BuildContext dialogContext) =>
Dialog(child: _buildCheckboxGroups(context)));
}
Widget _buildCheckboxGroups(BuildContext context) {
List<Widget> childrens = List.generate(_groups.length, (index) {
return CheckboxListTile(
title: Text(_groups[index].name),
value: _groups[index].checked,
onChanged: (bool val) {
setState(() {
_groups[index].checked = val;
});
},
);
});
return Container(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: childrens,
));
}
Btw, the onChange method is invoked when I tap the checkbox. Can anyone solve this?
class _MyHomePageState extends State<MyHomePage>{
//<Here you have to set default value for _groups[index].checked to false/true>
#override
Widget _buildCheckboxGroups(BuildContext context) {
List<Widget> childrens = List.generate(_groups.length, (index) {
return CheckboxListTile(
title: Text(_groups[index].name),
value: _groups[index].checked,
onChanged: (bool val) {
setState(() {
_groups[index].checked = val;
});
},
);
});}
Working Example is given below
class _MyHomePageState extends State<MyHomePage> {
bool flagWarranty=false;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: new Container(
padding: new EdgeInsets.all(20.0),
child: new Form(
key: this._formKey,
child: new ListView(
children: <Widget>[
new Checkbox(
value: flagWarranty,
onChanged: (bool value) {
setState((
) {
flagWarranty=value;
});
},
)
],),)));
}}
I have a list of stateful widgets where the user can add, remove, and interact with items in the list. Removing items from the list causes subsequent items in the list to rebuild as they shift to fill the deleted row. This results in a loss of state data for these widgets - though they should remain unaltered other than their location on the screen. I want to be able to maintain state for the remaining items in the list even as their position changes.
Below is a simplified version of my app which consists primarily of a list of StatefulWidgets. The user can add items to the list ("tasks" in my app) via the floating action button or remove them by swiping. Any item in the list can be highlighted by tapping the item, which changes the state of the background color of the item. If multiple items are highlighted in the list, and an item (other than the last item in the list) is removed, the items that shift to replace the removed item lose their state data (i.e. the background color resets to transparent). I suspect this is because _taskList rebuilds since I call setState() to update the display after a task is removed. I want to know if there is a clean way to maintain state data for the remaining tasks after a task is removed from _taskList.
void main() => runApp(new TimeTrackApp());
class TimeTrackApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Time Tracker',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new TimeTrackHome(title: 'Task List'),
);
}
}
class TimeTrackHome extends StatefulWidget {
TimeTrackHome({Key key, this.title}) : super(key: key);
final String title;
#override
_TimeTrackHomeState createState() => new _TimeTrackHomeState();
}
class _TimeTrackHomeState extends State<TimeTrackHome> {
TextEditingController _textController;
List<TaskItem> _taskList = new List<TaskItem>();
void _addTaskDialog() async {
_textController = TextEditingController();
await showDialog(
context: context,
builder: (_) => new AlertDialog(
title: new Text("Add A New Task"),
content: new TextField(
controller: _textController,
decoration: InputDecoration(
border: InputBorder.none, hintText: 'Enter the task name'),
),
actions: <Widget>[
new FlatButton(
onPressed: () => Navigator.pop(context),
child: const Text("CANCEL")),
new FlatButton(
onPressed: (() {
Navigator.pop(context);
_addTask(_textController.text);
}),
child: const Text("ADD"))
],
));
}
void _addTask(String title) {
setState(() {
// add the new task
_taskList.add(TaskItem(
name: title,
));
});
}
#override
void initState() {
_taskList = List<TaskItem>();
super.initState();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Align(
alignment: Alignment.topCenter,
child: ListView.builder(
padding: EdgeInsets.all(0.0),
itemExtent: 60.0,
itemCount: _taskList.length,
itemBuilder: (BuildContext context, int index) {
if (index < _taskList.length) {
return Dismissible(
key: ObjectKey(_taskList[index]),
onDismissed: (direction) {
if(this.mounted) {
setState(() {
_taskList.removeAt(index);
});
}
},
child: _taskList[index],
);
}
}),
),
floatingActionButton: new FloatingActionButton(
onPressed: _addTaskDialog,
tooltip: 'Click to add a new task',
child: new Icon(Icons.add),
),
);
}
}
class TaskItem extends StatefulWidget {
final String name;
TaskItem({Key key, this.name}) : super(key: key);
TaskItem.from(TaskItem other) : name = other.name;
#override
State<StatefulWidget> createState() => new _TaskState();
}
class _TaskState extends State<TaskItem> {
static final _taskFont =
const TextStyle(fontSize: 26.0, fontWeight: FontWeight.bold);
Color _color = Colors.transparent;
void _highlightTask() {
setState(() {
if(_color == Colors.transparent) {
_color = Colors.greenAccent;
}
else {
_color = Colors.transparent;
}
});
}
#override
Widget build(BuildContext context) {
return Column(children: <Widget>[
Material(
color: _color,
child: ListTile(
title: Text(
widget.name,
style: _taskFont,
textAlign: TextAlign.center,
),
onTap: () {
_highlightTask();
},
),
),
Divider(
height: 0.0,
),
]);
}
}
I ended up solving the problem by creating an intermediate class which contains a reference to the StatefulWidget and transferred over all the state variables. The State class accesses the state variables through a reference to the intermediate class. The higher level widget that contained and managed a List of the StatefulWidget now access the StatefulWidget through this intermediate class. I'm not entirely confident in the "correctness" of my solution as I haven't found any other examples of this, so I am still open to suggestions.
My intermediate class is as follows:
class TaskItemData {
// StatefulWidget reference
TaskItem widget;
Color _color = Colors.transparent;
TaskItemData({String name: "",}) {
_color = Colors.transparent;
widget = TaskItem(name: name, stateData: this,);
}
}
My StatefulWidget and its corresponding State classes are nearly unchanged, except that the state variables no longer reside in the State class. I also added a reference to the intermediate class inside my StatefulWidget which gets initialized in the constructor. Previous uses of state variables in my State class now get accessed through the reference to the intermediate class. The modified StatefulWidget and State classes is as follows:
class TaskItem extends StatefulWidget {
final String name;
// intermediate class reference
final TaskItemData stateData;
TaskItem({Key key, this.name, this.stateData}) : super(key: key);
#override
State<StatefulWidget> createState() => new _TaskItemState();
}
class _TaskItemState extends State<TaskItem> {
static final _taskFont =
const TextStyle(fontSize: 26.0, fontWeight: FontWeight.bold);
void _highlightTask() {
setState(() {
if(widget.stateData._color == Colors.transparent) {
widget.stateData._color = Colors.greenAccent;
}
else {
widget.stateData._color = Colors.transparent;
}
});
}
#override
Widget build(BuildContext context) {
return Column(children: <Widget>[
Material(
color: widget.stateData._color,
child: ListTile(
title: Text(
widget.name,
style: _taskFont,
textAlign: TextAlign.center,
),
onTap: () {
_highlightTask();
},
),
),
Divider(
height: 0.0,
),
]);
}
}
The widget containing the List of TaskItem objects has been replaced with a List of TaskItemData. The ListViewBuilder child now accesses the TaskItem widget through the intermediate class (i.e. child: _taskList[index], has changed to child: _taskList[index].widget,). It is as follows:
class _TimeTrackHomeState extends State<TimeTrackHome> {
TextEditingController _textController;
List<TaskItemData> _taskList = new List<TaskItemData>();
void _addTaskDialog() async {
_textController = TextEditingController();
await showDialog(
context: context,
builder: (_) => new AlertDialog(
title: new Text("Add A New Task"),
content: new TextField(
controller: _textController,
decoration: InputDecoration(
border: InputBorder.none, hintText: 'Enter the task name'),
),
actions: <Widget>[
new FlatButton(
onPressed: () => Navigator.pop(context),
child: const Text("CANCEL")),
new FlatButton(
onPressed: (() {
Navigator.pop(context);
_addTask(_textController.text);
}),
child: const Text("ADD"))
],
));
}
void _addTask(String title) {
setState(() {
// add the new task
_taskList.add(TaskItemData(
name: title,
));
});
}
#override
void initState() {
_taskList = List<TaskItemData>();
super.initState();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Align(
alignment: Alignment.topCenter,
child: ListView.builder(
padding: EdgeInsets.all(0.0),
itemExtent: 60.0,
itemCount: _taskList.length,
itemBuilder: (BuildContext context, int index) {
if (index < _taskList.length) {
return Dismissible(
key: ObjectKey(_taskList[index]),
onDismissed: (direction) {
if(this.mounted) {
setState(() {
_taskList.removeAt(index);
});
}
},
child: _taskList[index].widget,
);
}
}),
),
floatingActionButton: new FloatingActionButton(
onPressed: _addTaskDialog,
tooltip: 'Click to add a new task',
child: new Icon(Icons.add),
),
);
}
}