如何在窗口小部件出现/消失时在Flutter中查明?

时间:2019-11-24 06:54:50

标签: flutter dart

我想在有状态的小部件中找出整个小部件出现在屏幕上还是消失,类似于iOS的onViewWillAppear /消失。有可能吗?我在Flutter文档中没有发现任何相关信息。

谢谢!

2 个答案:

答案 0 :(得分:1)

您需要的是flutter_widgets

将以下内容添加到您的pubspec.yaml

flutter_widgets: ^0.1.7+1

此软件包中包含一个名为VisibilityDetector的小部件,它需要一个key,一个child和一个函数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,
   ),
),

答案 1 :(得分:0)

如果您想在小部件构建后执行某些操作,则应使用以下代码:

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
}

希望这会对您有所帮助。