Dispose widget when navigating to new route

后端 未结 2 756
离开以前
离开以前 2021-02-13 03:36

I have two screens in my app.

Screen A runs a computationally expensive operation while opened, and properly disposes by cancelling animations/subscriptions to the datab

2条回答
  •  说谎
    说谎 (楼主)
    2021-02-13 04:02

    call Navigator.pushReplacement when routing between first and second screen.

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MaterialApp(
        title: 'Navigation Basics',
        home: FirstRoute(),
      ));
    }
    
    class FirstRoute extends StatefulWidget {
      @override
      _FirstRouteState createState() => _FirstRouteState();
    }
    
    class _FirstRouteState extends State {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('First Route'),
          ),
          body: RaisedButton(
            child: Text('Open route'),
            onPressed: () {
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(builder: (context) => SecondRoute()),
              );
            },
          ),
        );
      }
    
      @override
      void dispose() {
        // Never called
        print("Disposing first route");
        super.dispose();
      }
    }
    
    class SecondRoute extends StatefulWidget {
      @override
      _SecondRouteState createState() => _SecondRouteState();
    }
    
    class _SecondRouteState extends State {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("Second Route"),
          ),
          body: RaisedButton(
            onPressed: () {
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(builder: (context) => FirstRoute()),
              );
            },
            child: Text('Go back!'),
          ),
        );
      }
    
      @override
      void dispose() {
        print("Disposing second route");
        super.dispose();
      }
    }
    

    Try this

提交回复
热议问题