Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out in Flutter when a Widget appears / disappears?

Tags:

flutter

dart

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!

like image 476
Martin Schultz Avatar asked Dec 31 '22 11:12

Martin Schultz


2 Answers

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,
   ),
),
like image 116
Mathiew Abbas Avatar answered May 23 '23 21:05

Mathiew Abbas


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.

like image 44
Uttam Panchasara Avatar answered May 23 '23 21:05

Uttam Panchasara