我想在有状态的小部件中找出整个小部件何时出现在屏幕上或消失,类似于 iOS onViewWillAppear / 消失。这有可能吗?我在 Flutter 文档中没有找到任何相关内容。
谢谢!
您要找的东西就在flutter_widgets包裹里
将以下内容添加到您的pubspec.yaml
flutter_widgets: ^0.1.7+1
这个包里面有一个小部件,称为VisibilityDetector它需要 a key、 achild和一个函数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,
),
),
Run Code Online (Sandbox Code Playgroud)
如果您想在小部件构建后执行某些操作,您应该使用以下代码:
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
}
Run Code Online (Sandbox Code Playgroud)
希望这会对您有所帮助。