【Flutter】【widget】返回拦截 WillPopScope


在这里插入图片描述

前言


一、WillPopScope是什么?

返回拦截,作用?

  • 1.在设备点击返回的时候做一个拦截
  • 2.比如在编辑框编辑了内容,不小心点击了返回按键,那么这个时候直接返回就看导致内容的清除,如果这个时候弹出一个窗口,提示用户,给用户选择,这样体验机会好很多

二、使用步骤

1.WillPopScope

代码如下(示例):

WillPopScope(
     onWillPop: () async {
       //回调,future 类型,返回false 就不操作,true 就执行返回
       return false;
     },
     child: const Center(child: Text('I AM TOHER PAGE')),
        )

2. 单纯的点击返回

可以添加一个弹出框,或者你可以自己定义更多的功能
【Flutter】【弹窗】弹窗的快速上手使用和自定义Dialog
代码:

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});


  final String title;

  
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: WillPopScope(
        // 回调函数,返回true 就pop 返回false 就不处理
        onWillPop: () async {
          var result = await showCupertinoDialog(
              context: context,
              builder: (context) {
                return CupertinoAlertDialog(
                    title: const Text('再次点击就退出该页面'),
                    content: const Text('退出会返回到上一个页面'),
                    actions: [
                      CupertinoDialogAction(
                        isDestructiveAction: true,
                        child: const Text('确定'),
                        onPressed: () => Navigator.of(context).pop(true),
                      ),
                      CupertinoDialogAction(
                        isDefaultAction: true,
                        child: const Text('取消'),
                        onPressed: () => Navigator.of(context).pop(false),
                      )
                    ]);
              });
          return result;
        },

        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Text(
                'You have pushed the button this many times:',
              ),
              Text(
                '$_counter',
                style: Theme.of(context).textTheme.headline4,
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

在这里插入图片描述

3.我们经常看到的点击两次返回的情况,我们这样实现

我们在使用软件的时候,经常出现提示连续点击两次就退出的情况,一般是计算两次点击的返回的世界间隔的,如果小于一定的时候就直接退出返回。
在上面代码的基础上,跳转到另外的一个页面,在另外的一个页面上面做返回的处理。

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  void _incrementCounter() {
    // 跳转到other 页面在该页面做返回按键点击的处理
    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
      return OtherPage();
    }));
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: WillPopScope(
        // 回调函数,返回true 就pop 返回false 就不处理
        onWillPop: () async {
          var result = await showCupertinoDialog(
              context: context,
              builder: (context) {
                return CupertinoAlertDialog(
                    title: const Text('再次点击就退出该页面'),
                    content: const Text('退出会返回到上一个页面'),
                    actions: [
                      CupertinoDialogAction(
                        isDestructiveAction: true,
                        child: const Text('确定'),
                        onPressed: () => Navigator.of(context).pop(true),
                      ),
                      CupertinoDialogAction(
                        isDefaultAction: true,
                        child: const Text('取消'),
                        onPressed: () => Navigator.of(context).pop(false),
                      )
                    ]);
              });
          return result;
        },

        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Text(
                'You have pushed the button this many times:',
              ),
              Text(
                'jump to other page',
                style: Theme.of(context).textTheme.headline4,
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'jump to other page',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

class OtherPage extends StatelessWidget {
  OtherPage({Key? key}) : super(key: key);
  DateTime? firstTime;

  
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('hello,jack ma!'),
        ),
        body: WillPopScope(
          onWillPop: () async {
            //如果时间是空的就把新的时间给firstTime
            if (firstTime == null) {
              firstTime = DateTime.now();
            } else {
              if (DateTime.now().difference(firstTime!) <
                  const Duration(milliseconds: 600)) {
                return true;
              } else {
                // 如果两次的间隔时间大于600毫秒的话,就重新赋值给firstTime
                firstTime = DateTime.now();
              }
            }

            return false;
          },
          child: const Center(child: Text('I AM TOHER PAGE')),
        ));
  }
}


总结

欢迎关注,留言,咨询,交流!
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值