一尘不染

Flutter:更新简历时的小部件吗?

flutter

在Flutter中,当用户离开应用程序并返回到该应用程序时,是否可以更新小部件?我的应用是基于时间的,因此尽快更新时间会很有帮助。


阅读 385

收藏
2020-08-13

共1个答案

一尘不染

您可以通过执行以下操作来监听生命周期事件:

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';

class LifecycleEventHandler extends WidgetsBindingObserver {
  final AsyncCallback resumeCallBack;
  final AsyncCallback suspendingCallBack;

  LifecycleEventHandler({
    this.resumeCallBack,
    this.suspendingCallBack,
  });

  @override
  Future<Null> didChangeAppLifecycleState(AppLifecycleState state) async {
    switch (state) {
      case AppLifecycleState.resumed:
        if (resumeCallBack != null) {
          await resumeCallBack();
        }
        break;
      case AppLifecycleState.inactive:
      case AppLifecycleState.paused:
      case AppLifecycleState.detached:
        if (suspendingCallBack != null) {
          await suspendingCallBack();
        }
        break;
    }
  }
}



class AppWidgetState extends State<AppWidget> {
  void initState() {
    super.initState();

    WidgetsBinding.instance.addObserver(
      LifecycleEventHandler(resumeCallBack: () async => setState(() {
        // do something
      }))
    );
  }
  ...
}
2020-08-13