I working on a project where I have a Stack widget with a Container which has an image(this is the background of the app):
//Background image:
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(background),
fit: BoxFit.fill,
),
),
),
and a PageView widget that contains the page of the app. How do I do that when the widget changes page, then the AssetImage(background) change the image with a faded animation? Currently in the PageViews widget onPageChanged section I can change the background with multiple setStates:
onPageChanged: (index) {
if (index == 0) {
setState(() {
pageName = "Home";
background =
"lib/assets/Backgrounds/gradient_background_6.jpg";
});
} else if (index == 1) {
setState(() {
pageName = "Coupons";
background =
"lib/assets/Backgrounds/gradient_background_5.jpg";
});
} else if (index == 2) {
setState(() {
pageName = "Forum";
background =
"lib/assets/Backgrounds/gradient_background_4.jpg";
});
}
},
but with this solution the background image just change without any animation. What is the best why to change image with faded, or any other animation?
use AnimatedOpacity
for fade effect on background image, also you can fast or slow fade control with duration
properties i already use in it
Output:-
Code:-
import 'package:flutter/material.dart';
class PageViewExample extends StatefulWidget {
const PageViewExample({Key? key}) : super(key: key);
@override
State<PageViewExample> createState() => _PageViewExampleState();
}
class _PageViewExampleState extends State<PageViewExample>
with SingleTickerProviderStateMixin {
int currentIndex = 0;
String background = "https://picsum.photos/id/237/200/300";
@override
Widget build(BuildContext context) {
return Scaffold(
body: PageView.builder(
onPageChanged: (index) => setState(() {
currentIndex = index;
currentIndex == 1
? background = "https://picsum.photos/id/238/200/300"
: currentIndex == 2
? background = "https://picsum.photos/id/239/200/300"
: background = "https://picsum.photos/id/237/200/300";
}),
physics: const ClampingScrollPhysics(),
itemCount: 3,
itemBuilder: (context, index) {
return AnimatedOpacity(
duration: const Duration(seconds: 2),
opacity: currentIndex == index ? 1.0 : 0.1,
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(background),
fit: BoxFit.fill,
),
),
),
);
},
),
);
}
}