Flutter-WillPopScope

可以拦截内部child的返回事件,其中onWillPop返回Future<bool>,如果是false,就不会出栈,如果true就会出栈。

例子:

import 'dart:core';

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

import 'package:flutter/widgets.dart';


main() => runApp(MyApp());


class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Material(
        child: WillPopScopeTestRoute(),
      ),
    );
  }
}


class WillPopScopeTestRoute extends StatefulWidget {
  @override
  WillPopScopeTestRouteState createState() {
    return new WillPopScopeTestRouteState();
  }
}

class WillPopScopeTestRouteState extends State<WillPopScopeTestRoute> {
  DateTime _lastPressedAt; //上次点击时间

  @override
  Widget build(BuildContext context) {
    return new WillPopScope(
        onWillPop: () async {
          return false;
        },
        child: Container(
          alignment: Alignment.center,
          child: Text("1秒内连续按两次返回键退出"),
        )
    );
  }
}

当然也可以不简单的返回true或false。比如如果用户短时间内点击了两次返回,就退出。如果只点一次或者两次点击相隔事件过长不退出。

原文地址:https://www.cnblogs.com/FdWzy/p/13608766.html