Flutter WillPopScope 拦截路由返回

Posted ajanuw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flutter WillPopScope 拦截路由返回相关的知识,希望对你有一定的参考价值。

典型应用是如果用户尝试退出表单,则警告用户有关未保存的表单数据。连按两次返回键退出APP。

工作示例

import 'dart:async';

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: '/',
      routes: {
        '/': (context) => HomePage(),
      },
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Timer _closeTimer;
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (_closeTimer?.isActive ?? false) {
          return true;
        }
        Toast.show(
          "再次点击退出app",
          context,
          duration: Toast.LENGTH_SHORT,
          gravity: Toast.BOTTOM,
        );
        _closeTimer = Timer(Duration(milliseconds: 1000), null);
        return false;
      },
      child: Scaffold(
        appBar: AppBar(
          title: Text('Home Page'),
        ),
        body: Center(
          child: Text('home page'),
        ),
      ),
    );
  }
}

以上是关于Flutter WillPopScope 拦截路由返回的主要内容,如果未能解决你的问题,请参考以下文章

Flutter中WillPopScope导航返回拦截

Flutter 功能型组件:WillPopScope

Flutter中如何使用WillPopScope

Flutter中如何使用WillPopScope

Flutter学习 功能型Widget

Flutter学习 功能型Widget