View multiple images & videos - flutter - list

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

Related

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;
},
);
}

Add image reference to List and Carousel and Firebase

I am not sure how to ask this question, therefore, bare with me.
first page displays a gridview of different items, when you click on one of the items it brings you to a description page of the item.
in this description page it uses futurebuilder where future: gets firebasefirestore.instance.collection......get()
it then follows with a builder:
if (snapshot.connectionState == ConnectionState.done) {
Map<String, dynamic> documentData = snapshot.data.data();
//Add images
// imgList.clear();
imgList.add(documentData['item_images'][0]);
imgList.add(documentData['item_images'][1]);
imgList.add(documentData['item_images'][2]);
return ListView(
children: [
CarouselWithIndicatorDemo(),
],);
}
The CarouselWithIndicatorDemo() is straight from the Dart dev carousel_slider example.
Retrieving the data works perfectly fine and the carousel displays all 3 images from the imglist (seen above).
but when I go back to the previous page to click on another item, the images in the carousel do not update. I tried imgList.removeAt(0) 3 times to clear the list within the dispose:
#override
void dispose() {
imgList.removeAt(0);
imgList.removeAt(0);
imgList.removeAt(0);
super.dispose();
}
but that didn't work... how can I update this list correctly?
***************** EDIT *********************
in a dart file I am passing the following information:
Map<String, dynamic> documentData = snapshot.data.data();
List imageList = documentData['item_images'];
This is within my ListView( children:[
ImageSwipe(imageList: imageList) // instead of CarouselWithIndicatorDemo()
The other dart file:
class ImageSwipe extends StatefulWidget {
ImageSwipe({Key key, this.imageList}) : super(key: key);
final List imageList;
#override
_ImageSwipeState createState() => _ImageSwipeState();
}
class _ImageSwipeState extends State<ImageSwipe> {
int _selectedPage = 0;
#override
Widget build(BuildContext context) {
return Container(
height: 400.0,
child: Stack(
children: [
PageView(
onPageChanged: (value) {
setState(() {
_selectedPage = value;
});
},
children: [
for (var i = 0; i < widget.imageList.length; i++)
Container(
child: FadeInImage.assetNetwork(
placeholder: 'assets/missingImage.jpg',
image: widget
.imageList[i],
fit: BoxFit.cover,
),
),
],
),
Positioned(
bottom: 10.0,
left: 0.0,
right: 0.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
for (var i = 0; i < widget.imageList.length; i++)
AnimatedContainer(
duration: Duration(
milliseconds: 300,
),
curve: Curves.easeOutCubic,
margin: EdgeInsets.symmetric(horizontal: 5.0),
width: _selectedPage == i ? 36.0 : 10.0,
height: 10.0,
decoration: BoxDecoration(
color: AppColors.primaryColor,
borderRadius: BorderRadius.circular(
12.0,
),
),
)
],
),
),
]),
);
}
}
I have resolved and issue like that by using this:
final backgroundImages = ['signin_background.png','limpieza.jpg',/*'medicina.jpg',*/'plomero.jpg','profesor.jpg','veterinario.jpg'];
Then wrapping it in a animatedSwitcher like this:
Stack(
children: [
AnimatedSwitcher(
duration: Duration(milliseconds: 800),
transitionBuilder: (Widget image, Animation<double> animation) {
return FadeTransition(opacity: animation, child: image,);
},
child: Image.asset('assets/'+backgroundImages[pos],
width: MediaQuery.of(context).size.width,
key: ValueKey(pos),
fit: BoxFit.fill,
),
),
So you have to first fetch the images from your db or store them withing the app.

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!;
});
}),

Create a switch list tile with separators in flutter

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('-'),
),
);
},
);

Populate a widget with a List<Widgets> function from a pre-populated List - Flutter

The idea behind my code is to populate a Column widget with dynamic data I get from a list of objects
I use a List>> that's essentially just a list of objects.
My List :
List<List<Map<String, String>>> listCardsAll = [
[
{
"cardCate": "AMEX",
"cardDesc": "American Platinum 6",
"cardImg":
"images/AMEX/American-Express®-Green-Card-Earn-Rewards-Points.png"
}
],
[
{
"cardCate": "AMEX",
"cardDesc": "American Platinum 5",
"cardImg":
"images/AMEX/American-Express®-Green-Card-Earn-Rewards-Points.png"
}
],
];
Then I call a function within a column that returns a Widget(I want to return a List but it gives an error)
Widget:
Column(
children: <Widget>[
Row(
children: <Widget>[generateCardsALL()],
)
],
)
I Use a for-loop then in the function a make a widget with that dynamic data but it only returns one widget rather than the Collection that i was hoping for.
my Function :
Widget generateCardsALL() {
var count = 0;
for (var item in listCardsAll) {
count++;
if (count <= 2) {
return ReusableCards(
cardName: item[0]["cardDesc"],
cardLink: item[0]["cardImg"],
cardRowNum: count,
);
} else {
count = 0;
return ReusableCards(
cardName: item[0]["cardDesc"],
cardLink: item[0]["cardImg"],
cardRowNum: 3,
);
}
}
}
(The cardRowNum is only to see when its 3 cards next to each other that it can generate a new row)
This is the ReusableCards
ReusableCards:
class ReusableCards extends StatelessWidget {
final String cardLink;
final int cardRowNum;
final String cardName;
ReusableCards(
{#required this.cardLink,
#required this.cardRowNum,
#required this.cardName});
#override
Widget build(BuildContext context) {
// addToListcards(cardLink);
print("Inserted");
return (cardRowNum == 1 || cardRowNum == 2
? GestureDetector(
onDoubleTap: () {},
child: Padding(
padding: EdgeInsets.fromLTRB(0, 15, 15, 20),
child: Container(
width: MediaQuery.of(context).size.width * 0.24,
child: SizedBox(
child: Column(
children: <Widget>[
Image.asset(cardLink, fit: BoxFit.fill),
Text(cardName)
],
),
),
),
),
)
: cardRowNum == 3
? Padding(
padding: EdgeInsets.fromLTRB(0, 15, 0, 20),
child: Container(
width: MediaQuery.of(context).size.width * 0.24,
child: SizedBox(
child: Column(
children: <Widget>[
Image.asset(cardLink, fit: BoxFit.fill),
Text("" + cardRowNum.toString())
],
),
),
),
)
: SizedBox());
}
}
if I want to make it a List rather then just a widget it breaks. Can someone please help me with this dilemma
Try using map for iterating through the list and getting a list of widgets,
Example:
Column(
children: listCardsAll.map((oneCard){
return Container(
child: Text(oneCard.cardDesc)
);
}).toList(),
)
I think the problem is that inside of the function generateCardsALL. You don't return an array of Widgets, you should change to this.
List<Widget> generateCardsALL() {
var count = 0;
List<Widget> widgets;
for (var item in listCardsAll) {
count++;
if (count <= 2) {
widgets.add(ReusableCards(
cardName: item[0]["cardDesc"],
cardLink: item[0]["cardImg"],
cardRowNum: count,
));
} else {
count = 0;
widgets.add(ReusableCards(
cardName: item[0]["cardDesc"],
cardLink: item[0]["cardImg"],
cardRowNum: 3,
));
}
}
return widgets;
}