1// Copyright 2014 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5import 'package:flutter/material.dart';
6
7/// Flutter code sample for [RouteObserver].
8
9final RouteObserver<ModalRoute<void>> routeObserver = RouteObserver<ModalRoute<void>>();
10
11void main() {
12 runApp(const RouteObserverApp());
13}
14
15class RouteObserverApp extends StatelessWidget {
16 const RouteObserverApp({super.key});
17
18 @override
19 Widget build(BuildContext context) {
20 return MaterialApp(
21 navigatorObservers: <NavigatorObserver>[routeObserver],
22 home: const RouteObserverExample(),
23 );
24 }
25}
26
27class RouteObserverExample extends StatefulWidget {
28 const RouteObserverExample({super.key});
29
30 @override
31 State<RouteObserverExample> createState() => _RouteObserverExampleState();
32}
33
34class _RouteObserverExampleState extends State<RouteObserverExample> with RouteAware {
35 List<String> log = <String>[];
36
37 @override
38 void didChangeDependencies() {
39 super.didChangeDependencies();
40 routeObserver.subscribe(this, ModalRoute.of(context)!);
41 }
42
43 @override
44 void dispose() {
45 routeObserver.unsubscribe(this);
46 super.dispose();
47 }
48
49 @override
50 void didPush() {
51 // Route was pushed onto navigator and is now the topmost route.
52 log.add('didPush');
53 }
54
55 @override
56 void didPopNext() {
57 // Covering route was popped off the navigator.
58 log.add('didPopNext');
59 }
60
61 @override
62 Widget build(BuildContext context) {
63 return Scaffold(
64 body: Center(
65 child: Column(
66 mainAxisSize: MainAxisSize.min,
67 children: <Widget>[
68 Text('RouteObserver log:', style: Theme.of(context).textTheme.headlineSmall),
69 ConstrainedBox(
70 constraints: const BoxConstraints(maxHeight: 300.0),
71 child: ListView.builder(
72 itemCount: log.length,
73 itemBuilder: (BuildContext context, int index) {
74 if (log.isEmpty) {
75 return const SizedBox.shrink();
76 }
77 return Text(log[index], textAlign: TextAlign.center);
78 },
79 ),
80 ),
81 OutlinedButton(
82 onPressed: () {
83 Navigator.of(context).push<void>(
84 MaterialPageRoute<void>(builder: (BuildContext context) => const NextPage()),
85 );
86 },
87 child: const Text('Go to next page'),
88 ),
89 ],
90 ),
91 ),
92 );
93 }
94}
95
96class NextPage extends StatelessWidget {
97 const NextPage({super.key});
98
99 @override
100 Widget build(BuildContext context) {
101 return Scaffold(
102 body: Center(
103 child: FilledButton(
104 onPressed: () {
105 Navigator.of(context).pop();
106 },
107 child: const Text('Go back to RouteAware page'),
108 ),
109 ),
110 );
111 }
112}
113

Provided by KDAB

Privacy Policy
Learn more about Flutter for embedded and desktop on industrialflutter.com