admin管理员组

文章数量:1193728

In flutter, the pop animation is generally the reverse of the push animation. Now I have this requirement, I have a page, and I want it to be displayed in whatever situation, and I want it to pop out and fly down.

I looked at some of the postings and some of them said to use "Navigator.push" instead of pop, but that wouldn't handle the back key to exit the page.

  1. I tried to use PopScope to intercept pop operations and then execute animation manually, but I found that didpop forced true when Navigator.pop was used, the interception failed; In addition, he has another problem, my page is actually a template, PopScope may appear nested situation, the PopScope of the child level even didpop is false can not prevent pop events from passing upward, so this solution is excluded by me;

  2. I tried to replace the original route with an alternate route so that I could apply the pop animation I wanted

Navigator.of(context).replaceRouteBelow(
anchorRoute: ModalRoute.of(context)! ,
newRoute: MetroSlideRoute(
builder: (context) => widget,
),
);

But it doesn't work. I don't know much about the working principle of Navigator. I know that my newRoute must be wrong and I don't know how to improve it.

  1. I tried to read the source code of popscope to manually intercept pop events. When pop occurred, I blocked it first, and then continued after playing my animation. But I failed orz

I would like to ask if there is any good way to solve my problem

My program structure is roughly as follows. I want to capture pop behavior, execute code, and then exit page B

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: PageA(),
    );
  }
}

class PageA extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => PageB()),
            );
          },
          child: Text('Go to B'),
        ),
      ),
    );
  }
}

class PageB extends StatelessWidget {


  async void _preAnimate() {
    // I want to execute this code before popping
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text('Back to A'),
        ),
      ),
    );
  }
}

本文标签: