我在一個專案中作業,我有一個 Stack 小部件和一個帶有影像的容器(這是應用程式的背景):
//Background image:
Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(background),
fit: BoxFit.fill,
),
),
),
和一個包含應用程式頁面的 PageView 小部件。當小部件更改頁面時,我該怎么做,然后 AssetImage(background) 使用褪色影片更改影像?目前在 PageViews 小部件 onPageChanged 部分中,我可以使用多個 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";
});
}
},
但是使用此解決方案,背景影像只會更改而沒有任何影片。用褪色或任何其他影片更改影像的最佳原因是什么?
uj5u.com熱心網友回復:
用于AnimatedOpacity背景影像的淡入淡出效果,您也可以duration使用我已經在其中使用的屬性進行快速或慢速淡入淡出控制
輸出:-

代碼:-
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,
),
),
),
);
},
),
);
}
}
uj5u.com熱心網友回復:
也許你可以使用 SwitchAnimation,但你需要一個鍵,你可以像“鍵”一樣使用索引這是一個例子
import 'package:flutter/material.dart';
class Examp extends StatelessWidget {
const Examp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body:
AnimatedSwitcher(
key: index,
duration: const Duration(milliseconds: 700),
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(background),
fit: BoxFit.fill,
),
),
),
),
);
}
}
判斷此代碼??是否適合您
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/453699.html
上一篇:跨范圍查找重復項并將其匯總
