Flutter 中的 Android LiveData 相当于什么?

Ton*_*Joe 7 flutter android-livedata

Android 的 LiveData 允许在 Activity 处于活动状态时更新 UI。因此,如果在 Activity 暂停时后台操作已完成,则不会通知该 Activity,因此应用程序不会崩溃。Flutter 可以执行相同的行为吗?

Dan*_*lva 12

对于对其他场景的 LiveData 等价物感兴趣的人,我向您展示 StreamController:

class ExampleViewModel {

  StreamController<bool> loggedInStream = StreamController<bool>();

  logIn() { loggedInStream.add(true); }
}


class ExampleScreen extends StatefulWidget {

  @override
  State<StatefulWidget> createState() => ExampleScreenState();
}

class ExampleScreenState extends State<ExampleScreen> {

  ExampleViewModel _viewModel;
  BuildContext _ctx;

  @override
  void initState() {
    super.initState();

    _viewModel = ExampleViewModel()
    _viewModel.loggedInStream.stream.listen( (loggedIn) {
      if ( loggedIn != null && loggedIn ) {
        Navigator.of(_ctx).pushReplacementNamed("/home");
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    _ctx = context;

    var loginBtn =
    RaisedButton(
      onPressed: _viewModel.logIn(true),
        child: Text(
          "LOGIN",
          style: new TextStyle(
          fontSize: 24.0,
        )
      ),
      color: Colors.green,
      textColor: Colors.white,
    );

    return loginBtn;
  }

  @override
  void dispose() {
    super.dispose();
    _viewModel.loggedInStream.close();
  }

}
Run Code Online (Sandbox Code Playgroud)

您可以像订阅 LiveData 一样订阅它,使用:

loggedInStream.stream.listen( (data) { code } )
Run Code Online (Sandbox Code Playgroud)

您应该清除 dispose 中的侦听器以避免内存泄漏:

loggedInStream.close()
Run Code Online (Sandbox Code Playgroud)

这段代码主要做了以下几件事:

  1. 创建一个带有按钮的屏幕。
  2. 收听流(观察 LiveData)。
  3. 当您单击按钮时,它会更改值。
  4. 监听器(观察者)被触发。
  5. 启动新屏幕。


Rém*_*let 5

您可以使用WidgetsBindingObserver来监听应用程序状态。

class AppLifecycleReactor extends StatefulWidget {
  const AppLifecycleReactor({ Key key }) : super(key: key);

  @override
  _AppLifecycleReactorState createState() => new _AppLifecycleReactorState();
}

class _AppLifecycleReactorState extends State<AppLifecycleReactor> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  AppLifecycleState _notification;

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    setState(() { _notification = state; });
  }

  @override
  Widget build(BuildContext context) {
    return new Text('Last notification: $_notification');
  }
}
Run Code Online (Sandbox Code Playgroud)