Flutter two listview.builder on same page with dynamic height - list

I'm using flutter. I have two dynamic lists of item available and items unavailable.
I want to show both lists in a way that it shows complete available item list then complete unavailable item list and flutter will decide the length dynamically.
Thank you.

This is a small example should show red Container for available items and blue items for unavailable items.
List<int> unavailable;
List<int> available;
Expanded(
child: CustomScrollView(slivers: <Widget>[
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
final item = available[index];
if (index > available.length) return null;
return Container(color: Colors.red, height: 150.0); // you can add your available item here
},
childCount: available.length,
),
),
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
final item = unavailable[index];
if (index > unavailable.length) return null;
return Container(color: Colors.blue, height: 150.0); // you can add your unavailable item here
},
childCount: unavailable.length,
),
)
]));

Related

How can I make the list view scroll 360 using flutter

I have list view and I need it scroll 360ْ
I mean when last item finish the first item start.
Lets say you have list of items. You can do this.
ListView.builder(builder: (context, index) {
final actualIndex = index % items.size();
return YourWidget(items[actualIndex]);
},
itemCount: 9999999999,
);
Consider using ListWheelScrollView with looping delegate.
ListWheelScrollView.useDelegate(
itemExtent: 30,
childDelegate: ListWheelChildLoopingListDelegate(
children: List<Widget>.generate(
10, (index) => Text('$index'),
),
),
)

How to organize and show in a ListView my Map<DateTime, List<dynamic>>

I have one main map: Map<DateTime, List<dynamic>> _myEvents;. Within this variable I store many events related to days one ex: {2020-12-23 12:00:00.000Z: [{time: TimeOfDay(10:47), eventName: Navidad}]}. My events are stored by day but now I want to show the list of events from a given month (each time user change the month I update the list with the month's events).
What I'm trying:
_setMonthEvents(first,last){
_monthEvents.clear();
for(int i = first.day; i <= last.day; i++){
DateTime dayT = DateTime(first.year, first.month, i, first.hour,first.minute,first.second);
if(_myEvents[dayT] != null){
_monthEvents.addAll({'date': dayT, 'time': _myEvents[dayT][0]['time'], 'name': _myEvents[dayT][0]['name']});
}
}
setState(() {});
}
But with this approach only the last events saved keeps in the _monthEvents : {date: 2020-12-24 12:00:00.000Z, eventTime: TimeOfDay(12:30), eventName: Navidad} and if I put another it subscribes it..
This is my ListView (to show the events)
ListView.builder(
physics: AlwaysScrollableScrollPhysics(),
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: _monthEvents.length != null ? _monthEvents.length : 0,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () {
//
},
child: Dismissible(
child: ListTile(
leading: Padding(padding: EdgeInsets.only(top: 10), child: Icon(Icons.calendar_today_rounded)),
title: Text(_monthEvents.toString(), style: TextStyle(fontWeight: FontWeight.bold)), //returns the last insertion (the last event included)
subtitle: Text(
_monthEvents.length.toString(), //returns 3 *always*
style: TextStyle(fontWeight: FontWeight.w600, fontStyle: FontStyle.italic)
),
),
),);
},
);
I think I've been doing it wrong. What is the best approach to achieve my expected result?
My current result: A list with three equal elements (the last I added) and with length 3.
My expected result: A list with all the events from all days (a day can have more than one event) from a given month

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: getting switch toggle values from dynamic form or why does state change rebuild differs

I have kind of a form where I can add cards, each having 5 textfields and 2 switches. I would like to use a method to build the switch code (and the textfield code, but that is working). However, the switches refuse to show their intended state. I saw couple of similar questions. However, most were solved with a list view listing all switched/checkboxes next to one another (I have multiple cards with multiple textfields and multiple switches, each). This was close, but I don't really understand the answer (within the comments)
Actually some answers come up with the same (I guess more or less same because mine isn't working) code storing the switch state in a bool list. When debugging I can see that the values are correctly stored in the list. However, the changed value is not rendered upon state change.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class MainPage extends StatefulWidget {
#override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
var descrTECs = <TextEditingController>[];
var fixedSCs = [true]; //storing the switch values
var cards = <Card>[]; // storing the list of cards with forms
SizedBox createTextField(String placeholderStr, double fieldWidth) {
var tFieldController = TextEditingController();
switch (placeholderStr) { //switching placeholder to assign text controller to correct controller list
case "Description":
descrTECs.add(tFieldController);
break;
}
return SizedBox(width: fieldWidth, height: 25,
child: CupertinoTextField(
placeholder: placeholderStr,
controller: tFieldController,
),
);
}
SizedBox createSwitch(int pos) {
return SizedBox(width: 50, height: 25,
child: CupertinoSwitch(
value: fixedSCs[pos],
onChanged: (value) {
setState(() => fixedSCs[pos] = value); // value is stored in fixedSCs but not rendered upon rebuild
},
)
);
}
Card createCard() {
return Card(
child: Row(children: <Widget>[
Text('#p${cards.length + 1}:'),
Column(
children: <Widget>[
createSwitch(cards.length),
createTextField("Description", 70.0),
],),
],),
);
}
#override
void initState() {
super.initState();
cards.add(createCard()); // first card created upon start
}
#override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
child: SafeArea(
child: Column(
children: <Widget>[
Expanded(
child: ListView.builder( // List Builder to show all cards
itemCount: cards.length,
itemBuilder: (BuildContext context, int index) {
return cards[index];
},
),
),
RaisedButton(
child: Text('add new'),
onPressed: () => setState(() {
fixedSCs.add(true); // bool element created to create next card
cards.add(createCard());} // create next card
),
),
],
),
),);
}
}
One thing I do not understand in general: Upon rebuild after a state change cards.length} should be my number of cards, let's say 3. And when it renders the 1st card, it passes the line Text("#p${cards.length + 1}"), so it should show #p3 and not #p1. What do I get wrong here?
I meanwhile got this working with quite some logic changes.
I put the switch builder into a stateless widget
class createSwitch extends StatelessWidget {
const createSwitch({
this.label, this.margin=const EdgeInsets.all(0.0), this.width, this.height, this.value, this.onChanged});
final String label; final EdgeInsets margin; final double width; final double height; final bool value;
final Function onChanged;
#override
Widget build(BuildContext context) {
return Container(
child: Row(
children: <Widget>[
Expanded(child: Text(label)),
CupertinoSwitch(
value: value,
onChanged: (bool newValue) {onChanged(newValue);},
),
],
),
),
} }
In the parent stateful controller I created a list to store the switches' state var parameterSCs = [true]; and each time I add a card I add a value whith clicking the button onPressed: () => setState(() {parameterSCs.add(true);}
I no longer store the cards widgets as a list. Instead, I build them directly in the code within a ListView.builder
ListView.builder(
itemCount: parameterSCs.length,
itemBuilder: (BuildContext context, int index) {
return Card( ...
In my real code I have 2 switches per card, so I always add 2 elements and the ListView count is then half of the parameterSCs' length.
I tried loads of approaches, this was the only one working