Create a switch list tile with separators in flutter - list

I am trying to create a list of switch tiles in flutter which have separators between the tiles.
I've tried doing this by using ListTile.divideTiles:
ListView(
children: ListTile.divideTiles(
context: context,
tiles: [
SwitchListTile(
secondary: Icon(Icons.signal_cellular_4_bar),
title: Text(
"First Tile",
),
value: var1,
onChanged: (bool value) {
setState(
() {
var1= value;
},
);
},
),
SwitchListTile(
secondary: Icon(Icons.swap_vert),
title: Text(
"Second Tile",
),
value: var2,
onChanged: (bool value) {
setState(
() {
var2= value;
},
);
},
),
],
),
),
But when I tried running the code I got the following error:
"type '_SyncIterable<Widget>' is not a subtype of type 'List<Widget>'"
Who do I create a list of switch tiles with separator?

Please try this.
Add .toList() to the end of your ListTile.divideTiles
ListTile.divideTiles(
// all your code
// all your code
// all your code
).toList()

Why don't you try ListView.separated ?
int _selectedIndex = 0;
return ListView.separated(
//Here's your separator
separatorBuilder: (BuildContext context, int index) {
return SizedBox(
height: 10, //Whatever spacing you want.
);
},
physics: BouncingScrollPhysics(),
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: 2, //How many tiles you want
padding: EdgeInsets.all(10),
itemBuilder: (BuildContext context, int index) {
return ClipRRect( //round up the edges for nicer look
borderRadius: BorderRadius.all(Radius.circular(5)),
//And here's your tile
child: SwitchListTile(
tileColor: Colors.grey[900],
selectedTileColor: Colors.black,
selected: index == _selectedIndex,
value: ... ,
onChanged: (v) {
...
},
title: Text('Tile #' + index.toString()),
subtitle: Text('-'),
),
);
},
);

Related

How can I remove the icon when the validation is null in flutter?

I have a function that receives a list in the function parameter and I am displaying that list.
I have a validation in the Text, when it is null it shows me a message that says "no data" or otherwise it shows me the value of the list.
What I want to remove the cancel icon when it is null and only appear when I have a value to display.
Help would be greatly appreciated.
Code and Image ::
Widget SfuluilderSuggestions(List <SDM> historialMenuPrincipal){
return Container(
child:StatefulBuilder(
builder:(context,setState)
{
return Container(
child: ListView.builder(
itemCount: historialMenuPrincipal.length,
itemBuilder: (context,i)
{
contentPadding: EdgeInsets.symmetric(vertical: 12,horizontal: 16);
leading:CircleAvatar(
radius: 32,
backgroundImage: NetworkImage(
"https://2.bp.blogspot.com/-3ZzNt8ZjQk/WR9W4Fn4II/AAAAAAAJw/_inTVynhS6V75IZ-461-pda7WyrTStwCEw/s1600/A.jpg"),
);
return
ListTile(
title: Text(historialMenuPrincipal[i] == null ? "no data":historialMenuPrincipal[i].email ),
trailing: IconButton(
icon: Icon(Icons.cancel,color: Colors.black,),
onPressed: () {
setState(() {
historialMenuPrincipal.remove(historialMenuPrincipal[i]);
});
},
),
);
}
),
);
}
)
);
}
You can check if the text is null -
trailing: Text(historialMenuPrincipal[i] != null ? IconButton(
icon: Icon(Icons.cancel,color: Colors.black,),
onPressed: () {
setState(() {
historialMenuPrincipal.remove(historialMenuPrincipal[i]);
});
},
) : Padding(padding:EdgeInsets.zero),
While historialMenuPrincipal contains data, you can remove only when data is available. You can pass null on trailing.
trailing:
historialMenuPrincipal.contains(historialMenuPrincipal[i])
? IconButton(...)
: null
If you want to skip the generating ListTile, you can check on return level and provide SizedBox or better filter data while generating the list.

How can I make a list of multiple Cards with a headline in Flutter

I'm trying to create a List of containers containing a Headline and multiple cards. It should look like this in the end:
The Scaffold should contain a List of containers containing Rows of Cards and Text.
I'm not sure if that's smart so if you have a recommendation how this could be done better...
This is my code so far (without text "Text 1" segments):
body: ListView(
children: getItems(snapshot),
),//getItems(snapshot),
);
}
getItems(AsyncSnapshot<List<html.Document>> snapshot) {
List<Container> containers = [];
for(int x = 0; x<snapshot.data!.length; x++) {
containers.add(toRow(snapshot.data![x]));
}
return containers;
}
/*
Build list of containers first in a Row -> cards....
*/
toRow(html.Document document){
return Row(
children: listofcards(document),
);
}
listofcards(html.Document document) {
List<Card> cards = [];
return FutureBuilder<List<tage>>(
future: SiteParser().getData(document),
builder: (BuildContext context, AsyncSnapshot<List<tage>> document) {
for(int q = 0; q<document.data!.length; q++) {
containers.add(_buildCard(document.data![q]));
}
return cards;
},
);
}
_buildCard(tage snap) {
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
color: MyThemes().choosecardcolor(snap),
elevation: 5,
//color: _chooseColor(snap.art.toString()),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(snap.stunde),
Text(snap.klasse),
Text(snap.raum)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(snap.art),
Text(snap.lehrer),
Text(snap.mitteilung)
],
)
],
),
);
}
At the moment I can't do that, because "The return type 'List' isn't a 'Widget', as required by the closure's context. ".
It was easier thanks to #ravindra-s-patil's recommendation to use group list view.
Here is my code I've wrote.
Widget buildrevresh(AsyncSnapshot<List<html.Document>> snapshot) {
return RefreshIndicator(
onRefresh: _refresh,
child: buildData(snapshot),
);
}
Widget buildData(AsyncSnapshot<List<html.Document>> snapshot) {
List<List<tage>> days = [];
for(int x = 0; x<snapshot.data!.length; x++) {
days.add(SiteParser().getData(snapshot.data![x]));
}
return GroupListView(
itemBuilder: (context, index) {
return _buildCard(days[index.section][index.index]);
},
sectionsCount: days.length ,
groupHeaderBuilder: (BuildContext context, int section) {
return Text(
days[section].first.datum,
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600));
},
countOfItemInSection: (int section) {
return days[section].length;
},
);
}

View multiple images & videos - flutter

I have a list which contains multiple url strings like
var list = [
"https://.../1.jpg",
"https://.../2.png",
"https://.../3.mp4",
"https://.../4.avi",
];
My problem now is i want to be able to view and play this url as images and videos but don't know what plugin to use. I tried this way
int curIndex = 0;
...
Scaffold(
body: GestureDetector(
child: Container(
decoration: BoxDecoration(
color: theme.primaryVariant,
),
child: widget.url[curIndex].split(".").last == 'mp4'
? VideoPlayer(data: widget.url[curIndex])
: phView()),
onLongPress: () {
bottomSheet(
context,
imgBS({
"name": widget.url[curIndex].split("/").last,
"url": widget.url[curIndex],
}, context));
},
onVerticalDragEnd: (data) {
if (data.primaryVelocity > 200 || data.primaryVelocity < -200) {
Navigator.of(context).pop();
}
},
),
);
Widget phView() {
return PhotoViewGallery.builder(
scrollPhysics: const BouncingScrollPhysics(),
onPageChanged: (idx) {
setState(() {
curIndex = idx;
});
},
builder: (BuildContext context, int index) {
return PhotoViewGalleryPageOptions(
imageProvider: (widget.type == null ||
widget.type == 'network' ||
widget.type == '')
? NetworkImage(widget.url[index])
: FileImage(widget.url[index]),
initialScale: PhotoViewComputedScale.contained,
errorBuilder: (context, object, trace) =>
Center(child: Icon(Icons.info)),
minScale: PhotoViewComputedScale.contained,
maxScale: PhotoViewComputedScale.covered * 1.5,
);
},
itemCount: widget.url.length,
scrollDirection: Axis.horizontal,
loadingBuilder: (context, event) => Center(
child: Container(
width: 20.0,
height: 20.0,
child: CircularProgressIndicator(
value: event == null
? 0
: event.cumulativeBytesLoaded / event.expectedTotalBytes,
),
),
),
backgroundDecoration: BoxDecoration(
color: Colors.black87,
),
);
}
and for the video player i used the flick_video_player package but this isn't what i want so please is there a way to view all this and be able to swipe through each other like fb

Flutter property values of a Map all treated as strings

I have a list like this a = [{'one': 'one', 'two': null, 'three': [{'four': 'four'}]}]
I send it to a function to use it in a post request which in the body should receive a Map, so what I did was this to a[0], the problem is that I get this error The getter 'length' was called on null
I start to review and it treats all the property values as if they were Strings, even the nested list 'three': [{'four': 'four'}], I have tried to send the post in this way http.post (url, body: (recurrence [0] as Map)) but it has not worked, it always gives me the same error, even if in the body I put the properties by hand in the body: {'new property': a [0] [' tres']}, how should one act to solve this problem? Thank you very much for your help
Code:
void _ordersGet() async {
await http.get(url).then((value) {
setState(() {
orders = jsonDecode(value.body);
}
}
orders is sent to a new widget: orderList(orders)
orderList is a listView
ListView.builder(
shrinkWrap: true,
primary: false,
itemCount: orders.length,
itemBuilder: (orders, index) {
return return Card(
elevation: 5,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(orders[index]['facts']),
SizedBox(
width: 4,
),
Text('Cantidad : '),
Text(orders[index]['ITEMS'][0]['jeans']),
SizedBox(
width: 4,
),
IconButton(
onPressed: () => _reorderData(context, orders[index]),
icon: Icon(
Icons.replay_outlined,
color: Theme.of(context).accentColor,
)),
],
),
);
},
);
_reorderData is a function that make a get request, the info in shipped to ReorderModal
ReorderModal it only shows the information and has a button
void _reorderData(BuildContext ctx, order) async {
var data;
var url = 'serverAddress/${order['facts']}';
await http.get(url).then((value) {
data = jsonDecode(value.body);
data[0]['CORPORATION'] = order['corporation'];
showModalBottomSheet(
context: ctx,
builder: (_) {
return ReorderModal(data);
});
}).catchError((onError) {});
}
class ReorderModal extends StatelessWidget {
final List data;
ReorderModal(this.data);
void orderSend(orderInfo) async {
var url = 'serverAddress';
await http.post(url, body: orderInfo[0]).then((value) {
print(jsonDecode(value.body));
}).catchError((onError) {
print(onError);
});
}
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(10),
child: Column(children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: Column(
children: [
ElevatedButton(
onPressed: () {
orderSend(data);
//print(data);
},
child: Text('ONE Click'))
]),
);
}
}
when i press the ONE Click button execute the function orderSend, orderSend make a post request and the problem described above
This is the simplified code, I know it must be something very simple, but it is giving me a lot of work to solve

How can i get the radio button data with controller in flutter?

I created a widget which is sending data via an API in json format, built with controllers such as ;
final quantNumberController = TextEditingController();
And i am getting value from controller ;
String quant = quantNumberController.text;
And i store the data in json format such as ;
var data = {'quant': quant}
My current text widget container structure is like ;
Container(
width: 280,
padding: EdgeInsets.all(10.0),
child: TextField(
controller: quantNumberController,
autocorrect: true,
decoration: InputDecoration(hintText: 'Enter location'),
)
),
I would like to get this data within radio button structure. Is it possible to get the data with controller like before i did, or how should i get the data to my result json file ?
I tried like this ;
Container(
margin: EdgeInsets.fromLTRB(0, 0, 0, 10),
child: Column(
children: <Widget>[
Text('Location'),
ListTile(
title: const Text('First value'),
leading: Radio(
value: Cap.Cap33,
groupValue: _capp,
onChanged: (Capp value) {
setState(() {
_capp = value;
capp = 'Cap33';
});
},
),
),
ListTile(
title: const Text('Second value'),
leading: Radio(
value: Capp.Cap22,
groupValue: _capp,
onChanged: (Capp value) {
setState(() {
_capp = value;
capp = 'Cap22';
});
},
),
),
ListTile(
title: const Text('Third value'),
leading: Radio(
value: Capp.Cap44,
groupValue: _capp,
onChanged: (Capp value) {
setState(() {
_capp = value;
capp = 'Cap44';
});
},
),
),
],
) ,
),
Thanks.
you can define a function that takes a controller
widget myRadioButton(TextEditingController quantNumberController ){
return Radio(
value:quantNumberController.text
groupValue: _capp,
onChanged: (Capp value) {
setState(() {
_capp = value;
capp = 'Cap33';
});}
for using
Container(
child:myRadioButton (quantNumberController:quantNumberController)
)
You can use a variable like "Location Value"
Syntax -
late String LocationValue = '';
before #override
Widget build(BuildContext context)
And then assign LocationValue on radio button on change attribute
onChanged: ((value) {
LocationValue = 'cap33';
setState(() {
_value = value!;
});
}),