[英]How i can change the icon in the Icon button
我正在嘗試構建一個whatsapp克隆,並且當我正在從正面和背面更換相機時。 我試圖更改圖標按鈕中的圖標,但它沒有改變
我將在下面附上我的代碼文件
Widget bottomIcon({Icon icon,double size,Function onpress}){
return IconButton(
icon: icon,
iconSize: size,
color: Colors.white,
onPressed: onpress,
);
}
Icon iconForcam=Icon(Icons.camera_rear);
@override
Widget build(BuildContext context) {
if (!controller.value.isInitialized) {
return Container();
}
return MaterialApp(
home: Padding(
padding: const EdgeInsets.all(1.0),
child: Stack(
fit: StackFit.expand,
children: [
CameraPreview(controller),
Positioned(
bottom: 0,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
SizedBox(width: 20.0,),
bottomIcon(icon: Icon(Icons.flash_on_rounded),size: 50.0),
SizedBox(width: 20.0,),
bottomIcon(icon: Icon(Icons.fiber_manual_record_outlined),size: 100.0),
SizedBox(width: 30.0,),
bottomIcon(icon: iconForcam,size: 50.0,onpress: (){
setState(() {
if(iconForcam == Icon(Icons.camera_front)){
iconForcam = Icon(Icons.camera_rear);
}else if(iconForcam == Icon(Icons.camera_rear)){
print('rearcam');
iconForcam = Icon(Icons.camera_front);
}
});
//toggleCamera();
}),
],
),
),
],
),
),
);
}
}
我懷疑如果我可以在 if 語句中比較兩個圖標。
您可以定義一個 boolean 變量
//定義
bool _isFront = true;
//用法
bottomIcon(
icon: _isFront ?
Icons.camera_front : Icons.camera_rear,
size: 50.0, onpress: (){
setState(() {
_isFront = !_isFront;
});
//toggleCamera();
})
我試過這樣並得到了正確的
//定義
int _oldIndex=0;
Icon iconForcam=Icon(Icons.camera_rear);
//內部代碼
bottomIcon(icon: iconForcam,size: 50.0,onpress: (){
setState(() {
if(_oldIndex == 0){
iconForcam = Icon(Icons.camera_rear);
_oldIndex = 1;
}else if(_oldIndex == 1){
//print('rearcam');
iconForcam = Icon(Icons.camera_front);
_oldIndex = 0;
}
});
toggleCamera(_oldIndex);
}),
您可以將前置攝像頭是否打開存儲在 shared_prefernces 或數據庫中,使用 provider/stream/bloc 將此值公開給 UI。 現在您可以使用這個 package來更改帶有 animation 的圖標。 將此 package 安裝到您的 flutter 項目中,將其導入文件中,然后將相機按鈕的icon
屬性替換為以下代碼:
AdvancedIcon(
icon: Icons.camera_front,
secondaryIcon: Icons.camera_rear,
state: isFrontCameraOn ? AdvancedIconState.primary : AdvancedIconState.secondary,
)
現在圖標將根據前置攝像頭是否打開而自動更改。
如果您對此問題的數據庫或提供者部分有疑問,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.