Flutter image not showing on simulator - Exception: Invalid Image Data - flutter

Hello I'm trying to make a carousel on my app but the images are not showing. The code and error are below, would appreciate if anyone can help me out with this.
The error on my terminal:
══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞════════════════════════════════════════════════════
The following _Exception was thrown resolving an image codec:
Exception: Invalid image data
Code:
class CarouselBuild extends StatefulWidget {
CarouselBuild({Key? key}) : super(key: key);
#override
State<CarouselBuild> createState() => _CarouselBuildState();
}
class _CarouselBuildState extends State<CarouselBuild> {
final urlImages = [
'https://unsplash.com/photos/VURwPtZqyF4',
'https://unsplash.com/photos/oCZHIa1D4EU',
'https://unsplash.com/photos/5-GNa303REg',
];
#override
Widget build(BuildContext context) {
return CarouselSlider.builder(
options: CarouselOptions(
enlargeCenterPage: true,
autoPlay: true,
aspectRatio: 2.0,
),
itemCount: urlImages.length,
itemBuilder: (context, index, realIndex) {
final urlImage = urlImages[index];
return buildImage(urlImage, index);
},
);
}
Widget buildImage(String urlImage, int index) => Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height * 0.3,
margin: EdgeInsets.symmetric(horizontal: 0),
color: Colors.grey,
child: Image.network(
urlImage,
fit: BoxFit.cover,
),
);
}

The problem is not with your code but with image paths.
You have defined your image paths as:
final urlImages = [
'https://unsplash.com/photos/VURwPtZqyF4',
'https://unsplash.com/photos/oCZHIa1D4EU',
'https://unsplash.com/photos/5-GNa303REg',
];
However, these are not the actual images, but only the Unsplash pages. The existing paths for your provided photos would be:
final urlImages = [
'https://images.unsplash.com/photo-1578632767115-351597cf2477',
'https://images.unsplash.com/photo-1528360983277-13d401cdc186',
'https://images.unsplash.com/photo-1534214526114-0ea4d47b04f2',
];

Related

How to add network image in a List<ImageProvider>

I have a list of image.
final List<ImageProvider>_imageProviders_pro = [
new Image.asset(
"assets/page1.png",
fit: BoxFit.fitWidth,
).image,
new Image.asset(
"assets/page2.png",
fit: BoxFit.fitWidth,
).image,
...
];
#override
Widget build(BuildContext context) {
return Scaffold(
body:
ImageViewPager(imageProviders: _imageProviders_pro)
)
}
class ImageViewPager extends StatefulWidget {
final List<ImageProvider> imageProviders;
/// Create new instance, using the [imageProviders] to populate the [PageView]
const ImageViewPager({ Key? key, required this.imageProviders }) : super(key: key);
#override
_ImageViewPagerState createState() => _ImageViewPagerState();
}
class _ImageViewPagerState extends State<ImageViewPager> {
#override
Widget build(BuildContext context) {
return PageView(
children: <Widget>[
PageView.builder(
physics: _pagingEnabled ? const PageScrollPhysics() : const NeverScrollableScrollPhysics(),
itemCount: widget.imageProviders.length,
controller: _pageController,
itemBuilder: (context, index) {
final image = widget.imageProviders[index];
return ImageView(
imageProvider: image,
onScaleChanged: (scale) {
setState(() {
_pagingEnabled = scale <= 1.0;
});
},
);
},
)
}
}
Now, I try to use same list with Image.network. But I have this error
The element type 'Image' can't be assigned to the list type 'ImageProvider'.
So I try to do something like thtat
final List<ImageProvider>_imageProviders_pro = [
Image.network('url_page1')
Image.network('url_page2')
];
You can use .image to get image-provider from Image.network.
Image.networ("url").image
final List<ImageProvider> _imageProviders_pro = [
Image.network('url_page1').image,
Image.network('url_page2').image
];

Slider not updating itself

I saw another StackOverflow post, none of that worked for me.
I am a flutter newbie.
I am showing modal bottom sheet from a stateful widget called 'Home'
showMaterialModalBottomSheet(
context: context,
bounce: true,
duration: const Duration(milliseconds: 600),
builder: (context) => SingleChildScrollView(
controller: ModalScrollController.of(context),
child: bookmark(id: books[index]['_id'], totalPages: int.parse(books[index]['total']), completedPages: int.parse(books[index]['done']),);
//another 'Stateful widget'
),
);
Another stateful widget name 'bookmark' looks like this
int toggleIndex = 0;
double dragPercentage = 0;
double dragUpdate = 0;
//variables common to both main widget and this widget
class bookmark extends StatefulWidget {
final int totalPages;
final int completedPages;
final int id;
bookmark({#required this.completedPages, #required this.totalPages, #required this.id});
#override
State<bookmark> createState() => _bookmarkState();
}
class _bookmarkState extends State<bookmark> {
#override
Widget build(BuildContext context) {
return
Container(
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: SizedBox(
width: double.maxFinite,
child: CupertinoSlider(
value: dragUpdate,
max: 100,
min: 0,
onChanged: (double dragUpdate) {
setState(() {
dragUpdate = dragUpdate;
dragPercentage = dragUpdate * widget.totalPages;
pages.text = (dragPercentage / 100.0).toStringAsFixed(0);
});
},
),
),
),
],
)
);
}
}
The slider is updating the value but is not updating itself.
to be clear, there are 2 stateful widgets named home and bookmark. I am calling showMaterialModalBottomSheet from home and building a bookmark.
what I tried?
I already tried to wrap my slider with a statefulbuilder and used its state to update the values.

Implementing custom horizontal scroll of listview of items like Louis Vuitton app

Recently I have downloaded the Louis Vuitton App. I found a strange type of horizontal scroll of product items in listview. I tried card_swiper package but couldnot get through it. How can I achieve such scroll as in gif below?
the trick here is to use a stack and:
Use a page view to display every element except the first one
Use a left aligned FractionallySizedBox which displays the first item and grows with the first item offset
It took me a few tries but the result is very satisfying, I'll let you add the bags but here you go with colored boxes ;) :
import 'dart:math';
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(home: FunList()));
}
class FunList extends StatefulWidget {
#override
State<FunList> createState() => _FunListState();
}
class _FunListState extends State<FunList> {
/// The colors of the items in the list
final _itemsColors = List.generate(
100,
(index) => Color((Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(1.0),
);
/// The current page of the page view
double _page = 0;
/// The index of the leftmost element of the list to be displayed
int get _firstItemIndex => _page.toInt();
/// The offset of the leftmost element of the list to be displayed
double get _firstItemOffset => _controller.hasClients ? 1 - (_page % 1) : 1;
/// Controller to get the current position of the page view
final _controller = PageController(
viewportFraction: 0.25,
);
/// The width of a single item
late final _itemWidth = MediaQuery.of(context).size.width * _controller.viewportFraction;
#override
void initState() {
super.initState();
_controller.addListener(() => setState(() {
_page = _controller.page!;
}));
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Center(
child: Stack(
children: [
Positioned.fill(
child: Align(
alignment: Alignment.centerLeft,
child: SizedBox(
width: _itemWidth,
child: FractionallySizedBox(
widthFactor: _firstItemOffset,
heightFactor: _firstItemOffset,
child: PageViewItem(color: _itemsColors[_firstItemIndex]),
),
),
),
),
SizedBox(
height: 200,
child: PageView.builder(
padEnds: false,
controller: _controller,
itemBuilder: (context, index) {
return Opacity(
opacity: index <= _firstItemIndex ? 0 : 1,
child: PageViewItem(color: _itemsColors[index]),
);
},
itemCount: _itemsColors.length,
),
),
],
),
);
}
}
class PageViewItem extends StatelessWidget {
final Color color;
const PageViewItem({
Key? key,
required this.color,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(10),
color: color,
);
}
}

I cannot see my pictures in flutter swiper

I am new in flutter development. I cannot find my mistake. I can't see my images on my app. when I use them without slider it works what is wrong in my code can someone help me?
import 'package:feedme_start/widgets/Navigation_Drawer_Widget.dart';
import 'package:flutter/material.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:flutter_swiper/flutter_swiper.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
final imageList = [
"https://cdn.yeniakit.com.tr/images/news/625/pratik-degisik-yemek-tarifleri-en-sevilen-tarifler-h1581081558-3ff37b.jpg"
"https://cdn.yemek.com/mncrop/940/625/uploads/2021/04/patlicanli-pilav-yemekcom.jpg"
];
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.red,
title: Center(child: Text("FEED ME")),
actions: <Widget>[
IconButton(onPressed: () {}, icon: Icon(Icons.call))
],
),
drawer: NavigationDrawerWidget(),
backgroundColor: Colors.white,
body:
Container(
constraints: BoxConstraints.expand(height: 200),
child: imageSlider(context),
),
/*Swiper(itemCount: imageList.length,
itemBuilder: (context, index) {
return Image.network(imageList[index],/*errorBuilder:
(BuildContext context, Object exception, StackTrace? stackTrace), {return const("resim yüklenemedi")},*/
fit: BoxFit.cover,);
},)*/
),
);
}
}
Swiper imageSlider(context){
return new Swiper(
autoplay: true,
itemBuilder: (BuildContext context, int index) {
return new Image.network("https://cdn.yeniakit.com.tr/images/news/625/pratik-degisik-yemek-tarifleri-en-sevilen-tarifler-h1581081558-3ff37b.jpg",fit: BoxFit.fitHeight,);
},
itemCount: 10,
viewportFraction: 0.8,
scale: 0.9,
);
}
also here is the screenshots;
when I run the program it tries to upload the image. then it sends me the this screen and shows the 'rethrow' line error:
after I continue debugging my screen looks like in the second picture:
You're simply forgetting to add , in your list.
A newline string after a string is considered as a string. For example, the following variable:
var text = "one two three"
"four five six";
is the same as:
var text = "one two three" + "four five six";
So, instead of:
final imageList = [
"https://cdn.yeniakit.com.tr/images/news/625/pratik-degisik-yemek-tarifleri-en-sevilen-tarifler-h1581081558-3ff37b.jpg"
"https://cdn.yemek.com/mncrop/940/625/uploads/2021/04/patlicanli-pilav-yemekcom.jpg"
];
change to:
final imageList = [
"https://cdn.yeniakit.com.tr/images/news/625/pratik-degisik-yemek-tarifleri-en-sevilen-tarifler-h1581081558-3ff37b.jpg" ,
"https://cdn.yemek.com/mncrop/940/625/uploads/2021/04/patlicanli-pilav-yemekcom.jpg"
];

Flutter default image not loading

New to flutter. Working on a personal project. Stuck with a small issue related to show images. Here is my widget code which I'm using for showing images.
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:cached_network_image/cached_network_image.dart';
class UserProfile extends StatefulWidget {
#override
UserProfileState createState() => new UserProfileState();
}
class UserProfileState extends State<UserProfile> {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Map userDetails = {};
String profileImgPath;
#override
void initState() {
super.initState();
getUserDetails();
}
Future<Null> getUserDetails() async {
try {
final SharedPreferences prefs = await _prefs;
this.userDetails = json.decode(prefs.getString('user'));
if (prefs.getString('user') != null) {
if (this.userDetails['isLoggedIn']) {
setState(() {
this.profileImgPath = this.userDetails['profileImg'];
print('Shared preference userDetailsss : ${this.userDetails}');
});
}
} else {
print('Shared preference has no data');
}
} catch (e) {
print('Exception caught at getUserDetails method');
print(e.toString());
}
}
#override
Widget build(BuildContext context) {
Widget profileImage = new Container(
margin: const EdgeInsets.only(top: 20.0),
child: new Row(
children: <Widget>[
new Expanded(
child: new Column(
children: <Widget>[
new CircleAvatar(
backgroundImage: (this.profileImgPath == null) ? new AssetImage('images/user-avatar.png') : new CachedNetworkImageProvider(this.profileImgPath),
radius:50.0,
)
],
)
)
],
)
);
return new Scaffold(
appBar: new AppBar(title: new Text("Profile"), backgroundColor: const Color(0xFF009688)),
body: new ListView(
children: <Widget>[
profileImage,
],
),
);
}
}
What I'm trying to do is, show the default user-avatar.png image as long as CachedNetworkImageProvider don't get original image. But, it's bit behaving differently.
Whenever I'm opening the page - I'm getting a blank blue box then suddenly the original image from CachedNetworkImageProvider comes up.
Can't able to understand what's happening.
#Jonah Williams for your reference -
CachedNetworkImage can't be used for backgroundImage property because it does not extends ImageProvider. You can create a custom CircleAvatar like described below to use the CachedNetworkImage package:
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
class CustomCircleAvatar extends StatelessWidget {
final int animationDuration;
final double radius;
final String imagePath;
const CustomCircleAvatar({
Key key,
this.animationDuration,
this.radius,
this.imagePath
}) : super(key: key);
#override
Widget build(BuildContext context) {
return new AnimatedContainer(
duration: new Duration(
milliseconds: animationDuration,
),
constraints: new BoxConstraints(
minHeight: radius,
maxHeight: radius,
minWidth: radius,
maxWidth: radius,
),
child: new ClipOval(
child: new CachedNetworkImage(
errorWidget: (context, url, error) => Icon(Icons.error),
fit: BoxFit.cover,
imageUrl: imagePath,
placeholder: (context, url) => CircularProgressIndicator(),
),
),
);
}
}
And how to use:
body: new Center(
child: new CustomCircleAvatar(
animationDuration: 300,
radius: 100.0,
imagePath: 'https://avatars-01.gitter.im/g/u/mi6friend4all_twitter?s=128',
),
),
Maybe it is not the better way. But, it works!
(I'm assuming that CachedNetworkImageProvider is actually CachedNetworkImage from this package).
This line of code will always display the second image.
(this.profileImgPath == null)
? new AssetImage('images/user-avatar.png')
: new CachedNetworkImageProvider(this.profileImgPath)
Since profileImagePath is not null, the AssetImage is never created. Even if it was, as soon as it's not the cached network image will replace it before it has loaded. Instead, use the placeholder parameter of the network image. This will display your asset image until the network image loads.
new CachedNetworkImage(
placeholder: new AssetImage('images/user-avatar.png'),
imageUrl: profileImgPath,
)