Martin Schultz
Martin Schultz

Reputation: 2861

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!

Upvotes: 7

Views: 7394

Answers (3)

Jalakoo
Jalakoo

Reputation: 3583

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(),
    );

Upvotes: 1

Mathiew Abbas
Mathiew Abbas

Reputation: 853

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,
   ),
),

Upvotes: 6

Uttam Panchasara
Uttam Panchasara

Reputation: 5865

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.

Upvotes: 6

Related Questions