How to create carousel slider with firestore image and onclick launch url in flutter? - flutter

I want to create carousel slider in flutter with cloud firestore. I created cloud firestore collection with the name of "slider" and i have two fields one is "image" and another one is "url".
Now i need to stream firestore collection in my carousel slider and when user click image, want to launch url.
My Carousel Slider Code
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
class Dashboard extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ListView(
children: <Widget>[
SizedBox(height: 15.0),
CarouselSlider(
options: CarouselOptions(
height: 400.0,
enlargeCenterPage: true,
autoPlay: true,
aspectRatio: 16 / 9,
autoPlayCurve: Curves.fastOutSlowIn,
enableInfiniteScroll: true,
autoPlayAnimationDuration: Duration(milliseconds: 800),
viewportFraction: 0.8),
items: [
Container(
margin: EdgeInsets.all(5.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
image: DecorationImage(
image: AssetImage('$show Firestore image'),
onPressed: () {
launchURL(
"$ launch firestore url");
}
fit: BoxFit.cover,
),
),
),
],
),
],
);
}
}
Can anyone guide me?

Widget build(BuildContext context) {
var idx = 1;
return Container(
margin: EdgeInsets.only(top: 4.0, bottom: 8.0),
height: getProportionateScreenHeight(150),
width: double.infinity,
decoration: BoxDecoration(
color: Color(0xFF4A3298),
borderRadius: BorderRadius.circular(20),
),
child:StreamBuilder(
stream: FirebaseFirestore.instance.collection(BANNER_URL).snapshots(),
builder: (context, AsyncSnapshot snapshot) {
List list = []..length;
switch (snapshot.connectionState) {
case ConnectionState.none:
return Container(
child: Center(
child: new Text(
'No network. \nPlease, check the connection.')),
);
break;
case ConnectionState.waiting:
return Container(
child: Center(child: new CircularProgressIndicator()),
);
break;
default:
if (snapshot.hasError) {
return Container(
child: Center(
child: Text(snapshot.error.toString()),
),
);
} else if (snapshot.hasData) {
for (int i = 0; i < snapshot.data.size; i++) {
debugPrint("Index is " + idx.toString());
list.add(NetworkImage(
snapshot.data.docs[i].data()['image_url']));
idx++;
}
return ClipRect(
child: Banner(
message: "Publicite aqui",
location: BannerLocation.topEnd,
color: Colors.red,
child: Carousel(
boxFit: BoxFit.cover,
images: list,
autoplay: true,
animationCurve: Curves.fastLinearToSlowEaseIn,
animationDuration: Duration(milliseconds: 2000),
dotSize: 2.0,
dotColor: AppTheme.cuyuyuOrange400,
dotBgColor: AppTheme.cuyuyuTransparent,
indicatorBgPadding: 2.0,
)),
);
}
}
}),
);
}

You can make use of a FutureBuilder to fetch the document snapshot, and on completion, you can store the URLs in a list and use the list for the Carousel
Example code which uses FutureBuilder to fetch a list of urls:
Future getCarouselWidget() async {
var firestore = Firestore.instance;
QuerySnapshot qn = await firestore.collection("carousel").getDocuments();
return qn.documents;
}
Widget build(BuildContext context) {
var idx = 1;
return Container(
child: FutureBuilder(
future: getCarouselWidget(),
builder: (context, AsyncSnapshot snapshot) {
List<NetworkImage> list = new List<NetworkImage>();
if (snapshot.connectionState == ConnectionState.waiting) {
return new CircularProgressIndicator();
} else {
if (snapshot.hasError) {
return new Text("fetch error");
} else {
//Create for loop and store the urls in the list
for(int i = 0; i < snapshot.data[0].data.length; i++ ) {
debugPrint("Index is " + idx.toString());
list.add(NetworkImage(snapshot.data[0].data["img_"+idx.toString()]));
idx++;
}
return new Container(
height: 250.0,
child: new Carousel(
boxFit: BoxFit.cover,
images: list, <== Set the list here
autoplay: true,
dotSize: 4.0,
indicatorBgPadding: 4.0,
animationCurve: Curves.fastOutSlowIn,
animationDuration: Duration(milliseconds: 1000),
));
}
}
}),
);

Related

How to get image from API to Carousel in Flutter

I am facing this problem where I am trying to display images in a carousel. I am using the package carousel_slider: ^4.1.1. I am confused because when I hard code the content in a variable it is working perfectly displayed in my carousel widget. but the output is empty I want to use a Carousel in Flutter, so I tried to get it following the code. after running my code it's empty in output.
Map mapResponse = {};
Map dataResponse = {};
List listResponse = {} as List;
class apipro extends StatefulWidget {
const apipro({Key? key}) : super(key: key);
#override
State<apipro> createState() => _apipro();
}
class _apipro extends State<apipro> {
Future<List> team() async {
http.Response response;
response = await http.get(Uri.parse(
"https://www.archmage.lk/api/v1/webapi/getclients?page=0&limit=10"));
// ignore: unnecessary_null_comparison
Map mapResponse = json.decode(response.body);
return mapResponse['data'] as List;
}
#override
void initState() {
// team();
super.initState();
}
#override
Widget build(BuildContext context) {
return Center(
child: FutureBuilder<List?>(
future: team(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return const Text(
'Loading....',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w100,
),
);
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
List data = snapshot.data ?? [];
_buildItem(image, String name) {
return CarouselSlider(
options: CarouselOptions(
viewportFraction: 0.3,
autoPlayAnimationDuration:
const Duration(milliseconds: 2000),
autoPlay: true,
enlargeCenterPage: true,
height: 80),
items: <Widget>[
for (var i = 0; i < image.length; i++)
Container(
margin:
const EdgeInsets.only(top: 20.0, left: 20.0),
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(image[i]),
fit: BoxFit.fitHeight,
),
// border:
// Border.all(color: Theme.of(context).accentColor),
borderRadius: BorderRadius.circular(32.0),
),
),
],
);
// ignore: dead_code
}
return ListView.builder(
shrinkWrap: true,
padding: const EdgeInsets.all(18),
itemBuilder: (context, index) {
return _buildItem(data[index]['name']?.toString() ?? '',
data[index]['image']?.toString() ?? '');
},
itemCount: data.length,
);
}
}
}),
);
}
}
I got the Proper response by Function which I created there is no error in my code. So how i can display Images in carousel_slider? Please Help. Thank you.
Try this:
Center(
child: FutureBuilder<List?>(
future: team(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return const Text(
'Loading....',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w100,
),
);
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
List data = snapshot.data ?? [];
return CarouselSlider.builder(
itemBuilder: (context, index, realIndex) {
return Container(
margin: const EdgeInsets.only(top: 20.0, left: 20.0),
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(data[index]['image']),
fit: BoxFit.fitHeight,
),
color: Colors.red,
borderRadius: BorderRadius.circular(32.0),
),
);
},
options: CarouselOptions(
viewportFraction: 0.3,
autoPlayAnimationDuration:
const Duration(milliseconds: 2000),
autoPlay: true,
enlargeCenterPage: true,
height: 80),
itemCount: data.length,
);
}
}
}),
)
class APIPRO extends StatelessWidget {
const APIPRO({Key? key}) : super(key: key);
Future<List> team() async {
http.Response response;
response = await http.get(Uri.parse("https://www.archmage.lk/api/v1/webapi/getclients?page=0&limit=10"));
// ignore: unnecessary_null_comparison
Map mapResponse = jsonDecode(response.body);
return mapResponse['data'] as List;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FutureBuilder(
future: team(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return const Text(
'Loading....',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w100,
),
);
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
List data = snapshot.data ?? [];
return CarouselSlider(
options: CarouselOptions(viewportFraction: 0.3, autoPlayAnimationDuration: const Duration(milliseconds: 2000), autoPlay: true, enlargeCenterPage: true, height: 80),
items: data
.map(
(e) => Container(
margin: const EdgeInsets.only(top: 20.0, left: 20.0),
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(e["image"]),
fit: BoxFit.fitHeight,
),
// border:
// Border.all(color: Theme.of(context).accentColor),
borderRadius: BorderRadius.circular(32.0),
),
),
)
.toList());
}
}
}),
),
);
}
}

Carousel slider with data retrieved from firebase realtime database

What I would like is to retrieve the data from a Firebase Realtime Database query instead of the List I created manually.
Here I am using a flutter package which is CarouselSlider and I am retrieving the data from a list written manually by myself while what I would like is to retrieve the content of my slider from a query.
Thanks for your help.
Here is my complete code:
import 'package:carousel_slider/carousel_slider.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flyzik/size_config.dart';
class SliderWidget extends StatefulWidget {
#override
State<SliderWidget> createState() => _SliderWidgetState();
}
final List<String> imgList = [
'https://firebasestorage.googleapis.com/v0/b/zfly2020-151d6.appspot.com/o/images_slide%2F3b1ab9f0-671a-11eb-bbaf-6ef0e5b93f8c.jpeg?alt=media&token=2b10908d-edb5-4527-9130-a5e076972e88',
'https://firebasestorage.googleapis.com/v0/b/zfly2020-151d6.appspot.com/o/images_slide%2FCopie%20de%20Red%20and%20black%20Black%20Friday%20sale%20Twitter%20post%20-%20Fait%20avec%20PosterMyWall.jpg?alt=media&token=2c39e317-859c-4560-963a-8374fe34fbcc',
'https://firebasestorage.googleapis.com/v0/b/zfly2020-151d6.appspot.com/o/images_slide%2F6169541506df6_61695418e5c29.jpg?alt=media&token=4c250834-d4f9-4946-93d6-c4bba58766c4',
'https://firebasestorage.googleapis.com/v0/b/zfly2020-151d6.appspot.com/o/images_slide%2F20211211_234252.jpg?alt=media&token=1cb1edcc-bf80-4fbd-a419-2c175e85997f',
'https://firebasestorage.googleapis.com/v0/b/zfly2020-151d6.appspot.com/o/images_slide%2Frap%20(1).jpg?alt=media&token=a2f3996f-b2d9-4cfd-81d2-1fe5c0becb6a'
];
class _SliderWidgetState extends State<SliderWidget> {
#override
Widget build(BuildContext context) {
return Container(
child: CarouselSlider(
options: CarouselOptions(
autoPlay: true,
aspectRatio: 2.0,
enlargeCenterPage: true,
enlargeStrategy: CenterPageEnlargeStrategy.height,
),
items: imageSliders,
),
);
}
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: Center(
child: Image.network(
item,
fit: BoxFit.cover,
width: 1500.0,
height: getProportionateScreenHeight(300),
),
)),
),
))
.toList();
}
thank
This the result of all modification
First part
Second part
My database
You can fetch content with a method and use FutureBuilder to fetch it for you automatically.
Future<DataSnapshot> fetchList() async {
const path = 'SET YOUR PATH HERE';
return await FirebaseDatabase.instance.ref(path).get();
}
Wrap your Widget with FutureBuilder
#override
Widget build(BuildContext context) {
return FutureBuilder<DataSnapshot>(
future: fetchList(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
}
if (snapshot.hasData && snapshot.data != null) {
final imgList = List<String>.from(snapshot.data?.value as List);
return Container(
child: CarouselSlider(
options: CarouselOptions(
autoPlay: true,
aspectRatio: 2.0,
enlargeCenterPage: true,
enlargeStrategy: CenterPageEnlargeStrategy.height,
),
items: imageSliders(imgList),
),
);
}
);
return Text('Error');
}
final List<Widget> imageSliders(List<String> imgList) => imgList
.map((item) => Container(
child: Container(
margin: EdgeInsets.all(5.0),
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
child: Center(
child: Image.network(
item,
fit: BoxFit.cover,
width: 1500.0,
height: getProportionateScreenHeight(300),
),
)),
),
))
.toList();
}
Use imgList to map your data into Widget

Images dose not display on the screen instead it shows loading icon

I used a grid view list in order to show some items in another list that contain images
and doesn't show the items, instead it shows the loading icon
this is my code:
import 'package:flutter/material.dart';
import 'package:sct/list/list.dart';
class badriya2 extends StatefulWidget {
#override
State<badriya2> createState() => _badriya2State();
}
class _badriya2State extends State<badriya2> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
"She codes",
),
),
body: FutureBuilder(builder: (context, AsyncSnapshot snapshot) {
height:
MediaQuery.of(context).size.height;
width:
MediaQuery.of(context).size.width;
if (snapshot.hasData) {
List resList = snapshot.data;
child:
Expanded(
child: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 5,
crossAxisSpacing: 5.0,
mainAxisSpacing: 5.0,
),
itemCount: resList.length,
itemBuilder: (context, index) {
primary:
true;
padding:
const EdgeInsets.all(20);
shrinkWrap:
true;
children:
<Widget>[
Card(
child: Center(
child: CircleAvatar(
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Image.asset(
list[0].image,
),
),
minRadius: 50,
maxRadius: 75,
),
),
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
),
];
return Center(child: CircularProgressIndicator());
}));
}
return Center(child: CircularProgressIndicator());
}));
}
}
and this is the list :
import 'package:flutter/cupertino.dart';
List list = [
{
Image.asset('assets/images/butterfly.jpg'),
},
{
Image.asset('assets/images/flower.jpg'),
},
{
Image.asset('assets/images/glass.jpg'),
},
{
Image.asset('assets/images/sun.jpg'),
},
{
Image.asset('assets/images/lighting.jpg'),
},
{
Image.asset('assets/images/phone.jpg'),
},
{
Image.asset('assets/images/eye.jpg'),
},
{
Image.asset('assets/images/photo1.jpg'),
},
];
the point of this code is not to duplicate the items in grid view, I want to write in one line
Add future method onfuture inside FutureBuilder.
return FutureBuilder(
future: yourFutureMethod(),
builder: (context, snapshot) {...},
);
You use the Future Builder but you didn't mention any future. Set the Future
import 'package:flutter/material.dart';
import 'package:sct/list/list.dart';
class badriya2 extends StatefulWidget {
#override
State<badriya2> createState() => _badriya2State();
}
class _badriya2State extends State<badriya2> {
var dummy;
#override
void initState() {
super.initState();
dummy = _getimages();
print("data ${dummy}");
}
_getimages() async {
var imagelist = await list;
print(imagelist);
return imagelist;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
"She codes",
),
),
body: FutureBuilder(
future: _getimages(),
builder: (context, AsyncSnapshot snapshot) {
if(snapshot.hasError) print(snapshot.error);
return snapshot.hasData
?GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 5.0,
mainAxisSpacing: 5.0,
),
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
List reslist = snapshot.data;
return Column(
children: [
Card(
child: Center(
child: Container(
width: 100,
height: 100,
child: CircleAvatar(
child: ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Image.network(reslist[index].toString(),)
),
minRadius: 50,
maxRadius: 75,
),
),
),
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
),
],
);
}
):
Center(
child:CircularProgressIndicator()
);
}
)
);
}
}
And please assign proper list of data
import 'package:flutter/cupertino.dart';
List list= [
"https://dlanzer.com/flutter_api/assets/uploads/images/farm_2021-10-25%2005:09:48am.png",
"https://dlanzer.com/flutter_api/assets/uploads/images/farm_2021-10-25%2005:09:11am.png",
"https://dlanzer.com/flutter_api/assets/uploads/images/farm_2021-10-19%2002:51:18pm.png",
"https://dlanzer.com/flutter_api/assets/uploads/images/farm_2021_10_12_04_30_13_pm.png",
];
Here I use network images You change to asset images

Can't retrieve data from nested object firestore streambuilder listview

I'm new using firestore, so im still trying to understand it.
i had Closets on the inside i had Clothes. i want to retrieve Clothes data and show it with listview.
the problem is i failed to retrieve the data and show it into the app
this is my code for the streambuilder
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection("clothes").snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text("Failed to load data!");
}
if (snapshot.connectionState ==
ConnectionState.waiting) {
return ActivityServices.loadings();
}
return new ListView(
children: snapshot.data.docs
.map((DocumentSnapshot doc) {
Clothes clothes;
clothes = new Clothes(
doc.data()['clothesId'],
doc.data()['clothesName'],
doc.data()['clothesDesc'],
doc.data()['clothesImage'],
doc.data()['clothesCloset'],
doc.data()['clothesAge'],
doc.data()['clothesTag'],
doc.data()['clothesStatus'],
doc.data()['clothesLaundry'],
doc.data()['createdAt'],
doc.data()['updatedAt'],
);
print(doc.data()['clothesName']);
return CardClothesLemari(clothes: clothes);
}).toList(),
);
},
),
and this is my CardClothesLemari
final Clothes clothes;
CardClothesLemari({this.clothes, this.doc});
#override
_CardClothesLemariState createState() => _CardClothesLemariState();
}
class _CardClothesLemariState extends State<CardClothesLemari> {
#override
Widget build(BuildContext context) {
Clothes cloth = widget.clothes;
final Size size = MediaQuery.of(context).size;
if (clothes == null) {
return Container();
} else {
return Padding(
padding:
EdgeInsets.only(top: 5.0, bottom: 5.0, left: 5.0, right: 5.0),
child: InkWell(
onTap: () {
Navigator.pushNamed(context, DetailClothes.routeName,
arguments: cloth);
},
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(14.0),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.2),
spreadRadius: 3.0,
blurRadius: 5.0)
],
color: Color(0xffA77665),
),
child: Column(children: [
Padding(
padding: EdgeInsets.only(top: size.height * 0.04),
),
Hero(
tag: 'assets/images/dummy.jpg',
child: CircleAvatar(
radius: 55,
backgroundImage: AssetImage("assets/images/dummy.jpg"),
),
),
SizedBox(height: 7.0),
Text(
//show clothes name
cloth.clothes,
style: TextStyle(
fontSize: 14,
fontFamily: GoogleFonts.openSans().fontFamily,
fontWeight: FontWeight.w700,
color: Color(0xffF0E8E1)),
textAlign: TextAlign.center,
),
Padding(
padding: EdgeInsets.only(top: 8),
child:
Container(color: Color(0xFFEBEBEB), height: 2.9657),
),
]))));
}
}
}
this is the screenshot of my firestore
Add listview inside the ConnectionState.done like below code.
if (snapshot.connectionState == ConnectionState.done) {
return new ListView(
children: snapshot.data.docs
.map((DocumentSnapshot doc) {
Clothes clothes;
clothes = new Clothes(
doc.data()['clothesId'],
doc.data()['clothesName'],
doc.data()['clothesDesc'],..........<Rest of the code>......
}
As per your database structure you're entering wrong query. Kindly take a look below code
StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
stream: FirebaseFirestore.instance
.collection('closet')
.doc('your_document_id')
.collection('clothes')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Text('Loading...');
} else {
return ListView.builder(
itemCount: snapshot.data.docs.length,
shrinkWrap: true,
itemBuilder: (context, int index) {
QueryDocumentSnapshot<Map<String, dynamic>> data = snapshot.data.docs[index];
return Text(data.data()['clothesName']);
},
);
}
});

Flutter page jumps to top after setState({})

I display many images in a Staggered Gridview in a Flutter application.
Everytime I call setState({}), for example after deleting an item, the page jumps to top. How could I remove this behavior?
This is my code:
final _scaffoldKey = new GlobalKey<ScaffoldState>();
.. outside the build function. And then...
return loadingScreen == true
? LoadingScreen()
: Scaffold(
key: _scaffoldKey,
body: CustomScrollView(
slivers: <Widget>[
_AppBar(
theme: theme,
index: index,
albumImagePath: albumImagePath,
albumID: albumID,
albumValue: albumValue,
addPictureToGallery: _addPictureToGallery,
),
SliverToBoxAdapter(
child: Column(
children: <Widget>[
InfoBar(
albumPicturesSum: albumPicturesSum,
getBilderString: _getBilderString,
theme: theme,
getVideoProgress: _getVideoProgress,
progress: progress,
),
albumID == 99999999
? // Demo Projekt
DemoImageGrid(
demoImageList: demoImageList,
getDemoImagesJson: _getDemoImagesJson,
)
: UserImageGrid(
picturesData: picturesData,
albumID: albumID,
showPictureActions: _showPictureActions)
],
),
)
],
),
);
}
The UserImageGrid looks like the following:
class UserImageGrid extends StatelessWidget {
final Pictures picturesData;
final int albumID;
final Function showPictureActions;
final _key = new UniqueKey();
UserImageGrid(
{#required this.picturesData,
#required this.albumID,
#required this.showPictureActions});
#override
Widget build(BuildContext context) {
return FutureBuilder(
key: _key,
future: picturesData.getPicturesFromAlbum(albumID),
builder: (BuildContext context, AsyncSnapshot snapshot) {
// Normale Projekte
if (snapshot.hasData && snapshot.data.length == 0) {
return Center(
child: Column(
children: <Widget>[
Lottie.asset('assets/lottie/drone.json',
width: 250,
options: LottieOptions(enableMergePaths: false)),
],
),
);
}
if (!snapshot.hasData ||
snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return Container(
child: StaggeredGridView.countBuilder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
padding: EdgeInsets.all(0),
crossAxisCount: 6,
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) =>
GestureDetector(
onLongPress: () {
showPictureActions(snapshot.data[index]);
},
onTap: () async {
await showDialog(
context: context,
builder: (_) {
return Dialog(
child: Stack(
children: [
Container(
margin: const EdgeInsets.symmetric(
vertical: 10.0,
horizontal: 10.0,
),
height: 500.0,
child: ClipRect(
child: PhotoView(
maxScale:
PhotoViewComputedScale.covered * 2.0,
minScale:
PhotoViewComputedScale.contained *
0.8,
initialScale:
PhotoViewComputedScale.covered,
imageProvider: FileImage(
File(snapshot.data[index].path))),
),
),
Positioned(
bottom: 20,
left: 20,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
DateFormat(tr("date_format")).format(
snapshot.data[index].timestamp
.toDateTime()),
style: TextStyle(color: Colors.white),
),
),
)
],
));
});
},
child: Container(
child: Image.file(
File(snapshot.data[index].thumbPath),
fit: BoxFit.cover,
)),
),
staggeredTileBuilder: (int index) =>
new StaggeredTile.count(2, index.isEven ? 2 : 2),
mainAxisSpacing: 5.0,
crossAxisSpacing: 5.0,
),
);
}
});
}
}
What could be the issue?
I found a solution for this issue. The problem was not the setState({}). It was the return Widget of the FutureBuilder.
I changed
if (!snapshot.hasData || snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
}
to:
if (!snapshot.hasData || snapshot.connectionState == ConnectionState.waiting) {
return Container(
height: MediaQuery.of(context).size.height,
);
}
I donĀ“t exactly know why, but with this change the page is not jumping to top anymore on setState({})