How to use carousel_slider with assets in flutter - 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

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

How to add 3x3 row of buttons between my slider and floatingbutton

as the title says I want to add a 3x3 buttons grid, but I'm not able to do, I don't understand how to create all of this elements
(I'm thinking in a div way like in html)
Here is my code, at top is my carousel slider and at the bottom is the floatingbutton, I need my 3x3 to be below my carousel slider and top of my floating button
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
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',
];
void main() => runApp(CarouselDemo());
final themeMode = ValueNotifier(2);
class CarouselDemo extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ValueListenableBuilder(
builder: (context, value, g) {
return MaterialApp(
initialRoute: '/',
darkTheme: ThemeData.dark(),
themeMode: ThemeMode.values.toList()[value as int],
debugShowCheckedModeBanner: false,
routes: {
'/': (ctx) => ComplicatedImageDemo(),
},
);
},
valueListenable: themeMode,
);
}
}
class DemoItem extends StatelessWidget {
final String title;
final String route;
DemoItem(this.title, this.route);
#override
Widget build(BuildContext context) {
return ListTile(
title: Text(title),
onTap: () {
Navigator.pushNamed(context, route);
},
);
}
}
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),
Positioned(
bottom: 0.0,
left: 0.0,
right: 0.0,
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color.fromARGB(200, 0, 0, 0),
Color.fromARGB(0, 0, 0, 0)
],
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
),
),
padding: EdgeInsets.symmetric(
vertical: 10.0, horizontal: 20.0),
child: Text(
'No. ${imgList.indexOf(item)} image',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
),
),
),
],
)),
),
))
.toList();
class ComplicatedImageDemo extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Sayapp 0.2')),
body: Container(
child: CarouselSlider(
options: CarouselOptions(
autoPlay: true,
aspectRatio: 2.0,
enlargeCenterPage: true,
),
items: imageSliders,
),
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () {},
label: Text('Alert'),
icon: Icon(Icons.add_alert_sharp),
backgroundColor: Colors.red,
),
);
}
}
body: Column(
children: [
Container(
child: CarouselSlider(
options: CarouselOptions(
autoPlay: true,
aspectRatio: 2.0,
enlargeCenterPage: true,
),
items: imageSliders,
),
),
Column(
children: [
Row(
children: [
Button1();
Button2();
Button3();
],
),
Row(
children: [
Button1();
Button2();
Button3();
],
),
Row(
children: [
Button1();
Button2();
Button3();
],
),
],
),
],
),
You can use GridView.builder() to do this
List<Widget> buttonList = [Button1(),Button2(),Button3(),Button4(),Button5(),Button6(),Button7(),Button8(),Button9()];
// inside body
body: Column(
children: [
CarouselSlider(
options: CarouselOptions(
autoPlay: true,
aspectRatio: 2.0,
enlargeCenterPage: true,
),
items: imageSliders,
),
GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3, // number of widgets in a row
crossAxisSpacing: 10.0,
mainAxisSpacing: 10.0,
childAspectRatio: (1.0 / 1.2),
),
itemBuilder: (BuildContext context, int index) {
return buttonList[index];
},
itemCount: buttonList.length,
),
],)

Carousel Slider is repeated almost infinite number of times vertically, instead of once, with no error showing

I'm doing a carousel slider, but it's repeating itself almost an infinite number of times, instead of showing there once in my home page, and there is no error message that I can work with, I can't seem to find why it's doing all that, any help?
Carousel Slider code:
class CarouselSliderPage extends StatefulWidget {
const CarouselSliderPage({Key? key}) : super(key: key);
#override
_CarouselSliderPageState createState() => _CarouselSliderPageState();
}
class _CarouselSliderPageState extends State<CarouselSliderPage> {
int activeIndex = 0;
setActiveDot(index) {
setState(() {
activeIndex = index;
});
}
List imageList = [
"assets/images/mobiles/4.png",
"assets/images/laptops/1.jpg",
"assets/images/mobiles/3.png",
"assets/images/laptops/7.jpg",
"assets/images/mobiles/6.png",
];
#override
Widget build(BuildContext context) {
return Stack(
clipBehavior: Clip.none,
children: [
SizedBox(
height: 10,
),
Container(
width: MediaQuery.of(context).size.width,
child: CarouselSlider(
options: CarouselOptions(
autoPlayInterval: Duration(seconds: 4),
autoPlayCurve: Curves.fastLinearToSlowEaseIn,
autoPlayAnimationDuration: Duration(seconds: 2),
viewportFraction: 1.0,
onPageChanged: (index, reason) {
setActiveDot(index);
},
),
items: imageList
.map(
(item) => Center(
child: Image.asset(
item,
fit: BoxFit.cover,
),
),
)
.toList(),
),
),
Positioned(
left: 0,
right: 0,
bottom: 10,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: List.generate(imageList.length, (idx) {
return activeIndex == idx ? ActiveDot() : InactiveDot();
})),
)
],
);
}
}
class ActiveDot extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(right: 8.0),
child: Container(
width: 25,
height: 8,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5),
),
),
);
}
}
class InactiveDot extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(right: 8.0),
child: Container(
width: 8,
height: 8,
decoration: BoxDecoration(
color: Colors.grey,
borderRadius: BorderRadius.circular(5),
),
),
);
}
}
The calling of Carousel Slider class:
Container(
height: MediaQuery.of(context).size.height,
child: ListView.builder(
itemBuilder: (context, index) =>
CarouselSliderPage(),
),
),
ListView.builder is a builder that can and will multiple of 'x' widgets it works like a loop unless told otherwise.
You can try adding a parameter into listview.builder that's called itemCount: 1 or in your specific case add 'imageList.length' and it will cap on the amount of images you have on your list.
or simply remove the listview.builder entirely and just call
CarouselSliderPage(),
Example of code below:
Container(
height: MediaQuery.of(context).size.height,
child: ListView.builder(
itemCount: imageList.length,
itemBuilder: (context, index) =>
CarouselSliderPage(),
),
),
But I would use this one below:
Container(
height: MediaQuery.of(context).size.height,
child: CarouselSliderPage(),
),
Just remove the ListView.builder
Container(
height: MediaQuery.of(context).size.height,
child: CarouselSliderPage(),
),

Flutter : Column is not support under DraggableScrollbar

this is a page of TabBarView(). I want to add some text or container(), top of the ListView.builder(). Which is scroll-able with ListView.builder(). But column() isn't supported as child of DraggableScrollbar(). Why isn't it supported it here ?
How can I add Text() or any container(), before starting ListView.builder() widget ?
import 'package:boimarket/booksdescription.dart';
import 'package:boimarket/model/model.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:draggable_scrollbar/draggable_scrollbar.dart';
class StoryBooksCategory extends StatelessWidget {
final ScrollController controller;
const StoryBooksCategory({Key key, #required this.controller})
: super(key: key);
#override
Widget build(BuildContext context) {
var _height = MediaQuery.of(context).size.height;
var _width = MediaQuery.of(context).size.width;
final Color _whiteCream = Color.fromRGBO(250, 245, 228, 1);
final Color _darkBlue = Color.fromRGBO(0, 68, 69, 1);
return Align(
alignment: Alignment.topCenter,
child: Container(
width: _width / 1.1,
child: FutureBuilder(
future: fetchBooks(),
builder: (context, AsyncSnapshot<List<Book>> snapshot) {
if (!snapshot.hasData) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
LinearProgressIndicator(
backgroundColor: _whiteCream,
),
Text("Loading"),
],
);
} else(snapshot.hasData) {
var storyBooks =
snapshot.data.where((b) => b.category == 1).toList();
storyBooks.sort((a, b) => a.name.compareTo(b.name));
print(storyBooks.length);
return DraggableScrollbar.rrect(
controller: controller,
backgroundColor: _darkBlue,
child: Column(
children: [
Text("I want to add some text here"),
ListView.builder(
controller: controller,
scrollDirection: Axis.vertical,
itemCount: storyBooks.length,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () {
Route route = MaterialPageRoute(
builder: (context) => BookDescription(
storyBooksValue: storyBooks[index]),
);
Navigator.push(context, route);
},
child: Padding(
padding: const EdgeInsets.only(
left: 10.0, right: 10.0, top: 20.0),
child: Container(
width: _width / 1.1,
height: _height / 4,
decoration: BoxDecoration(
color: _whiteCream,
borderRadius: BorderRadius.all(
Radius.circular(5.0),
),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 2,
spreadRadius: 2,
offset: Offset(2.0, 2.0),
)
],
),
),
),
),
},
),
],
),
),
},
},
),
),
),
},
}

How to set image size in carousel slider 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(),
),
),
],
);