How to set image size in carousel slider flutter - flutter

I am new in flutter. I am using carousel slider package to show image. I want to set my image size. Now I faced the problem with my vertical image have been crop and show part center only. Here is my code:
final List<String> imgList = [
'https://images.unsplash.com/photo-1520342868574-5fa3804e551c?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=6ff92caffcdd63681a35134a6770ed3b&auto=format&fit=crop&w=1951&q=80',
'https://images.unsplash.com/photo-1522205408450-add114ad53fe?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=368f45b0888aeb0b7b08e3a1084d3ede&auto=format&fit=crop&w=1950&q=80',
'https://images.unsplash.com/photo-1519125323398-675f0ddb6308?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=94a1e718d89ca60a6337a6008341ca50&auto=format&fit=crop&w=1950&q=80',
];
final List<Widget> imageSliders = imgList.map((item) => Container(
child: Container(
margin: EdgeInsets.all(5.0),
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
child: Stack(
children: <Widget>[
Image.network(item, fit: BoxFit.cover, width: 1000.0),],
)),),
)).toList();
class CarouselWithIndicatorDemo extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _CarouselWithIndicatorState();
}
}
class _CarouselWithIndicatorState extends State<CarouselWithIndicatorDemo> {
int _current = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Carousel with indicator demo')),
body: Column(
children: [
CarouselSlider(
items: imageSliders,
options: CarouselOptions(
enlargeCenterPage: true,
aspectRatio: 2.0,
onPageChanged: (index, reason) {
setState(() {
_current = index;
});}), ),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: imgList.map((url) {
int index = imgList.indexOf(url);
return Container(
width: 8.0,height: 8.0,
margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 2.0),
decoration: BoxDecoration(
shape: BoxShape.circle,color: _current == index ? Color.fromRGBO(0, 0, 0, 0.9): Color.fromRGBO(0, 0, 0, 0.4),
), );
}).toList(),
), ]
),
);
}
}
Anyone can help me? Thanks in advance

This function can help you while scrolling left to right carousel images
Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: parentHeight * .025),
child: CarouselSlider(
height: parentHeight * .45,
enlargeCenterPage: true,
reverse: false,
autoPlay: true,
autoPlayInterval: Duration(seconds: 4),
autoPlayAnimationDuration: Duration(milliseconds: 800),
autoPlayCurve: Curves.fastOutSlowIn,
enableInfiniteScroll: true,
scrollDirection: Axis.horizontal,
onPageChanged: (index) {
setState(() {
_current = index;
});
},
items: imageTextList.map((data) {
return Builder(
builder: (BuildContext context) {
return Wrap(
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width,
margin: EdgeInsets.symmetric(
horizontal: 8.0, /*vertical: 10.0 */
),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10.0)),
),
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(10.0)),
child: Image(
image: new AssetImage(data.imageUrl),
fit: BoxFit.cover,
),
),
),
getNewTextLayout(data, parentHeight, parentWidth),
],
);
},
);
}).toList(),
),
),
],
);

Related

Can I add a CarouselSlider to a PageView.builder, no auto scroll

I have a Futurebuilder that works with a ListView.builder that displays on the screen but I wanted to add the carousel_slider package but nothing happens, the Carouselslider is set to auto scroll . I can still so it manually like a list view.
My Code:
There are just 2 elements from the Future on the screen, image and a title image.
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import '../../future_carousel.dart';
class CarouselInformation extends StatelessWidget {
CarouselInformation({Key? key}) : super(key: key);
var datasource = const FutureInformation();
getSliderDetailsEvents() async {
List futureEvents = await datasource.getSliderDetails();
return futureEvents;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sliders')),
body: SingleChildScrollView(
child: Column(
children: [
FutureBuilder(
future: getSliderDetailsEvents(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return const CircularProgressIndicator();
} else {
return Column(
children: [
const Text('Block 1'),
CarouselSlider(
options: CarouselOptions(
aspectRatio: 1.5,
viewportFraction: 1.0,
enlargeCenterPage: true,
enlargeStrategy: CenterPageEnlargeStrategy.height,
enableInfiniteScroll: false,
initialPage: 2,
autoPlay: true,
),
items: [
SizedBox(
height: 260,
width: 375,
child: Expanded(
child: PageView.builder(
scrollDirection: Axis.horizontal,
itemCount: snapshot.data.length,
itemBuilder:
(BuildContext context, int index) {
return Container(
margin: const EdgeInsets.all(5.0),
child: ClipRRect(
borderRadius: const BorderRadius.all(
Radius.circular(5.0)),
child: Stack(
children: [
Image.network(
snapshot.data[index].image,
fit: BoxFit.cover),
Positioned(
bottom: 0.0,
left: 0.0,
right: 0.0,
child: Container(
decoration:
const BoxDecoration(
gradient: LinearGradient(
colors: [
Color.fromARGB(
200, 0, 0, 0),
Color.fromARGB(
0, 0, 0, 0)
],
begin: Alignment
.bottomCenter,
end: Alignment.topCenter,
),
),
padding: const EdgeInsets
.symmetric(
vertical: 10.0,
horizontal: 20.0),
child: Text(
snapshot.data[index].title,
style: const TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight:
FontWeight.bold,
),
),
),
),
],
),
),
);
},
),
),
),
]),
],
);
}
}),
],
),
),
);
}
}
Result of the code above:
I want to achieve the same effect as the bottom Widget as on this clip but the images on that clip which is working are hardcoded not from a Future.
https://www.screencast.com/t/ouWL8AkSuI

Animated Smooth Indicator not Working ? FLUTTER

I'm building an app with a PageView Widget and I wanted to add AnimatedSmoothIndicator.
I added a CarouseLslider to the pageView to make it auto run
but it never changes .. I tried a lot of methods but none of them work
can anyone help..
class FoodPageBody extends StatefulWidget {
const FoodPageBody({Key? key}) : super(key: key);
#override
State<FoodPageBody> createState() => _FoodPageBodyState();
}
class _FoodPageBodyState extends State<FoodPageBody> {
PageController pageController = PageController(viewportFraction: 1);
int activeIndex = 0;
//------------------------------------------------------------------------------
#override
Widget build(BuildContext context) {
return SizedBox(
height: 340,
child: PageView.builder(
controller: pageController,
itemCount: 5,
itemBuilder: (context, position) {
return _bulidPageItem(position);
}),
);
}
Widget _bulidPageItem(int index) {
//------------------------------------------------------------------------------
// Slide image 🚩
return Column(
children: [
CarouselSlider(
options: CarouselOptions(
onPageChanged: (index, reason) {
setState(() {
activeIndex = index;
});
},
enlargeStrategy: CenterPageEnlargeStrategy.height,
enableInfiniteScroll: true,
enlargeCenterPage: true,
autoPlayCurve: Curves.ease,
autoPlay: true,
autoPlayInterval: const Duration(seconds: 5),
height: 320,
),
items: [
Stack(
alignment: Alignment.topCenter,
children: [
Container(
margin: const EdgeInsets.only(left: 5, right: 5),
height: 220,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: index.isEven
? const Color(0xFFffd28d)
: const Color(0xFF89dad0),
image: const DecorationImage(
image: AssetImage('images/chineseFood.jpg'),
fit: BoxFit.cover),
),
),
//------------------------------------------------------------------------------
// Slide Information 🚩
Align(
alignment: Alignment.bottomCenter,
child: Container(
margin:
const EdgeInsets.only(left: 20, right: 20, bottom: 15),
height: 130,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.3),
blurRadius: 6,
spreadRadius: 0.7,
offset: const Offset(1, 4))
],
borderRadius: BorderRadius.circular(25),
color: Colors.white,
),
//------------------------------------------------
// Slider title
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const BigText(
text: 'Chinese side',
),
//----------------------------------------------
// Slider Rating
const SizedBox(height: 10),
Row(
children: [
Wrap(
children: List.generate(
5,
(index) => const Icon(Icons.star,
color: AppColor.mainColor, size: 12),
),
),
const SizedBox(width: 10),
SmallText(text: 4.5.toString()),
const SizedBox(width: 10),
const SmallText(text: '1287 comments'),
],
),
const SizedBox(height: 20),
//----------------------------------------------
// Slider Icons
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: const [
SliderIcons(
color: AppColor.iconColor1,
text: 'Normal',
icon: Icons.circle),
SliderIcons(
color: AppColor.mainColor,
text: '1.7km',
icon: Icons.location_pin),
SliderIcons(
color: AppColor.iconColor2,
text: '32min',
icon: FontAwesomeIcons.clock),
],
),
],
),
),
),
),
],
),
],
),
//------------------------------------------------------------------------------
// Slider Dots 🚩
AnimatedSmoothIndicator(
activeIndex: activeIndex,
count: 5,
effect: const WormEffect(),
)
],
);
}
}
The issue is here, the CarouselSlider's items is just one of this snippet. Therefore, onPageChanged active index is always getting 0.
To have five items, we need to generate item here.
I think pageView is not necessary for this case.
#override
Widget build(BuildContext context) {
return SizedBox(height: 340, child: _bulidPageItem());
}
Widget _bulidPageItem() {
//------------------------------------------------------------------------------
// Slide image 🚩
return Column(
children: [
CarouselSlider(
carouselController: carouselController,
options: CarouselOptions(
onPageChanged: (index1, reason) {
debugPrint("on Page changed $index1");
setState(() {
activeIndex = index1;
});
},
),
items: List.generate(
5,
(index) => Stack(

How i can set custom animation between slide in CarouselSlider flutter

I have created an image slider using CarouselSlider, I want to set animation when the page change but when the page change it will not reflect to the dot indicator
slider and dot position
here is the full code of my slider
final RxInt _current = 0.obs;
PageController pageViewController = PageController();
final CarouselController _controller = CarouselController();
#override
void initState() {
super.initState();
WidgetsBinding.instance!.addPostFrameCallback((_) {
for (var imageUrl in images) {
precacheImage(NetworkImage(imageUrl), context);
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Slider demo')),
body: Obx(
() => Stack(
children: [
Positioned(
bottom: 40.0,
left: 0.0,
right: 0.0,
child: Padding(
padding: const EdgeInsets.only(top: 15),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedSmoothIndicator(
activeIndex: _current.value,
count: images.length,
effect: ExpandingDotsEffect(
radius: 10,
dotWidth: 10,
dotHeight: 10,
activeDotColor: Colors.green,
expansionFactor: 4,
dotColor: Colors.green.withOpacity(0.17),
), // your preferred effect
onDotClicked: (index) {
pageViewController.animateToPage(
index,
duration: const Duration(milliseconds: 500),
curve: Curves.ease,
);
},
)
],
),
),
),
Padding(
padding: const EdgeInsets.only(top: 50),
child: Expanded(
child: Container(
child: CarouselSlider.builder(
itemCount: images.length,
carouselController: _controller,
options: CarouselOptions(
autoPlay: true,
aspectRatio: 14 / 8.5,
viewportFraction: 0.8,
enlargeCenterPage: true,
autoPlayAnimationDuration: const Duration(seconds: 2),
autoPlayInterval: const Duration(seconds: 4),
autoPlayCurve: Curves.easeInOutSine,
onPageChanged: (index, reason) {
_current.value = index;
},
scrollPhysics: const BouncingScrollPhysics(),
),
itemBuilder: (context, index, realIdx) {
return index == _current.value
? ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(5.0)),
child: Stack(
children: [
Image.network(
images[index],
fit: BoxFit.cover,
width: 1000,
height: 170,
)
],
),
)
: Padding(
padding: const EdgeInsets.only(top: 25),
child: Container(
child: ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(5.0)),
child: Stack(
children: [
Image.network(
images[index],
fit: BoxFit.cover,
width: 1000,
height: 172,
)
],
),
),
),
);
},
)),
),
),
],
),
),
);
}

How to Implement a manual carousel slider in Flutter?

I am creating a product image carousel which contains pictures of shoes where the user can change the image to be viewed by selecting a different color.
The user can manually scroll through the images without an issue,however when I try to manually change the displayed carousel image, only the indicator changes, but the image remains on the first image.
class DetailsPage extends StatefulWidget {
final String url;
final String title;
final int index;
DetailsPage({this.url, this.title, this.index});
#override
_DetailsPageState createState() => _DetailsPageState();
}
class _DetailsPageState extends State<DetailsPage> {
List imgList = [
'https://i.dlpng.com/static/png/6838599_preview.png',
'https://www.manelsanchez.pt/uploads/media/images/nike-air-force-max-ii-blue-fury-18.jpg',
'https://www.vippng.com/png/detail/30-302339_nike-women-running-shoes-png-image-transparent-background.png',
];
int _current = 0;
String selected = "grey";
List<T> map<T>(List list, Function handler) {
List<T> result = [];
for (var i = 0; i < list.length; i++) {
result.add(handler(i, list[i]));
}
return result;
}
final CarouselController _buttonCarouselController = CarouselController();
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).canvasColor,
appBar: AppBar(
title: Center(
child: Text(
'Details',
style: TextStyle(
fontFamily: 'OpenSansLight',
fontSize: 26,
color: Theme.of(context).textTheme.headline1.color),
),
),
body: ListView(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
//Carousel Slider
CarouselSlider.builder(
options: CarouselOptions(
carouselController: _buttonCarouselController,
height: 200.0,
enlargeCenterPage: true,
enlargeStrategy: CenterPageEnlargeStrategy.height,
initialPage: 0,
reverse: false,
autoPlay: false,
enableInfiniteScroll: false,
scrollDirection: Axis.horizontal,
onPageChanged: (index, fn) {
setState(() {
_current = index;
});
}),
itemCount: imgList.length,
itemBuilder: (BuildContext context, int index) =>
Builder(builder: (BuildContext context) {
return Image.network(
imgList[index],
fit: BoxFit.contain,
);
}),
),
SizedBox(height: 10),
//Indicator to show current index of images
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: map<Widget>(imgList, (index, url) {
return Container(
width: 30.0,
height: 2.0,
margin: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 4.0),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(10.0),
color: _current == index
? Colors.deepPurple
: Colors.grey,
),
);
}),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 30,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Color',
style: TextStyle(
fontFamily: 'OpenSansLight',
fontSize: 24)),
],
),
),
),
Flexible(
fit: FlexFit.loose,
child: Container(
width: width,
height: 120,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: imgList.length,
itemBuilder: (BuildContext context, int index) {
//Color selector from images to manually control the carousel
return GestureDetector(
onTap: () {
setState(() {
selected = imgList[index];
_current = index;
_buttonCarouselController
.animateToPage(_current);
print('I HAVE SELECTED $selected');
});
},
child: ColorTicker(
image: imgList[index],
selected: selected == imgList[index],
),
);
},
),
),
),
],
),
);
Color Ticker Widget
class ColorTicker extends StatelessWidget {
final image;
final bool selected;
ColorTicker({this.image, this.selected});
#override
Widget build(BuildContext context) {
print(selected);
return Container(
margin: EdgeInsets.all(5),
width: 100,
height: 100,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.scaleDown, image: NetworkImage(image)),
shape: BoxShape.circle,
border: selected
? Border.all(color: Colors.deepPurple, width: 3)
: Border.all(color: Colors.grey[500])),
// color: color.withOpacity(0.7)),
child: selected
? Center(child: Icon(Icons.check, size: 40, color: Colors.deepPurple))
: Container(),
);
}
}
I've tried all I could from the documentation : https://pub.dev/packages/carousel_slider/example
But I kept getting an error
Unhandled Exception: NoSuchMethodError: The getter 'options' was called on null
I am almost embarassed at my mistake.
In the configuration of the slider, I placed the controller in the wrong place.
I put the controller inside the Carousel options instead of under CarouselSlider
CarouselSlider(
carouselController: _buttonCarouselController,
options: CarouselOptions(
... ))
It now works :)

How to use carousel_slider with assets in flutter

I have been trying to use the carousel_slider tool in flutter but it does not seem to load up my asset images. I works when I change it to network images though. Could someone please tell me why. the code is below:
import 'package:flutter/material.dart';
import 'package:carousel_pro/carousel_pro.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:mindfulness/components/anxiety2.dart';
final List<String> imgList = [
'assets/images/anxiety1.png',
'assets/images/anxiety2.png'
];
class anxiety extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
backgroundColor: Colors.pink[200],
),
body: Builder(
builder: (context) {
final double height = MediaQuery.of(context).size.height;
return CarouselSlider(
options: CarouselOptions(
height: height,
viewportFraction: 1.0,
enlargeCenterPage: false,
// autoPlay: false,
),
items: imgList.map((item) => Container(
child: Center(
child: Image.asset(item, fit: BoxFit.cover, height: height,)
),
)).toList(),
);
},
),
);
}
}
What I found was that there was no need for a builder, the only parameters necessary were a list and an options parameter, so you can use the list to supply the assets one by one
import 'package:flutter/material.dart';
import 'package:carousel_pro/carousel_pro.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:mindfulness/components/anxiety2.dart';
class anxiety extends StatelessWidget {
#override
Widget build(BuildContext context) {
return CarouselSlider(
options: CarouselOptions(
autoPlay: true,
aspectRatio: 2.0,
enlargeCenterPage: true,
),
items: [
Image.asset('assets/images/anxiety1.png'),
Image.asset('assets/images/anxiety2.png'),
],
);
}
}
How about you change your code to this:
import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';
class ImageCarouselExample extends StatefulWidget {
const ImageCarouselExample({ Key? key }) : super(key: key);
#override
_ImageCarouselExampleState createState() => _ImageCarouselExampleState();
}
class _ImageCarouselExampleState extends State<ImageCarouselExample> {
int _currentIndex = 0;
late CarouselSlider carouselSlider;
List imageList = [
'assets/images/loginimage.jpeg',
'assets/images/smartanalytics.png',
'assets/images/smartbiometrics.png',
'assets/images/smarthmis.png',
];
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
CarouselSlider(
options: CarouselOptions(
height: 250.0,
initialPage: 0,
autoPlay: true,
reverse: false,
enlargeCenterPage: true,
enableInfiniteScroll: true,
scrollDirection: Axis.horizontal,
autoPlayInterval: Duration(seconds: 2),
autoPlayAnimationDuration: Duration(milliseconds: 2000),
onPageChanged: (index, reason) => _currentIndex = index,
// pauseAutoPlayOnTouch: Duration(seconds: 10),
// scrollDirection: Axis.horizontal,
),
items: imageList
.map(
(item) => Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
margin: EdgeInsets.only(
top: 10.0,
bottom: 20.0,
),
elevation: 6.0,
shadowColor: Colors.redAccent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
child: ClipRRect(
borderRadius: BorderRadius.all(
Radius.circular(10.0),
),
child: Image.asset(
item,
fit: BoxFit.fill,
),
),
),
),
)
.toList(),
),
SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: imageList.map((urlOfItem) {
int index = imageList.indexOf(urlOfItem);
return Container(
width: 10.0,
height: 10.0,
margin: EdgeInsets.symmetric(vertical: 10.0, horizontal: 2.0),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: _currentIndex == index
? Color.fromRGBO(0, 0, 0, 0.8)
: Color.fromRGBO(0, 0, 0, 0.3),
),
);
}).toList(),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(padding: EdgeInsets.symmetric(vertical: 100)),
FloatingActionButton(
heroTag: "btn1",
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => MainMenu()));
},
child: Icon(Icons.apps),
backgroundColor: Colors.red.shade800,
),
],
),
],
),
),
);
}
}
Have you added them to pubspec.yaml? Watch out for indentantion, like here.
After that stop an app and run it again, assets won't load if you hot restart.
I try one of the examples in one demo app, and it works like this:
Image(image: AssetImage(item), fit: BoxFit.cover, width: 1000.0),
Of course, first look at the pubspec.yaml, and be sure you have added the images