Android 导航返回拦截(WillPopScope)处理

287 阅读1分钟
import 'package:flutter/material.dart';

class TestRoute extends StatefulWidget {
  @override
  _TestRouteState createState() => _TestRouteState();
}

class _TestRouteState extends State<TestRoute> {

  DateTime _lastTime;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if(_lastTime == null || DateTime.now().difference(_lastTime) > Duration(seconds: 1)) {
          _lastTime = DateTime.now();
          return false;
        }
        return true;
      },
      child: Container(
        color: Colors.yellow,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            FlatButton(
              child: Text("退出"),
            )
          ],
        ),
      ),
    );
  }
}