removing item from ListView.builder Flutter - list

hi may i ask how to remove an item from the ListViewBuilder,
normally it must be enough if i have an array let's call it x;
then i can remove any item that i want by using remoteAt
x.removeAt(index);
but in this case i couldn't know exactly how can i do that.
so i don't have an x array or list in this case , see please the code below.
i just declared how can i do that if i have a list and including it inside a list builder , then i can remove any widget on the screen by calling removeAt property
thanks in advance
child: Column(
children: <Widget>[BlocBuilder(
cubit: BlocProvider.of<AppBloc>(context),
builder: (BuildContext context, AppState state) {
if (state is AppUpdated && state.services.count > 0) {
return Expanded(
child: ListView.builder(
itemCount: state.services.count,
itemBuilder: (BuildContext context, int index) =>
Dismissible(
key: Key(state.service.toString()),

ListView.builder(
itemCount: state.services.count,
itemBuilder: (BuildContext context, int index) =>
Dismissible(
key: Key(state.service.toString()),
onDismissed: (direction) {
// Remove the item from the data source.
setState(() {
x.removeAt(index);
});
},
child: //your child here (maybe listivew)
),
),

Related

Flutter-Dart List-Map get item number or text where i clicked?

I wanna get a String or Map Number int if I clicked on List. I wanna forward to another Function. Like this,
I got a List,
List <String> konulistesi = <String> ["Max","Adam","Anna","Sophie","Alex",]
And if I click on the List example Adam, then it will print to number like : 1, or for Sophie print: 3,
body: SafeArea(
child:
ListView.separated(
padding: const EdgeInsets.all(8),
itemCount: konuListesi.length,
itemBuilder: (BuildContext context, int index) {
return Container(
height: 50,
color: Colors.green,
child: InkWell(child:
Center(child:
Text(konuListesi[index],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 18),),),
onTap: ()=> {
print("Number of the Position or direkt Item"),
}),
);
},
separatorBuilder: (BuildContext context, int index) => const Divider(),
),
),
You should not use the arrow function for the onTap method of the InkWell widget. print(index) will give you the index of the array. print(index + 1) will give you the countable index of the array. The index of an array starts with 0 in Dart.
And, print(konuListesi[index]) will give you the selected item:
onTap: () {
print("Number of the Position or direkt Item");
print(index);
print(konuListesi[index]);
}),

Manage items in a List with their ids

Let me explain, I have two List Views with Items. At the moment I don’t give an id to these items but I have a problem. In fact, when I remove an item from my favorites list, it doesn’t change the icon (favorite or not favorite) for the right item on the home_screen.
I want to get the place of the item in the menu screen so I can change the icon from the favorites list. I’m using the provider package.
And so I wonder if it wouldn’t be better to create an id for each item and store a List<int> and then create a List<Item> in my favorites list. Also, I can use this id to change the right icon.
But I don’t know how to use these ids to create a List and then change the right icon.
Illustrations of what I said :
Black heart = in favorite and White heart = not in favorite.
It is the wrong item which is deleting.
My code on Github ans some relevant parts of my code :
favModel.dart
class FavModel extends ChangeNotifier {
List<Item> favList = [];
List<bool> isInFav = [];
addInFavorite(title, description, index){
Item item = Item(title: title, description: description, );
favList.add(item);
isInFav[index] = true;
notifyListeners();
}
removeOfFavorite(int index, int index2){
favList.removeAt(index);
isInFav[index2] = false;
notifyListeners();
}
implement(){
isInFav.add(false);
}
}
favorite_screen.dart
class Favorite extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Favorite'),
),
body: Consumer<FavModel>(
builder: (context, favModel, child) {
return ListView.builder(
itemCount: favModel.favList.length,
itemBuilder: (context, index) {
return TextObject(favModel.favList[index].title,
favModel.favList[index].description),
Padding(
padding: const EdgeInsets.all(7.0),
child: GestureDetector(
child: Icon(
Icons.favorite,
color: Colors.red,
size: 32,
),
onTap: () {
favModel.removeOfFavorite(index, index);
}),
),
});
},
),
);
}
}
home_screen.dart
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
actions: [
IconButton(
icon: Icon(Icons.favorite_border),
onPressed: () => Navigator.push(
context,
MaterialPageRoute(
fullscreenDialog: true,
builder: (context) {
return Favorite();
},
),
),
),
],
),
body: Consumer<FavModel>(builder: (context, favModel, child) {
return ListView.builder(
shrinkWrap: false,
itemCount: itemData.length,
itemBuilder: (context, index) {
favModel.implement();
return TextObject(
itemData[index].title, itemData[index].description),
Padding(
padding: const EdgeInsets.all(7.0),
child: GestureDetector(
child: Icon(
favModel.isInFav.elementAt(index)
? Icons.favorite
: Icons.favorite_border,
color:
favModel.isInFav[index] ? Colors.red : null,
size: 32,
),
onTap: () {
favModel.isInFav[index]
? null
: Provider.of<FavModel>(context,
listen: false)
.addInFavorite(
itemData[index].title,
itemData[index].description,
index,
);
}),
);
});
}),
);
}
}
Where I want to get the index is in the favorite_screen.dart at this line favModel.removeOfFavorite(index, index);
I would suggest you to add bool isFavorite to your class Item and add an id for the class also. So you can avoid having two arrays.
And using the id will help you using some awesome methods like findWhere and removeWhere
EDIT
You can iterate the List using for
for(int i = 0;i<favList.length;i++){
if(favList[i].id == selectedItem.id){
favList[i].isSelected = true;
break;// break the loop no need to continue
}
}
notifyListeners()
Notice that now you have to pass Item instead of index

Flutter, How to get Image URL from Firestore for respective Index Items and show in a list View

I am trying to create an app which displays a dynamic FireStore List. I have made the List with a Future Builder, what I am trying to achieve is to add a Icon to every list of which the URL should be fetched from firesotre of the same documents Index. For Eg. Flipkart is a Document in FireStore it has a "images" field with the URL to Flipkart logo. I want the List View "leading" property to display this image by getting the URL from FireStore Database.
ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (_, index) {
return Card(
margin: EdgeInsets.fromLTRB(10, 2, 10, 2),
elevation: 3,
borderOnForeground: true,
child: ListTile(
title: Text(snapshot.data[index].data['title']),
subtitle: Text(snapshot.data[index].data['description']),
onTap: () => navigateToDetails(snapshot.data[index]),
),
);
});
The Code would go something like
ListTile(
leading: "Code Goes Here"
title: Text(snapshot.data[index].data['title']),
subtitle: Text(snapshot.data[index].data['description']),
Please share your valuable thoughts. I would like this to work, New to programming.
Full Code For FireStore Get Data:
class OfferScroll extends StatefulWidget {
#override
_OfferScrollState createState() => _OfferScrollState();
}
class _OfferScrollState extends State<OfferScroll> {
Future _data;
Future getOffers() async {
var firestore = Firestore.instance;
QuerySnapshot qn = await firestore.collection('Offers').getDocuments();
return qn.documents;
}
navigateToDetails (DocumentSnapshot offers) {
Navigator.push(context, MaterialPageRoute(builder: (context) =>
OfferDetails(offers: offers,)));
}
#override
void initState() {
super.initState();
_data = getOffers();
}
#override
Widget build(BuildContext context) {
return Container(
child: FutureBuilder(
future: _data,
builder: (_, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: AwesomeLoader(
loaderType: AwesomeLoader.AwesomeLoader3,
color: Colors.green[900],
),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (_, index) {
return Card(
margin: EdgeInsets.fromLTRB(10, 2, 10, 2),
elevation: 3,
borderOnForeground: true,
child: ListTile(
title: Text(snapshot.data[index].data['title']),
subtitle: Text(snapshot.data[index].data['description']),
onTap: () => navigateToDetails(snapshot.data[index]),
),
);
});
}
}),
);
}
}
When you have the URL as a string in your FireStore you can retrieve the URL with someone like this: snapshot.data[index].data['imageFieldName'] and then you can give the return of this (the URL) to a NetworkImage to display the image.

Removing items from a list on Flutter

i'm having a problem removing items from a list.
I want to remove the tapped item, but when i put the removing command i got a error:
"I/flutter ( 9410): Another exception was thrown: type '_InternalLinkedHashMap' is not a subtype of type '() => void'"
child: ListView.builder(
// padding: EdgeInsets.only(bottom: 50.0),
itemCount: _pecasList.length,
itemBuilder: (context, index) {
return ListTile(
key: Key(
DateTime.now().millisecondsSinceEpoch.toString()),
title: Text(_pecasList[index]["title"]),
onTap: _pecasList.removeAt(index)); //<<Trying to remove
}),
), ```
Replace:
onTap: _pecasList.removeAt(index)
With:
onTap: ()=>_pecasList.removeAt(index)

Cannot map a list to a widget

I have a hardcoded list that I want to map it to a list of widgets. The code below shows squiggly lines with the error The return type 'List<ItemWidget>' isn't a 'Widget', as defined by anonymous closure.dart(return_of_invalid_type_from_closure).
.................MISSING CODE....................
ListView.builder(
itemBuilder: (context, index) => items.map((item) => ItemWidget(item: item)).toList();
)
..................MISSING CODE....................
class ItemWidget extends StatelessWidget{
final Item item;
ItemWidget({this.item});
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Expanded(
child: FittedBox(
fit: BoxFit.fill,
child: Image.asset(item.iconPath)
)
),
Padding(
padding: const EdgeInsets.only(top: 15.0),
child: Text(item.name),
)
],
);
}
}
EDIT:
This is the list of items, currently I hold just an item for testing purposes.
List<Item> items = [
Item(name: 'Medicines', iconPath: '$ICON_BASE_PATH/medicines.svg'),
];
If you have any idea please let me know, thanks!
The issues is using the ListView.builder, the builder function expects you to return one Widget at a time corresponding to the index provided. Use ListView directly instead.
Example:
ListView(
children: items.map((item) => ItemWidget(item: item)).toList(),
);
Hope that helps!
If you want to use ListView.builder then you can use as following. This may helps you.
body: ListView.builder(
itemCount: items == null ? 0 : items.length,
itemBuilder: (BuildContext context, int index) {
return ItemWidget(
item: items[index],
);
},
),