If an image in your Flutter app flickers — especially when using an image from the backend wrapped in FastCachedImage — is usually caused by the widget being rebuilt when switching between views. Here’s how to prevent the flickering:
✅ 1. Keep the View State Persistent
If you’re rebuilding after state change, the widget tree is recreated and the image reloads (even if cached).
Solution: Use a StatefulWidget with an indexed stack to keep state persistent across sub-tree view changes.
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _selectedIndex = 0;
final List<Widget> _pages = [
HomePage(),
SearchPage(),
ProfilePage(),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(
index: _selectedIndex,
children: _pages,
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _selectedIndex,
onTap: _onItemTapped,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: 'Search',
),
BottomNavigationBarItem(
icon: FastCachedImage(
url: "https://your-backend.com/user-icon.png",
fit: BoxFit.cover,
fadeInDuration: Duration.zero, // ⛔ avoid fade animation
fadeOutDuration: Duration.zero,
),
label: 'Profile',
),
],
),
);
}
}
✅ 2. Disable Fade Transitions in FastCachedImage
The default behavior of many image libraries (including FastCachedImage) includes a fade-in effect after loading from cache or network — this may cause a flicker.
Solution: Set fadeInDuration and fadeOutDuration to Duration.zero.
FastCachedImage(
url: "https://your-backend.com/user-icon.png",
fit: BoxFit.cover,
fadeInDuration: Duration.zero,
fadeOutDuration: Duration.zero,
)
✅ 3. Use key or const Where Possible
If your image widget is being rebuilt because Flutter thinks it’s different (e.g. due to lack of a key), add a Key or promote the widget to a const (if possible).
BottomNavigationBarItem(
icon: FastCachedImage(
key: ValueKey("profile_icon"),
url: "https://your-backend.com/user-icon.png",
fadeInDuration: Duration.zero,
fadeOutDuration: Duration.zero,
),
label: 'Profile',
),
✅ 4. Cache the URL (If Backend URL Changes Often)
If your image URL changes (e.g. has a token or timestamp), the cache is invalidated and reloaded every time.
Solution: If you have dynamic URLs, consider:
- Using a stable URL
- Or caching the image file manually and referencing it via
FileImageif needed
✅ 5. Preload the Image
Optionally preload the image during the app startup or before switching tabs:
FastCachedImageConfig.addUrlToPreload("https://your-backend.com/user-icon.png");