'How to find out in Flutter when a Widget appears / disappears?
I would like to find out in a stateful widget when the whole widget appears on screen or disappears, similar to iOS onViewWillAppear / disappear. Is that possible somehow? I didn't find anything related in the Flutter docs.
Thanks!
Solution 1:[1]
What your looking for is in the flutter_widgets
package
Add the following to your pubspec.yaml
flutter_widgets: ^0.1.7+1
Inside this package is a widget called VisibilityDetector
it requires a key
, a child
, and a function onVisibilityChanged
return VisibilityDetector(
key: Key("1"),
onVisibilityChanged: (visibility) {
//This will give you a range of values between 0 and 1,
//0 being not visible and 1 being fully visible.
print(visibility.visibleFraction)
}
child: Container(
width:double.infinity,
height: 300,
),
),
Solution 2:[2]
If you are thinking to perform something after widget build, You should use below code:
void initState() {
super.initState();
if (SchedulerBinding.instance.schedulerPhase ==
SchedulerPhase.persistentCallbacks) {
SchedulerBinding.instance.addPostFrameCallback((_) => onWidgetBuild());
}
/// appear
void onWidgetBuild() {
/// This block will be called onWidgetBuild
/// do your code here
}
/// disappear
@override
void dispose() {
super.dispose();
/// release whatever you have consume
}
Hope this will helps you.
Solution 3:[3]
I've had good luck using the focus_detector package. A FocusDetector
widget will need to be placed within the default build()
function and your existing UI code made it's child:
@override
Widget build(BuildContext context) =>
FocusDetector(
onFocusLost: () {
},
onFocusGained: () {
},
onVisibilityLost: () {
},
onVisibilityGained: () {
},
onForegroundLost: () {
},
onForegroundGained: () {
},
// Your previous build code replaces the Container() below
child: Container(),
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mathiew Abbas |
Solution 2 | Uttam Panchasara |
Solution 3 | Jalakoo |