1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:developer' as developer;
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'basic.dart';
import 'binding.dart';
import 'focus_manager.dart';
import 'focus_scope.dart';
import 'framework.dart';
import 'heroes.dart';
import 'overlay.dart';
import 'restoration.dart';
import 'restoration_properties.dart';
import 'routes.dart';
import 'ticker_provider.dart';
// Examples can assume:
// class MyPage extends Placeholder { const MyPage({Key? key}) : super(key: key); }
// class MyHomePage extends Placeholder { const MyHomePage({Key? key}) : super(key: key); }
// late NavigatorState navigator;
// late BuildContext context;
/// Creates a route for the given route settings.
///
/// Used by [Navigator.onGenerateRoute].
///
/// See also:
///
/// * [Navigator], which is where all the [Route]s end up.
typedef RouteFactory = Route<dynamic>? Function(RouteSettings settings);
/// Creates a series of one or more routes.
///
/// Used by [Navigator.onGenerateInitialRoutes].
typedef RouteListFactory = List<Route<dynamic>> Function(NavigatorState navigator, String initialRoute);
/// Creates a [Route] that is to be added to a [Navigator].
///
/// The route can be configured with the provided `arguments`. The provided
/// `context` is the `BuildContext` of the [Navigator] to which the route is
/// added.
///
/// Used by the restorable methods of the [Navigator] that add anonymous routes
/// (e.g. [NavigatorState.restorablePush]). For this use case, the
/// [RestorableRouteBuilder] must be static function as the [Navigator] will
/// call it again during state restoration to re-create the route.
typedef RestorableRouteBuilder<T> = Route<T> Function(BuildContext context, Object? arguments);
/// Signature for the [Navigator.popUntil] predicate argument.
typedef RoutePredicate = bool Function(Route<dynamic> route);
/// Signature for a callback that verifies that it's OK to call [Navigator.pop].
///
/// Used by [Form.onWillPop], [ModalRoute.addScopedWillPopCallback],
/// [ModalRoute.removeScopedWillPopCallback], and [WillPopScope].
typedef WillPopCallback = Future<bool> Function();
/// Signature for the [Navigator.onPopPage] callback.
///
/// This callback must call [Route.didPop] on the specified route and must
/// properly update the pages list the next time it is passed into
/// [Navigator.pages] so that it no longer includes the corresponding [Page].
/// (Otherwise, the page will be interpreted as a new page to show when the
/// [Navigator.pages] list is next updated.)
typedef PopPageCallback = bool Function(Route<dynamic> route, dynamic result);
/// Indicates whether the current route should be popped.
///
/// Used as the return value for [Route.willPop].
///
/// See also:
///
/// * [WillPopScope], a widget that hooks into the route's [Route.willPop]
/// mechanism.
enum RoutePopDisposition {
/// Pop the route.
///
/// If [Route.willPop] returns [pop] then the back button will actually pop
/// the current route.
pop,
/// Do not pop the route.
///
/// If [Route.willPop] returns [doNotPop] then the back button will be ignored.
doNotPop,
/// Delegate this to the next level of navigation.
///
/// If [Route.willPop] returns [bubble] then the back button will be handled
/// by the [SystemNavigator], which will usually close the application.
bubble,
}
/// An abstraction for an entry managed by a [Navigator].
///
/// This class defines an abstract interface between the navigator and the
/// "routes" that are pushed on and popped off the navigator. Most routes have
/// visual affordances, which they place in the navigators [Overlay] using one
/// or more [OverlayEntry] objects.
///
/// See [Navigator] for more explanation of how to use a [Route] with
/// navigation, including code examples.
///
/// See [MaterialPageRoute] for a route that replaces the entire screen with a
/// platform-adaptive transition.
///
/// A route can belong to a page if the [settings] are a subclass of [Page]. A
/// page-based route, as opposed to a pageless route, is created from
/// [Page.createRoute] during [Navigator.pages] updates. The page associated
/// with this route may change during the lifetime of the route. If the
/// [Navigator] updates the page of this route, it calls [changedInternalState]
/// to notify the route that the page has been updated.
///
/// The type argument `T` is the route's return type, as used by
/// [currentResult], [popped], and [didPop]. The type `void` may be used if the
/// route does not return a value.
abstract class Route<T> {
/// Initialize the [Route].
///
/// If the [settings] are not provided, an empty [RouteSettings] object is
/// used instead.
Route({ RouteSettings? settings }) : _settings = settings ?? const RouteSettings();
/// The navigator that the route is in, if any.
NavigatorState? get navigator => _navigator;
NavigatorState? _navigator;
/// The settings for this route.
///
/// See [RouteSettings] for details.
///
/// The settings can change during the route's lifetime. If the settings
/// change, the route's overlays will be marked dirty (see
/// [changedInternalState]).
///
/// If the route is created from a [Page] in the [Navigator.pages] list, then
/// this will be a [Page] subclass, and it will be updated each time its
/// corresponding [Page] in the [Navigator.pages] has changed. Once the
/// [Route] is removed from the history, this value stops updating (and
/// remains with its last value).
RouteSettings get settings => _settings;
RouteSettings _settings;
/// The restoration scope ID to be used for the [RestorationScope] surrounding
/// this route.
///
/// The restoration scope ID is null if restoration is currently disabled
/// for this route.
///
/// If the restoration scope ID changes (e.g. because restoration is enabled
/// or disabled) during the life of the route, the [ValueListenable] notifies
/// its listeners. As an example, the ID changes to null while the route is
/// transitioning off screen, which triggers a notification on this field. At
/// that point, the route is considered as no longer present for restoration
/// purposes and its state will not be restored.
ValueListenable<String?> get restorationScopeId => _restorationScopeId;
final ValueNotifier<String?> _restorationScopeId = ValueNotifier<String?>(null);
void _updateSettings(RouteSettings newSettings) {
assert(newSettings != null);
if (_settings != newSettings) {
_settings = newSettings;
changedInternalState();
}
}
void _updateRestorationId(String? restorationId) {
_restorationScopeId.value = restorationId;
}
/// The overlay entries of this route.
///
/// These are typically populated by [install]. The [Navigator] is in charge
/// of adding them to and removing them from the [Overlay].
///
/// There must be at least one entry in this list after [install] has been
/// invoked.
///
/// The [Navigator] will take care of keeping the entries together if the
/// route is moved in the history.
List<OverlayEntry> get overlayEntries => const <OverlayEntry>[];
/// Called when the route is inserted into the navigator.
///
/// Uses this to populate [overlayEntries]. There must be at least one entry in
/// this list after [install] has been invoked. The [Navigator] will be in charge
/// to add them to the [Overlay] or remove them from it by calling
/// [OverlayEntry.remove].
@protected
@mustCallSuper
void install() { }
/// Called after [install] when the route is pushed onto the navigator.
///
/// The returned value resolves when the push transition is complete.
///
/// The [didAdd] method will be called instead of [didPush] when the route
/// immediately appears on screen without any push transition.
///
/// The [didChangeNext] and [didChangePrevious] methods are typically called
/// immediately after this method is called.
@protected
@mustCallSuper
TickerFuture didPush() {
return TickerFuture.complete()..then<void>((void _) {
navigator?.focusScopeNode.requestFocus();
});
}
/// Called after [install] when the route is added to the navigator.
///
/// This method is called instead of [didPush] when the route immediately
/// appears on screen without any push transition.
///
/// The [didChangeNext] and [didChangePrevious] methods are typically called
/// immediately after this method is called.
@protected
@mustCallSuper
void didAdd() {
// This TickerFuture serves two purposes. First, we want to make sure
// animations triggered by other operations finish before focusing the
// navigator. Second, navigator.focusScopeNode might acquire more focused
// children in Route.install asynchronously. This TickerFuture will wait for
// it to finish first.
//
// The later case can be found when subclasses manage their own focus scopes.
// For example, ModalRoute create a focus scope in its overlay entries. The
// focused child can only be attached to navigator after initState which
// will be guarded by the asynchronous gap.
TickerFuture.complete().then<void>((void _) {
// The route can be disposed before the ticker future completes. This can
// happen when the navigator is under a TabView that warps from one tab to
// another, non-adjacent tab, with an animation. The TabView reorders its
// children before and after the warping completes, and that causes its
// children to be built and disposed within the same frame. If one of its
// children contains a navigator, the routes in that navigator are also
// added and disposed within that frame.
//
// Since the reference to the navigator will be set to null after it is
// disposed, we have to do a null-safe operation in case that happens
// within the same frame when it is added.
navigator?.focusScopeNode.requestFocus();
});
}
/// Called after [install] when the route replaced another in the navigator.
///
/// The [didChangeNext] and [didChangePrevious] methods are typically called
/// immediately after this method is called.
@protected
@mustCallSuper
void didReplace(Route<dynamic>? oldRoute) { }
/// Returns whether calling [Navigator.maybePop] when this [Route] is current
/// ([isCurrent]) should do anything.
///
/// [Navigator.maybePop] is usually used instead of [Navigator.pop] to handle
/// the system back button.
///
/// By default, if a [Route] is the first route in the history (i.e., if
/// [isFirst]), it reports that pops should be bubbled
/// ([RoutePopDisposition.bubble]). This behavior prevents the user from
/// popping the first route off the history and being stranded at a blank
/// screen; instead, the larger scope is popped (e.g. the application quits,
/// so that the user returns to the previous application).
///
/// In other cases, the default behavior is to accept the pop
/// ([RoutePopDisposition.pop]).
///
/// The third possible value is [RoutePopDisposition.doNotPop], which causes
/// the pop request to be ignored entirely.
///
/// See also:
///
/// * [Form], which provides a [Form.onWillPop] callback that uses this
/// mechanism.
/// * [WillPopScope], another widget that provides a way to intercept the
/// back button.
Future<RoutePopDisposition> willPop() async {
return isFirst ? RoutePopDisposition.bubble : RoutePopDisposition.pop;
}
/// Whether calling [didPop] would return false.
bool get willHandlePopInternally => false;
/// When this route is popped (see [Navigator.pop]) if the result isn't
/// specified or if it's null, this value will be used instead.
///
/// This fallback is implemented by [didComplete]. This value is used if the
/// argument to that method is null.
T? get currentResult => null;
/// A future that completes when this route is popped off the navigator.
///
/// The future completes with the value given to [Navigator.pop], if any, or
/// else the value of [currentResult]. See [didComplete] for more discussion
/// on this topic.
Future<T?> get popped => _popCompleter.future;
final Completer<T?> _popCompleter = Completer<T?>();
/// A request was made to pop this route. If the route can handle it
/// internally (e.g. because it has its own stack of internal state) then
/// return false, otherwise return true (by returning the value of calling
/// `super.didPop`). Returning false will prevent the default behavior of
/// [NavigatorState.pop].
///
/// When this function returns true, the navigator removes this route from
/// the history but does not yet call [dispose]. Instead, it is the route's
/// responsibility to call [NavigatorState.finalizeRoute], which will in turn
/// call [dispose] on the route. This sequence lets the route perform an
/// exit animation (or some other visual effect) after being popped but prior
/// to being disposed.
///
/// This method should call [didComplete] to resolve the [popped] future (and
/// this is all that the default implementation does); routes should not wait
/// for their exit animation to complete before doing so.
///
/// See [popped], [didComplete], and [currentResult] for a discussion of the
/// `result` argument.
@mustCallSuper
bool didPop(T? result) {
didComplete(result);
return true;
}
/// The route was popped or is otherwise being removed somewhat gracefully.
///
/// This is called by [didPop] and in response to
/// [NavigatorState.pushReplacement]. If [didPop] was not called, then the
/// [NavigatorState.finalizeRoute] method must be called immediately, and no exit
/// animation will run.
///
/// The [popped] future is completed by this method. The `result` argument
/// specifies the value that this future is completed with, unless it is null,
/// in which case [currentResult] is used instead.
///
/// This should be called before the pop animation, if any, takes place,
/// though in some cases the animation may be driven by the user before the
/// route is committed to being popped; this can in particular happen with the
/// iOS-style back gesture. See [NavigatorState.didStartUserGesture].
@protected
@mustCallSuper
void didComplete(T? result) {
_popCompleter.complete(result ?? currentResult);
}
/// The given route, which was above this one, has been popped off the
/// navigator.
///
/// This route is now the current route ([isCurrent] is now true), and there
/// is no next route.
@protected
@mustCallSuper
void didPopNext(Route<dynamic> nextRoute) { }
/// This route's next route has changed to the given new route.
///
/// This is called on a route whenever the next route changes for any reason,
/// so long as it is in the history, including when a route is first added to
/// a [Navigator] (e.g. by [Navigator.push]), except for cases when
/// [didPopNext] would be called.
///
/// The `nextRoute` argument will be null if there's no new next route (i.e.
/// if [isCurrent] is true).
@protected
@mustCallSuper
void didChangeNext(Route<dynamic>? nextRoute) { }
/// This route's previous route has changed to the given new route.
///
/// This is called on a route whenever the previous route changes for any
/// reason, so long as it is in the history, except for immediately after the
/// route itself has been pushed (in which case [didPush] or [didReplace] will
/// be called instead).
///
/// The `previousRoute` argument will be null if there's no previous route
/// (i.e. if [isFirst] is true).
@protected
@mustCallSuper
void didChangePrevious(Route<dynamic>? previousRoute) { }
/// Called whenever the internal state of the route has changed.
///
/// This should be called whenever [willHandlePopInternally], [didPop],
/// [ModalRoute.offstage], or other internal state of the route changes value.
/// It is used by [ModalRoute], for example, to report the new information via
/// its inherited widget to any children of the route.
///
/// See also:
///
/// * [changedExternalState], which is called when the [Navigator] has
/// updated in some manner that might affect the routes.
@protected
@mustCallSuper
void changedInternalState() { }
/// Called whenever the [Navigator] has updated in some manner that might
/// affect routes, to indicate that the route may wish to rebuild as well.
///
/// This is called by the [Navigator] whenever the
/// [NavigatorState]'s [State.widget] changes (as in [State.didUpdateWidget]),
/// for example because the [MaterialApp] has been rebuilt. This
/// ensures that routes that directly refer to the state of the
/// widget that built the [MaterialApp] will be notified when that
/// widget rebuilds, since it would otherwise be difficult to notify
/// the routes that state they depend on may have changed.
///
/// It is also called whenever the [Navigator]'s dependencies change
/// (as in [State.didChangeDependencies]). This allows routes to use the
/// [Navigator]'s context ([NavigatorState.context]), for example in
/// [ModalRoute.barrierColor], and update accordingly.
///
/// The [ModalRoute] subclass overrides this to force the barrier
/// overlay to rebuild.
///
/// See also:
///
/// * [changedInternalState], the equivalent but for changes to the internal
/// state of the route.
@protected
@mustCallSuper
void changedExternalState() { }
/// Discards any resources used by the object.
///
/// This method should not remove its [overlayEntries] from the [Overlay]. The
/// object's owner is in charge of doing that.
///
/// After this is called, the object is not in a usable state and should be
/// discarded.
///
/// This method should only be called by the object's owner; typically the
/// [Navigator] owns a route and so will call this method when the route is
/// removed, after which the route is no longer referenced by the navigator.
@mustCallSuper
@protected
void dispose() {
_navigator = null;
}
/// Whether this route is the top-most route on the navigator.
///
/// If this is true, then [isActive] is also true.
bool get isCurrent {
if (_navigator == null)
return false;
final _RouteEntry? currentRouteEntry = _navigator!._history.cast<_RouteEntry?>().lastWhere(
(_RouteEntry? e) => e != null && _RouteEntry.isPresentPredicate(e),
orElse: () => null,
);
if (currentRouteEntry == null)
return false;
return currentRouteEntry.route == this;
}
/// Whether this route is the bottom-most active route on the navigator.
///
/// If [isFirst] and [isCurrent] are both true then this is the only route on
/// the navigator (and [isActive] will also be true).
bool get isFirst {
if (_navigator == null)
return false;
final _RouteEntry? currentRouteEntry = _navigator!._history.cast<_RouteEntry?>().firstWhere(
(_RouteEntry? e) => e != null && _RouteEntry.isPresentPredicate(e),
orElse: () => null,
);
if (currentRouteEntry == null)
return false;
return currentRouteEntry.route == this;
}
/// Whether there is at least one active route underneath this route.
@protected
bool get hasActiveRouteBelow {
if (_navigator == null)
return false;
for (final _RouteEntry entry in _navigator!._history) {
if (entry.route == this)
return false;
if (_RouteEntry.isPresentPredicate(entry))
return true;
}
return false;
}
/// Whether this route is on the navigator.
///
/// If the route is not only active, but also the current route (the top-most
/// route), then [isCurrent] will also be true. If it is the first route (the
/// bottom-most route), then [isFirst] will also be true.
///
/// If a higher route is entirely opaque, then the route will be active but not
/// rendered. It is even possible for the route to be active but for the stateful
/// widgets within the route to not be instantiated. See [ModalRoute.maintainState].
bool get isActive {
if (_navigator == null)
return false;
return _navigator!._history.cast<_RouteEntry?>().firstWhere(
(_RouteEntry? e) => e != null && _RouteEntry.isRoutePredicate(this)(e),
orElse: () => null,
)?.isPresent == true;
}
}
/// Data that might be useful in constructing a [Route].
@immutable
class RouteSettings {
/// Creates data used to construct routes.
const RouteSettings({
this.name,
this.arguments,
});
/// Creates a copy of this route settings object with the given fields
/// replaced with the new values.
RouteSettings copyWith({
String? name,
Object? arguments,
}) {
return RouteSettings(
name: name ?? this.name,
arguments: arguments ?? this.arguments,
);
}
/// The name of the route (e.g., "/settings").
///
/// If null, the route is anonymous.
final String? name;
/// The arguments passed to this route.
///
/// May be used when building the route, e.g. in [Navigator.onGenerateRoute].
final Object? arguments;
@override
String toString() => '${objectRuntimeType(this, 'RouteSettings')}("$name", $arguments)';
}
/// Describes the configuration of a [Route].
///
/// The type argument `T` is the corresponding [Route]'s return type, as
/// used by [Route.currentResult], [Route.popped], and [Route.didPop].
///
/// See also:
///
/// * [Navigator.pages], which accepts a list of [Page]s and updates its routes
/// history.
abstract class Page<T> extends RouteSettings {
/// Creates a page and initializes [key] for subclasses.
///
/// The [arguments] argument must not be null.
const Page({
this.key,
String? name,
Object? arguments,
this.restorationId,
}) : super(name: name, arguments: arguments);
/// The key associated with this page.
///
/// This key will be used for comparing pages in [canUpdate].
final LocalKey? key;
/// Restoration ID to save and restore the state of the [Route] configured by
/// this page.
///
/// If no restoration ID is provided, the [Route] will not restore its state.
///
/// See also:
///
/// * [RestorationManager], which explains how state restoration works in
/// Flutter.
final String? restorationId;
/// Whether this page can be updated with the [other] page.
///
/// Two pages are consider updatable if they have same the [runtimeType] and
/// [key].
bool canUpdate(Page<dynamic> other) {
return other.runtimeType == runtimeType &&
other.key == key;
}
/// Creates the [Route] that corresponds to this page.
///
/// The created [Route] must have its [Route.settings] property set to this [Page].
@factory
Route<T> createRoute(BuildContext context);
@override
String toString() => '${objectRuntimeType(this, 'Page')}("$name", $key, $arguments)';
}
/// An interface for observing the behavior of a [Navigator].
class NavigatorObserver {
/// The navigator that the observer is observing, if any.
NavigatorState? get navigator => _navigator;
NavigatorState? _navigator;
/// The [Navigator] pushed `route`.
///
/// The route immediately below that one, and thus the previously active
/// route, is `previousRoute`.
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) { }
/// The [Navigator] popped `route`.
///
/// The route immediately below that one, and thus the newly active
/// route, is `previousRoute`.
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) { }
/// The [Navigator] removed `route`.
///
/// If only one route is being removed, then the route immediately below
/// that one, if any, is `previousRoute`.
///
/// If multiple routes are being removed, then the route below the
/// bottommost route being removed, if any, is `previousRoute`, and this
/// method will be called once for each removed route, from the topmost route
/// to the bottommost route.
void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) { }
/// The [Navigator] replaced `oldRoute` with `newRoute`.
void didReplace({ Route<dynamic>? newRoute, Route<dynamic>? oldRoute }) { }
/// The [Navigator]'s routes are being moved by a user gesture.
///
/// For example, this is called when an iOS back gesture starts, and is used
/// to disabled hero animations during such interactions.
void didStartUserGesture(Route<dynamic> route, Route<dynamic>? previousRoute) { }
/// User gesture is no longer controlling the [Navigator].
///
/// Paired with an earlier call to [didStartUserGesture].
void didStopUserGesture() { }
}
/// An inherited widget to host a hero controller.
///
/// The hosted hero controller will be picked up by the navigator in the
/// [child] subtree. Once a navigator picks up this controller, the navigator
/// will bar any navigator below its subtree from receiving this controller.
///
/// The hero controller inside the [HeroControllerScope] can only subscribe to
/// one navigator at a time. An assertion will be thrown if the hero controller
/// subscribes to more than one navigators. This can happen when there are
/// multiple navigators under the same [HeroControllerScope] in parallel.
class HeroControllerScope extends InheritedWidget {
/// Creates a widget to host the input [controller].
const HeroControllerScope({
Key? key,
required HeroController this.controller,
required Widget child,
}) : assert(controller != null),
super(key: key, child: child);
/// Creates a widget to prevent the subtree from receiving the hero controller
/// above.
const HeroControllerScope.none({
Key? key,
required Widget child,
}) : controller = null,
super(key: key, child: child);
/// The hero controller that is hosted inside this widget.
final HeroController? controller;
/// Retrieves the [HeroController] from the closest [HeroControllerScope]
/// ancestor.
static HeroController? of(BuildContext context) {
final HeroControllerScope? host = context.dependOnInheritedWidgetOfExactType<HeroControllerScope>();
return host?.controller;
}
@override
bool updateShouldNotify(HeroControllerScope oldWidget) {
return oldWidget.controller != controller;
}
}
/// A [Route] wrapper interface that can be staged for [TransitionDelegate] to
/// decide how its underlying [Route] should transition on or off screen.
abstract class RouteTransitionRecord {
/// Retrieves the wrapped [Route].
Route<dynamic> get route;
/// Whether this route is waiting for the decision on how to enter the screen.
///
/// If this property is true, this route requires an explicit decision on how
/// to transition into the screen. Such a decision should be made in the
/// [TransitionDelegate.resolve].
bool get isWaitingForEnteringDecision;
/// Whether this route is waiting for the decision on how to exit the screen.
///
/// If this property is true, this route requires an explicit decision on how
/// to transition off the screen. Such a decision should be made in the
/// [TransitionDelegate.resolve].
bool get isWaitingForExitingDecision;
/// Marks the [route] to be pushed with transition.
///
/// During [TransitionDelegate.resolve], this can be called on an entering
/// route (where [RouteTransitionRecord.isWaitingForEnteringDecision] is true) in indicate that the
/// route should be pushed onto the [Navigator] with an animated transition.
void markForPush();
/// Marks the [route] to be added without transition.
///
/// During [TransitionDelegate.resolve], this can be called on an entering
/// route (where [RouteTransitionRecord.isWaitingForEnteringDecision] is true) in indicate that the
/// route should be added onto the [Navigator] without an animated transition.
void markForAdd();
/// Marks the [route] to be popped with transition.
///
/// During [TransitionDelegate.resolve], this can be called on an exiting
/// route to indicate that the route should be popped off the [Navigator] with
/// an animated transition.
void markForPop([dynamic result]);
/// Marks the [route] to be completed without transition.
///
/// During [TransitionDelegate.resolve], this can be called on an exiting
/// route to indicate that the route should be completed with the provided
/// result and removed from the [Navigator] without an animated transition.
void markForComplete([dynamic result]);
/// Marks the [route] to be removed without transition.
///
/// During [TransitionDelegate.resolve], this can be called on an exiting
/// route to indicate that the route should be removed from the [Navigator]
/// without completing and without an animated transition.
void markForRemove();
}
/// The delegate that decides how pages added and removed from [Navigator.pages]
/// transition in or out of the screen.
///
/// This abstract class implements the API to be called by [Navigator] when it
/// requires explicit decisions on how the routes transition on or off the screen.
///
/// To make route transition decisions, subclass must implement [resolve].
///
/// {@tool sample --template=freeform}
/// The following example demonstrates how to implement a subclass that always
/// removes or adds routes without animated transitions and puts the removed
/// routes at the top of the list.
///
/// ** See code in examples/api/lib/widgets/navigator/transition_delegate.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [Navigator.transitionDelegate], which uses this class to make route
/// transition decisions.
/// * [DefaultTransitionDelegate], which implements the default way to decide
/// how routes transition in or out of the screen.
abstract class TransitionDelegate<T> {
/// Creates a delegate and enables subclass to create a constant class.
const TransitionDelegate();
Iterable<RouteTransitionRecord> _transition({
required List<RouteTransitionRecord> newPageRouteHistory,
required Map<RouteTransitionRecord?, RouteTransitionRecord> locationToExitingPageRoute,
required Map<RouteTransitionRecord?, List<RouteTransitionRecord>> pageRouteToPagelessRoutes,
}) {
final Iterable<RouteTransitionRecord> results = resolve(
newPageRouteHistory: newPageRouteHistory,
locationToExitingPageRoute: locationToExitingPageRoute,
pageRouteToPagelessRoutes: pageRouteToPagelessRoutes,
);
// Verifies the integrity after the decisions have been made.
//
// Here are the rules:
// - All the entering routes in newPageRouteHistory must either be pushed or
// added.
// - All the exiting routes in locationToExitingPageRoute must either be
// popped, completed or removed.
// - All the pageless routes that belong to exiting routes must either be
// popped, completed or removed.
// - All the entering routes in the result must preserve the same order as
// the entering routes in newPageRouteHistory, and the result must contain
// all exiting routes.
// ex:
//
// newPageRouteHistory = [A, B, C]
//
// locationToExitingPageRoute = {A -> D, C -> E}
//
// results = [A, B ,C ,D ,E] is valid
// results = [D, A, B ,C ,E] is also valid because exiting route can be
// inserted in any place
//
// results = [B, A, C ,D ,E] is invalid because B must be after A.
// results = [A, B, C ,E] is invalid because results must include D.
assert(() {
final List<RouteTransitionRecord> resultsToVerify = results.toList(growable: false);
final Set<RouteTransitionRecord> exitingPageRoutes = locationToExitingPageRoute.values.toSet();
// Firstly, verifies all exiting routes have been marked.
for (final RouteTransitionRecord exitingPageRoute in exitingPageRoutes) {
assert(!exitingPageRoute.isWaitingForExitingDecision);
if (pageRouteToPagelessRoutes.containsKey(exitingPageRoute)) {
for (final RouteTransitionRecord pagelessRoute in pageRouteToPagelessRoutes[exitingPageRoute]!) {
assert(!pagelessRoute.isWaitingForExitingDecision);
}
}
}
// Secondly, verifies the order of results matches the newPageRouteHistory
// and contains all the exiting routes.
int indexOfNextRouteInNewHistory = 0;
for (final _RouteEntry routeEntry in resultsToVerify.cast<_RouteEntry>()) {
assert(routeEntry != null);
assert(!routeEntry.isWaitingForEnteringDecision && !routeEntry.isWaitingForExitingDecision);
if (
indexOfNextRouteInNewHistory >= newPageRouteHistory.length ||
routeEntry != newPageRouteHistory[indexOfNextRouteInNewHistory]
) {
assert(exitingPageRoutes.contains(routeEntry));
exitingPageRoutes.remove(routeEntry);
} else {
indexOfNextRouteInNewHistory += 1;
}
}
assert(
indexOfNextRouteInNewHistory == newPageRouteHistory.length &&
exitingPageRoutes.isEmpty,
'The merged result from the $runtimeType.resolve does not include all '
'required routes. Do you remember to merge all exiting routes?',
);
return true;
}());
return results;
}
/// A method that will be called by the [Navigator] to decide how routes
/// transition in or out of the screen when [Navigator.pages] is updated.
///
/// The `newPageRouteHistory` list contains all page-based routes in the order
/// that will be on the [Navigator]'s history stack after this update
/// completes. If a route in `newPageRouteHistory` has its
/// [RouteTransitionRecord.isWaitingForEnteringDecision] set to true, this
/// route requires explicit decision on how it should transition onto the
/// Navigator. To make a decision, call [RouteTransitionRecord.markForPush] or
/// [RouteTransitionRecord.markForAdd].
///
/// The `locationToExitingPageRoute` contains the pages-based routes that
/// are removed from the routes history after page update. This map records
/// page-based routes to be removed with the location of the route in the
/// original route history before the update. The keys are the locations
/// represented by the page-based routes that are directly below the removed
/// routes, and the value are the page-based routes to be removed. The
/// location is null if the route to be removed is the bottom most route. If
/// a route in `locationToExitingPageRoute` has its
/// [RouteTransitionRecord.isWaitingForExitingDecision] set to true, this
/// route requires explicit decision on how it should transition off the
/// Navigator. To make a decision for a removed route, call
/// [RouteTransitionRecord.markForPop],
/// [RouteTransitionRecord.markForComplete] or
/// [RouteTransitionRecord.markForRemove]. It is possible that decisions are
/// not required for routes in the `locationToExitingPageRoute`. This can
/// happen if the routes have already been popped in earlier page updates and
/// are still waiting for popping animations to finish. In such case, those
/// routes are still included in the `locationToExitingPageRoute` with their
/// [RouteTransitionRecord.isWaitingForExitingDecision] set to false and no
/// decisions are required.
///
/// The `pageRouteToPagelessRoutes` records the page-based routes and their
/// associated pageless routes. If a page-based route is waiting for exiting
/// decision, its associated pageless routes also require explicit decisions
/// on how to transition off the screen.
///
/// Once all the decisions have been made, this method must merge the removed
/// routes (whether or not they require decisions) and the
/// `newPageRouteHistory` and return the merged result. The order in the
/// result will be the order the [Navigator] uses for updating the route
/// history. The return list must preserve the same order of routes in
/// `newPageRouteHistory`. The removed routes, however, can be inserted into
/// the return list freely as long as all of them are included.
///
/// For example, consider the following case.
///
/// `newPageRouteHistory = [A, B, C]`
///
/// `locationToExitingPageRoute = {A -> D, C -> E}`
///
/// The following outputs are valid.
///
/// `result = [A, B ,C ,D ,E]` is valid.
/// `result = [D, A, B ,C ,E]` is also valid because exiting route can be
/// inserted in any place.
///
/// The following outputs are invalid.
///
/// `result = [B, A, C ,D ,E]` is invalid because B must be after A.
/// `result = [A, B, C ,E]` is invalid because results must include D.
///
/// See also:
///
/// * [RouteTransitionRecord.markForPush], which makes route enter the screen
/// with an animated transition.
/// * [RouteTransitionRecord.markForAdd], which makes route enter the screen
/// without an animated transition.
/// * [RouteTransitionRecord.markForPop], which makes route exit the screen
/// with an animated transition.
/// * [RouteTransitionRecord.markForRemove], which does not complete the
/// route and makes it exit the screen without an animated transition.
/// * [RouteTransitionRecord.markForComplete], which completes the route and
/// makes it exit the screen without an animated transition.
/// * [DefaultTransitionDelegate.resolve], which implements the default way
/// to decide how routes transition in or out of the screen.
Iterable<RouteTransitionRecord> resolve({
required List<RouteTransitionRecord> newPageRouteHistory,
required Map<RouteTransitionRecord?, RouteTransitionRecord> locationToExitingPageRoute,
required Map<RouteTransitionRecord?, List<RouteTransitionRecord>> pageRouteToPagelessRoutes,
});
}
/// The default implementation of [TransitionDelegate] that the [Navigator] will
/// use if its [Navigator.transitionDelegate] is not specified.
///
/// This transition delegate follows two rules. Firstly, all the entering routes
/// are placed on top of the exiting routes if they are at the same location.
/// Secondly, the top most route will always transition with an animated transition.
/// All the other routes below will either be completed with
/// [Route.currentResult] or added without an animated transition.
class DefaultTransitionDelegate<T> extends TransitionDelegate<T> {
/// Creates a default transition delegate.
const DefaultTransitionDelegate() : super();
@override
Iterable<RouteTransitionRecord> resolve({
required List<RouteTransitionRecord> newPageRouteHistory,
required Map<RouteTransitionRecord?, RouteTransitionRecord> locationToExitingPageRoute,
required Map<RouteTransitionRecord?, List<RouteTransitionRecord>> pageRouteToPagelessRoutes,
}) {
final List<RouteTransitionRecord> results = <RouteTransitionRecord>[];
// This method will handle the exiting route and its corresponding pageless
// route at this location. It will also recursively check if there is any
// other exiting routes above it and handle them accordingly.
void handleExitingRoute(RouteTransitionRecord? location, bool isLast) {
final RouteTransitionRecord? exitingPageRoute = locationToExitingPageRoute[location];
if (exitingPageRoute == null)
return;
if (exitingPageRoute.isWaitingForExitingDecision) {
final bool hasPagelessRoute = pageRouteToPagelessRoutes.containsKey(exitingPageRoute);
final bool isLastExitingPageRoute = isLast && !locationToExitingPageRoute.containsKey(exitingPageRoute);
if (isLastExitingPageRoute && !hasPagelessRoute) {
exitingPageRoute.markForPop(exitingPageRoute.route.currentResult);
} else {
exitingPageRoute.markForComplete(exitingPageRoute.route.currentResult);
}
if (hasPagelessRoute) {
final List<RouteTransitionRecord> pagelessRoutes = pageRouteToPagelessRoutes[exitingPageRoute]!;
for (final RouteTransitionRecord pagelessRoute in pagelessRoutes) {
// It is possible that a pageless route that belongs to an exiting
// page-based route does not require exiting decision. This can
// happen if the page list is updated right after a Navigator.pop.
if (pagelessRoute.isWaitingForExitingDecision) {
if (isLastExitingPageRoute && pagelessRoute == pagelessRoutes.last) {
pagelessRoute.markForPop(pagelessRoute.route.currentResult);
} else {
pagelessRoute.markForComplete(pagelessRoute.route.currentResult);
}
}
}
}
}
results.add(exitingPageRoute);
// It is possible there is another exiting route above this exitingPageRoute.
handleExitingRoute(exitingPageRoute, isLast);
}
// Handles exiting route in the beginning of list.
handleExitingRoute(null, newPageRouteHistory.isEmpty);
for (final RouteTransitionRecord pageRoute in newPageRouteHistory) {
final bool isLastIteration = newPageRouteHistory.last == pageRoute;
if (pageRoute.isWaitingForEnteringDecision) {
if (!locationToExitingPageRoute.containsKey(pageRoute) && isLastIteration) {
pageRoute.markForPush();
} else {
pageRoute.markForAdd();
}
}
results.add(pageRoute);
handleExitingRoute(pageRoute, isLastIteration);
}
return results;
}
}
/// A widget that manages a set of child widgets with a stack discipline.
///
/// Many apps have a navigator near the top of their widget hierarchy in order
/// to display their logical history using an [Overlay] with the most recently
/// visited pages visually on top of the older pages. Using this pattern lets
/// the navigator visually transition from one page to another by moving the widgets
/// around in the overlay. Similarly, the navigator can be used to show a dialog
/// by positioning the dialog widget above the current page.
///
/// ## Using the Navigator API
///
/// Mobile apps typically reveal their contents via full-screen elements
/// called "screens" or "pages". In Flutter these elements are called
/// routes and they're managed by a [Navigator] widget. The navigator
/// manages a stack of [Route] objects and provides two ways for managing
/// the stack, the declarative API [Navigator.pages] or imperative API
/// [Navigator.push] and [Navigator.pop].
///
/// When your user interface fits this paradigm of a stack, where the user
/// should be able to _navigate_ back to an earlier element in the stack,
/// the use of routes and the Navigator is appropriate. On certain platforms,
/// such as Android, the system UI will provide a back button (outside the
/// bounds of your application) that will allow the user to navigate back
/// to earlier routes in your application's stack. On platforms that don't
/// have this build-in navigation mechanism, the use of an [AppBar] (typically
/// used in the [Scaffold.appBar] property) can automatically add a back
/// button for user navigation.
///
/// ## Using the Pages API
///
/// The [Navigator] will convert its [Navigator.pages] into a stack of [Route]s
/// if it is provided. A change in [Navigator.pages] will trigger an update to
/// the stack of [Route]s. The [Navigator] will update its routes to match the
/// new configuration of its [Navigator.pages]. To use this API, one can create
/// a [Page] subclass and defines a list of [Page]s for [Navigator.pages]. A
/// [Navigator.onPopPage] callback is also required to properly clean up the
/// input pages in case of a pop.
///
/// By Default, the [Navigator] will use [DefaultTransitionDelegate] to decide
/// how routes transition in or out of the screen. To customize it, define a
/// [TransitionDelegate] subclass and provide it to the
/// [Navigator.transitionDelegate].
///
/// ### Displaying a full-screen route
///
/// Although you can create a navigator directly, it's most common to use the
/// navigator created by the `Router` which itself is created and configured by
/// a [WidgetsApp] or a [MaterialApp] widget. You can refer to that navigator
/// with [Navigator.of].
///
/// A [MaterialApp] is the simplest way to set things up. The [MaterialApp]'s
/// home becomes the route at the bottom of the [Navigator]'s stack. It is what
/// you see when the app is launched.
///
/// ```dart
/// void main() {
/// runApp(MaterialApp(home: MyAppHome()));
/// }
/// ```
///
/// To push a new route on the stack you can create an instance of
/// [MaterialPageRoute] with a builder function that creates whatever you
/// want to appear on the screen. For example:
///
/// ```dart
/// Navigator.push(context, MaterialPageRoute<void>(
/// builder: (BuildContext context) {
/// return Scaffold(
/// appBar: AppBar(title: Text('My Page')),
/// body: Center(
/// child: TextButton(
/// child: Text('POP'),
/// onPressed: () {
/// Navigator.pop(context);
/// },
/// ),
/// ),
/// );
/// },
/// ));
/// ```
///
/// The route defines its widget with a builder function instead of a
/// child widget because it will be built and rebuilt in different
/// contexts depending on when it's pushed and popped.
///
/// As you can see, the new route can be popped, revealing the app's home
/// page, with the Navigator's pop method:
///
/// ```dart
/// Navigator.pop(context);
/// ```
///
/// It usually isn't necessary to provide a widget that pops the Navigator
/// in a route with a [Scaffold] because the Scaffold automatically adds a
/// 'back' button to its AppBar. Pressing the back button causes
/// [Navigator.pop] to be called. On Android, pressing the system back
/// button does the same thing.
///
/// ### Using named navigator routes
///
/// Mobile apps often manage a large number of routes and it's often
/// easiest to refer to them by name. Route names, by convention,
/// use a path-like structure (for example, '/a/b/c').
/// The app's home page route is named '/' by default.
///
/// The [MaterialApp] can be created
/// with a [Map<String, WidgetBuilder>] which maps from a route's name to
/// a builder function that will create it. The [MaterialApp] uses this
/// map to create a value for its navigator's [onGenerateRoute] callback.
///
/// ```dart
/// void main() {
/// runApp(MaterialApp(
/// home: MyAppHome(), // becomes the route named '/'
/// routes: <String, WidgetBuilder> {
/// '/a': (BuildContext context) => MyPage(title: 'page A'),
/// '/b': (BuildContext context) => MyPage(title: 'page B'),
/// '/c': (BuildContext context) => MyPage(title: 'page C'),
/// },
/// ));
/// }
/// ```
///
/// To show a route by name:
///
/// ```dart
/// Navigator.pushNamed(context, '/b');
/// ```
///
/// ### Routes can return a value
///
/// When a route is pushed to ask the user for a value, the value can be
/// returned via the [pop] method's result parameter.
///
/// Methods that push a route return a [Future]. The Future resolves when the
/// route is popped and the [Future]'s value is the [pop] method's `result`
/// parameter.
///
/// For example if we wanted to ask the user to press 'OK' to confirm an
/// operation we could `await` the result of [Navigator.push]:
///
/// ```dart
/// bool value = await Navigator.push(context, MaterialPageRoute<bool>(
/// builder: (BuildContext context) {
/// return Center(
/// child: GestureDetector(
/// child: Text('OK'),
/// onTap: () { Navigator.pop(context, true); }
/// ),
/// );
/// }
/// ));
/// ```
///
/// If the user presses 'OK' then value will be true. If the user backs
/// out of the route, for example by pressing the Scaffold's back button,
/// the value will be null.
///
/// When a route is used to return a value, the route's type parameter must
/// match the type of [pop]'s result. That's why we've used
/// `MaterialPageRoute<bool>` instead of `MaterialPageRoute<void>` or just
/// `MaterialPageRoute`. (If you prefer to not specify the types, though, that's
/// fine too.)
///
/// ### Popup routes
///
/// Routes don't have to obscure the entire screen. [PopupRoute]s cover the
/// screen with a [ModalRoute.barrierColor] that can be only partially opaque to
/// allow the current screen to show through. Popup routes are "modal" because
/// they block input to the widgets below.
///
/// There are functions which create and show popup routes. For
/// example: [showDialog], [showMenu], and [showModalBottomSheet]. These
/// functions return their pushed route's Future as described above.
/// Callers can await the returned value to take an action when the
/// route is popped, or to discover the route's value.
///
/// There are also widgets which create popup routes, like [PopupMenuButton] and
/// [DropdownButton]. These widgets create internal subclasses of PopupRoute
/// and use the Navigator's push and pop methods to show and dismiss them.
///
/// ### Custom routes
///
/// You can create your own subclass of one of the widget library route classes
/// like [PopupRoute], [ModalRoute], or [PageRoute], to control the animated
/// transition employed to show the route, the color and behavior of the route's
/// modal barrier, and other aspects of the route.
///
/// The [PageRouteBuilder] class makes it possible to define a custom route
/// in terms of callbacks. Here's an example that rotates and fades its child
/// when the route appears or disappears. This route does not obscure the entire
/// screen because it specifies `opaque: false`, just as a popup route does.
///
/// ```dart
/// Navigator.push(context, PageRouteBuilder(
/// opaque: false,
/// pageBuilder: (BuildContext context, _, __) {
/// return Center(child: Text('My PageRoute'));
/// },
/// transitionsBuilder: (___, Animation<double> animation, ____, Widget child) {
/// return FadeTransition(
/// opacity: animation,
/// child: RotationTransition(
/// turns: Tween<double>(begin: 0.5, end: 1.0).animate(animation),
/// child: child,
/// ),
/// );
/// }
/// ));
/// ```
///
/// The page route is built in two parts, the "page" and the
/// "transitions". The page becomes a descendant of the child passed to
/// the `transitionsBuilder` function. Typically the page is only built once,
/// because it doesn't depend on its animation parameters (elided with `_`
/// and `__` in this example). The transition is built on every frame
/// for its duration.
///
/// ### Nesting Navigators
///
/// An app can use more than one [Navigator]. Nesting one [Navigator] below
/// another [Navigator] can be used to create an "inner journey" such as tabbed
/// navigation, user registration, store checkout, or other independent journeys
/// that represent a subsection of your overall application.
///
/// #### Example
///
/// It is standard practice for iOS apps to use tabbed navigation where each
/// tab maintains its own navigation history. Therefore, each tab has its own
/// [Navigator], creating a kind of "parallel navigation."
///
/// In addition to the parallel navigation of the tabs, it is still possible to
/// launch full-screen pages that completely cover the tabs. For example: an
/// on-boarding flow, or an alert dialog. Therefore, there must exist a "root"
/// [Navigator] that sits above the tab navigation. As a result, each of the
/// tab's [Navigator]s are actually nested [Navigator]s sitting below a single
/// root [Navigator].
///
/// In practice, the nested [Navigator]s for tabbed navigation sit in the
/// [WidgetsApp] and [CupertinoTabView] widgets and do not need to be explicitly
/// created or managed.
///
/// {@tool sample --template=freeform}
/// The following example demonstrates how a nested [Navigator] can be used to
/// present a standalone user registration journey.
///
/// Even though this example uses two [Navigator]s to demonstrate nested
/// [Navigator]s, a similar result is possible using only a single [Navigator].
///
/// Run this example with `flutter run --route=/signup` to start it with
/// the signup flow instead of on the home page.
///
/// ** See code in examples/api/lib/widgets/navigator/navigator.0.dart **
/// {@end-tool}
///
/// [Navigator.of] operates on the nearest ancestor [Navigator] from the given
/// [BuildContext]. Be sure to provide a [BuildContext] below the intended
/// [Navigator], especially in large `build` methods where nested [Navigator]s
/// are created. The [Builder] widget can be used to access a [BuildContext] at
/// a desired location in the widget subtree.
///
/// ## State Restoration
///
/// If provided with a [restorationScopeId] and when surrounded by a valid
/// [RestorationScope] the [Navigator] will restore its state by recreating
/// the current history stack of [Route]s during state restoration and by
/// restoring the internal state of those [Route]s. However, not all [Route]s
/// on the stack can be restored:
///
/// * [Page]-based routes restore their state if [Page.restorationId] is
/// provided.
/// * [Route]s added with the classic imperative API ([push], [pushNamed], and
/// friends) can never restore their state.
/// * A [Route] added with the restorable imperative API ([restorablePush],
/// [restorablePushNamed], and all other imperative methods with "restorable"
/// in their name) restores its state if all routes below it up to and
/// including the first [Page]-based route below it are restored. If there
/// is no [Page]-based route below it, it only restores its state if all
/// routes below it restore theirs.
///
/// If a [Route] is deemed restorable, the [Navigator] will set its
/// [Route.restorationScopeId] to a non-null value. Routes can use that ID to
/// store and restore their own state. As an example, the [ModalRoute] will
/// use this ID to create a [RestorationScope] for its content widgets.
class Navigator extends StatefulWidget {
/// Creates a widget that maintains a stack-based history of child widgets.
///
/// The [onGenerateRoute], [pages], [onGenerateInitialRoutes],
/// [transitionDelegate], [observers] arguments must not be null.
///
/// If the [pages] is not empty, the [onPopPage] must not be null.
const Navigator({
Key? key,
this.pages = const <Page<dynamic>>[],
this.onPopPage,
this.initialRoute,
this.onGenerateInitialRoutes = Navigator.defaultGenerateInitialRoutes,
this.onGenerateRoute,
this.onUnknownRoute,
this.transitionDelegate = const DefaultTransitionDelegate<dynamic>(),
this.reportsRouteUpdateToEngine = false,
this.observers = const <NavigatorObserver>[],
this.restorationScopeId,
}) : assert(pages != null),
assert(onGenerateInitialRoutes != null),
assert(transitionDelegate != null),
assert(observers != null),
assert(reportsRouteUpdateToEngine != null),
super(key: key);
/// The list of pages with which to populate the history.
///
/// Pages are turned into routes using [Page.createRoute] in a manner
/// analogous to how [Widget]s are turned into [Element]s (and [State]s or
/// [RenderObject]s) using [Widget.createElement] (and
/// [StatefulWidget.createState] or [RenderObjectWidget.createRenderObject]).
///
/// When this list is updated, the new list is compared to the previous
/// list and the set of routes is updated accordingly.
///
/// Some [Route]s do not correspond to [Page] objects, namely, those that are
/// added to the history using the [Navigator] API ([push] and friends). A
/// [Route] that does not correspond to a [Page] object is called a pageless
/// route and is tied to the [Route] that _does_ correspond to a [Page] object
/// that is below it in the history.
///
/// Pages that are added or removed may be animated as controlled by the
/// [transitionDelegate]. If a page is removed that had other pageless routes
/// pushed on top of it using [push] and friends, those pageless routes are
/// also removed with or without animation as determined by the
/// [transitionDelegate].
///
/// To use this API, an [onPopPage] callback must also be provided to properly
/// clean up this list if a page has been popped.
///
/// If [initialRoute] is non-null when the widget is first created, then
/// [onGenerateInitialRoutes] is used to generate routes that are above those
/// corresponding to [pages] in the initial history.
final List<Page<dynamic>> pages;
/// Called when [pop] is invoked but the current [Route] corresponds to a
/// [Page] found in the [pages] list.
///
/// The `result` argument is the value with which the route is to complete
/// (e.g. the value returned from a dialog).
///
/// This callback is responsible for calling [Route.didPop] and returning
/// whether this pop is successful.
///
/// The [Navigator] widget should be rebuilt with a [pages] list that does not
/// contain the [Page] for the given [Route]. The next time the [pages] list
/// is updated, if the [Page] corresponding to this [Route] is still present,
/// it will be interpreted as a new route to display.
final PopPageCallback? onPopPage;
/// The delegate used for deciding how routes transition in or off the screen
/// during the [pages] updates.
///
/// Defaults to [DefaultTransitionDelegate] if not specified, cannot be null.
final TransitionDelegate<dynamic> transitionDelegate;
/// The name of the first route to show.
///
/// Defaults to [Navigator.defaultRouteName].
///
/// The value is interpreted according to [onGenerateInitialRoutes], which
/// defaults to [defaultGenerateInitialRoutes].
final String? initialRoute;
/// Called to generate a route for a given [RouteSettings].
final RouteFactory? onGenerateRoute;
/// Called when [onGenerateRoute] fails to generate a route.
///
/// This callback is typically used for error handling. For example, this
/// callback might always generate a "not found" page that describes the route
/// that wasn't found.
///
/// Unknown routes can arise either from errors in the app or from external
/// requests to push routes, such as from Android intents.
final RouteFactory? onUnknownRoute;
/// A list of observers for this navigator.
final List<NavigatorObserver> observers;
/// Restoration ID to save and restore the state of the navigator, including
/// its history.
///
/// {@template flutter.widgets.navigator.restorationScopeId}
/// If a restoration ID is provided, the navigator will persist its internal
/// state (including the route history as well as the restorable state of the
/// routes) and restore it during state restoration.
///
/// If no restoration ID is provided, the route history stack will not be
/// restored and state restoration is disabled for the individual routes as
/// well.
///
/// The state is persisted in a [RestorationBucket] claimed from
/// the surrounding [RestorationScope] using the provided restoration ID.
/// Within that bucket, the [Navigator] also creates a new [RestorationScope]
/// for its children (the [Route]s).
///
/// See also:
///
/// * [RestorationManager], which explains how state restoration works in
/// Flutter.
/// * [RestorationMixin], which contains a runnable code sample showcasing
/// state restoration in Flutter.
/// * [Navigator], which explains under the heading "state restoration"
/// how and under what conditions the navigator restores its state.
/// * [Navigator.restorablePush], which includes an example showcasing how
/// to push a restorable route unto the navigator.
/// {@endtemplate}
final String? restorationScopeId;
/// The name for the default route of the application.
///
/// See also:
///
/// * [dart:ui.PlatformDispatcher.defaultRouteName], which reflects the route that the
/// application was started with.
static const String defaultRouteName = '/';
/// Called when the widget is created to generate the initial list of [Route]
/// objects if [initialRoute] is not null.
///
/// Defaults to [defaultGenerateInitialRoutes].
///
/// The [NavigatorState] and [initialRoute] will be passed to the callback.
/// The callback must return a list of [Route] objects with which the history
/// will be primed.
///
/// When parsing the initialRoute, if there's any chance that the it may
/// contain complex characters, it's best to use the
/// [characters](https://pub.dev/packages/characters) API. This will ensure
/// that extended grapheme clusters and surrogate pairs are treated as single
/// characters by the code, the same way that they appear to the user. For
/// example, the string "👨👩👦" appears to the user as a single
/// character and `string.characters.length` intuitively returns 1. On the
/// other hand, `string.length` returns 8, and `string.runes.length` returns
/// 5!
final RouteListFactory onGenerateInitialRoutes;
/// Whether this navigator should report route update message back to the
/// engine when the top-most route changes.
///
/// If the property is set to true, this navigator automatically sends the
/// route update message to the engine when it detects top-most route changes.
/// The messages are used by the web engine to update the browser URL bar.
///
/// If the property is set to true when the [Navigator] is first created,
/// single-entry history mode is requested using
/// [SystemNavigator.selectSingleEntryHistory]. This means this property
/// should not be used at the same time as [PlatformRouteInformationProvider]
/// is used with a [Router] (including when used with [MaterialApp.router],
/// for example).
///
/// If there are multiple navigators in the widget tree, at most one of them
/// can set this property to true (typically, the top-most one created from
/// the [WidgetsApp]). Otherwise, the web engine may receive multiple route
/// update messages from different navigators and fail to update the URL
/// bar.
///
/// Defaults to false.
final bool reportsRouteUpdateToEngine;
/// Push a named route onto the navigator that most tightly encloses the given
/// context.
///
/// {@template flutter.widgets.navigator.pushNamed}
/// The route name will be passed to the [Navigator.onGenerateRoute]
/// callback. The returned route will be pushed into the navigator.
///
/// The new route and the previous route (if any) are notified (see
/// [Route.didPush] and [Route.didChangeNext]). If the [Navigator] has any
/// [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didPush]).
///
/// Ongoing gestures within the current route are canceled when a new route is
/// pushed.
///
/// Returns a [Future] that completes to the `result` value passed to [pop]
/// when the pushed route is popped off the navigator.
///
/// The `T` type argument is the type of the return value of the route.
///
/// To use [pushNamed], an [Navigator.onGenerateRoute] callback must be
/// provided,
/// {@endtemplate}
///
/// {@template flutter.widgets.Navigator.pushNamed}
/// The provided `arguments` are passed to the pushed route via
/// [RouteSettings.arguments]. Any object can be passed as `arguments` (e.g. a
/// [String], [int], or an instance of a custom `MyRouteArguments` class).
/// Often, a [Map] is used to pass key-value pairs.
///
/// The `arguments` may be used in [Navigator.onGenerateRoute] or
/// [Navigator.onUnknownRoute] to construct the route.
/// {@endtemplate}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _didPushButton() {
/// Navigator.pushNamed(context, '/settings');
/// }
/// ```
/// {@end-tool}
///
/// {@tool snippet}
///
/// The following example shows how to pass additional `arguments` to the
/// route:
///
/// ```dart
/// void _showBerlinWeather() {
/// Navigator.pushNamed(
/// context,
/// '/weather',
/// arguments: <String, String>{
/// 'city': 'Berlin',
/// 'country': 'Germany',
/// },
/// );
/// }
/// ```
/// {@end-tool}
///
/// {@tool snippet}
///
/// The following example shows how to pass a custom Object to the route:
///
/// ```dart
/// class WeatherRouteArguments {
/// WeatherRouteArguments({ required this.city, required this.country });
/// final String city;
/// final String country;
///
/// bool get isGermanCapital {
/// return country == 'Germany' && city == 'Berlin';
/// }
/// }
///
/// void _showWeather() {
/// Navigator.pushNamed(
/// context,
/// '/weather',
/// arguments: WeatherRouteArguments(city: 'Berlin', country: 'Germany'),
/// );
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePushNamed], which pushes a route that can be restored
/// during state restoration.
@optionalTypeArgs
static Future<T?> pushNamed<T extends Object?>(
BuildContext context,
String routeName, {
Object? arguments,
}) {
return Navigator.of(context).pushNamed<T>(routeName, arguments: arguments);
}
/// Push a named route onto the navigator that most tightly encloses the given
/// context.
///
/// {@template flutter.widgets.navigator.restorablePushNamed}
/// Unlike [Route]s pushed via [pushNamed], [Route]s pushed with this method
/// are restored during state restoration according to the rules outlined
/// in the "State Restoration" section of [Navigator].
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.pushNamed}
///
/// {@template flutter.widgets.Navigator.restorablePushNamed.arguments}
/// The provided `arguments` are passed to the pushed route via
/// [RouteSettings.arguments]. Any object that is serializable via the
/// [StandardMessageCodec] can be passed as `arguments`. Often, a Map is used
/// to pass key-value pairs.
///
/// The arguments may be used in [Navigator.onGenerateRoute] or
/// [Navigator.onUnknownRoute] to construct the route.
/// {@endtemplate}
///
/// {@template flutter.widgets.Navigator.restorablePushNamed.returnValue}
/// The method returns an opaque ID for the pushed route that can be used by
/// the [RestorableRouteFuture] to gain access to the actual [Route] object
/// added to the navigator and its return value. You can ignore the return
/// value of this method, if you do not care about the route object or the
/// route's return value.
/// {@endtemplate}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _showParisWeather() {
/// Navigator.restorablePushNamed(
/// context,
/// '/weather',
/// arguments: <String, String>{
/// 'city': 'Paris',
/// 'country': 'France',
/// },
/// );
/// }
/// ```
/// {@end-tool}
@optionalTypeArgs
static String restorablePushNamed<T extends Object?>(
BuildContext context,
String routeName, {
Object? arguments,
}) {
return Navigator.of(context).restorablePushNamed<T>(routeName, arguments: arguments);
}
/// Replace the current route of the navigator that most tightly encloses the
/// given context by pushing the route named [routeName] and then disposing
/// the previous route once the new route has finished animating in.
///
/// {@template flutter.widgets.navigator.pushReplacementNamed}
/// If non-null, `result` will be used as the result of the route that is
/// removed; the future that had been returned from pushing that old route
/// will complete with `result`. Routes such as dialogs or popup menus
/// typically use this mechanism to return the value selected by the user to
/// the widget that created their route. The type of `result`, if provided,
/// must match the type argument of the class of the old route (`TO`).
///
/// The route name will be passed to the [Navigator.onGenerateRoute]
/// callback. The returned route will be pushed into the navigator.
///
/// The new route and the route below the removed route are notified (see
/// [Route.didPush] and [Route.didChangeNext]). If the [Navigator] has any
/// [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didReplace]). The removed route is notified once the
/// new route has finished animating (see [Route.didComplete]). The removed
/// route's exit animation is not run (see [popAndPushNamed] for a variant
/// that does animated the removed route).
///
/// Ongoing gestures within the current route are canceled when a new route is
/// pushed.
///
/// Returns a [Future] that completes to the `result` value passed to [pop]
/// when the pushed route is popped off the navigator.
///
/// The `T` type argument is the type of the return value of the new route,
/// and `TO` is the type of the return value of the old route.
///
/// To use [pushReplacementNamed], a [Navigator.onGenerateRoute] callback must
/// be provided.
/// {@endtemplate}
///
/// {@macro flutter.widgets.Navigator.pushNamed}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _switchToBrightness() {
/// Navigator.pushReplacementNamed(context, '/settings/brightness');
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePushReplacementNamed], which pushes a replacement route that
/// can be restored during state restoration.
@optionalTypeArgs
static Future<T?> pushReplacementNamed<T extends Object?, TO extends Object?>(
BuildContext context,
String routeName, {
TO? result,
Object? arguments,
}) {
return Navigator.of(context).pushReplacementNamed<T, TO>(routeName, arguments: arguments, result: result);
}
/// Replace the current route of the navigator that most tightly encloses the
/// given context by pushing the route named [routeName] and then disposing
/// the previous route once the new route has finished animating in.
///
/// {@template flutter.widgets.navigator.restorablePushReplacementNamed}
/// Unlike [Route]s pushed via [pushReplacementNamed], [Route]s pushed with
/// this method are restored during state restoration according to the rules
/// outlined in the "State Restoration" section of [Navigator].
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.pushReplacementNamed}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.arguments}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _switchToAudioVolume() {
/// Navigator.restorablePushReplacementNamed(context, '/settings/volume');
/// }
/// ```
/// {@end-tool}
@optionalTypeArgs
static String restorablePushReplacementNamed<T extends Object?, TO extends Object?>(
BuildContext context,
String routeName, {
TO? result,
Object? arguments,
}) {
return Navigator.of(context).restorablePushReplacementNamed<T, TO>(routeName, arguments: arguments, result: result);
}
/// Pop the current route off the navigator that most tightly encloses the
/// given context and push a named route in its place.
///
/// {@template flutter.widgets.navigator.popAndPushNamed}
/// The popping of the previous route is handled as per [pop].
///
/// The new route's name will be passed to the [Navigator.onGenerateRoute]
/// callback. The returned route will be pushed into the navigator.
///
/// The new route, the old route, and the route below the old route (if any)
/// are all notified (see [Route.didPop], [Route.didComplete],
/// [Route.didPopNext], [Route.didPush], and [Route.didChangeNext]). If the
/// [Navigator] has any [Navigator.observers], they will be notified as well
/// (see [NavigatorObserver.didPop] and [NavigatorObserver.didPush]). The
/// animations for the pop and the push are performed simultaneously, so the
/// route below may be briefly visible even if both the old route and the new
/// route are opaque (see [TransitionRoute.opaque]).
///
/// Ongoing gestures within the current route are canceled when a new route is
/// pushed.
///
/// Returns a [Future] that completes to the `result` value passed to [pop]
/// when the pushed route is popped off the navigator.
///
/// The `T` type argument is the type of the return value of the new route,
/// and `TO` is the return value type of the old route.
///
/// To use [popAndPushNamed], a [Navigator.onGenerateRoute] callback must be provided.
///
/// {@endtemplate}
///
/// {@macro flutter.widgets.Navigator.pushNamed}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _selectAccessibility() {
/// Navigator.popAndPushNamed(context, '/settings/accessibility');
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePopAndPushNamed], which pushes a new route that can be
/// restored during state restoration.
@optionalTypeArgs
static Future<T?> popAndPushNamed<T extends Object?, TO extends Object?>(
BuildContext context,
String routeName, {
TO? result,
Object? arguments,
}) {
return Navigator.of(context).popAndPushNamed<T, TO>(routeName, arguments: arguments, result: result);
}
/// Pop the current route off the navigator that most tightly encloses the
/// given context and push a named route in its place.
///
/// {@template flutter.widgets.navigator.restorablePopAndPushNamed}
/// Unlike [Route]s pushed via [popAndPushNamed], [Route]s pushed with
/// this method are restored during state restoration according to the rules
/// outlined in the "State Restoration" section of [Navigator].
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.popAndPushNamed}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.arguments}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _selectNetwork() {
/// Navigator.restorablePopAndPushNamed(context, '/settings/network');
/// }
/// ```
/// {@end-tool}
@optionalTypeArgs
static String restorablePopAndPushNamed<T extends Object?, TO extends Object?>(
BuildContext context,
String routeName, {
TO? result,
Object? arguments,
}) {
return Navigator.of(context).restorablePopAndPushNamed<T, TO>(routeName, arguments: arguments, result: result);
}
/// Push the route with the given name onto the navigator that most tightly
/// encloses the given context, and then remove all the previous routes until
/// the `predicate` returns true.
///
/// {@template flutter.widgets.navigator.pushNamedAndRemoveUntil}
/// The predicate may be applied to the same route more than once if
/// [Route.willHandlePopInternally] is true.
///
/// To remove routes until a route with a certain name, use the
/// [RoutePredicate] returned from [ModalRoute.withName].
///
/// To remove all the routes below the pushed route, use a [RoutePredicate]
/// that always returns false (e.g. `(Route<dynamic> route) => false`).
///
/// The removed routes are removed without being completed, so this method
/// does not take a return value argument.
///
/// The new route's name (`routeName`) will be passed to the
/// [Navigator.onGenerateRoute] callback. The returned route will be pushed
/// into the navigator.
///
/// The new route and the route below the bottommost removed route (which
/// becomes the route below the new route) are notified (see [Route.didPush]
/// and [Route.didChangeNext]). If the [Navigator] has any
/// [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didPush] and [NavigatorObserver.didRemove]). The
/// removed routes are disposed, without being notified, once the new route
/// has finished animating. The futures that had been returned from pushing
/// those routes will not complete.
///
/// Ongoing gestures within the current route are canceled when a new route is
/// pushed.
///
/// Returns a [Future] that completes to the `result` value passed to [pop]
/// when the pushed route is popped off the navigator.
///
/// The `T` type argument is the type of the return value of the new route.
///
/// To use [pushNamedAndRemoveUntil], an [Navigator.onGenerateRoute] callback
/// must be provided.
/// {@endtemplate}
///
/// {@macro flutter.widgets.Navigator.pushNamed}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _resetToCalendar() {
/// Navigator.pushNamedAndRemoveUntil(context, '/calendar', ModalRoute.withName('/'));
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePushNamedAndRemoveUntil], which pushes a new route that can
/// be restored during state restoration.
@optionalTypeArgs
static Future<T?> pushNamedAndRemoveUntil<T extends Object?>(
BuildContext context,
String newRouteName,
RoutePredicate predicate, {
Object? arguments,
}) {
return Navigator.of(context).pushNamedAndRemoveUntil<T>(newRouteName, predicate, arguments: arguments);
}
/// Push the route with the given name onto the navigator that most tightly
/// encloses the given context, and then remove all the previous routes until
/// the `predicate` returns true.
///
/// {@template flutter.widgets.navigator.restorablePushNamedAndRemoveUntil}
/// Unlike [Route]s pushed via [pushNamedAndRemoveUntil], [Route]s pushed with
/// this method are restored during state restoration according to the rules
/// outlined in the "State Restoration" section of [Navigator].
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.pushNamedAndRemoveUntil}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.arguments}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _resetToOverview() {
/// Navigator.restorablePushNamedAndRemoveUntil(context, '/overview', ModalRoute.withName('/'));
/// }
/// ```
/// {@end-tool}
@optionalTypeArgs
static String restorablePushNamedAndRemoveUntil<T extends Object?>(
BuildContext context,
String newRouteName,
RoutePredicate predicate, {
Object? arguments,
}) {
return Navigator.of(context).restorablePushNamedAndRemoveUntil<T>(newRouteName, predicate, arguments: arguments);
}
/// Push the given route onto the navigator that most tightly encloses the
/// given context.
///
/// {@template flutter.widgets.navigator.push}
/// The new route and the previous route (if any) are notified (see
/// [Route.didPush] and [Route.didChangeNext]). If the [Navigator] has any
/// [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didPush]).
///
/// Ongoing gestures within the current route are canceled when a new route is
/// pushed.
///
/// Returns a [Future] that completes to the `result` value passed to [pop]
/// when the pushed route is popped off the navigator.
///
/// The `T` type argument is the type of the return value of the route.
/// {@endtemplate}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _openMyPage() {
/// Navigator.push<void>(
/// context,
/// MaterialPageRoute<void>(
/// builder: (BuildContext context) => const MyPage(),
/// ),
/// );
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePush], which pushes a route that can be restored during
/// state restoration.
@optionalTypeArgs
static Future<T?> push<T extends Object?>(BuildContext context, Route<T> route) {
return Navigator.of(context).push(route);
}
/// Push a new route onto the navigator that most tightly encloses the
/// given context.
///
/// {@template flutter.widgets.navigator.restorablePush}
/// Unlike [Route]s pushed via [push], [Route]s pushed with this method are
/// restored during state restoration according to the rules outlined in the
/// "State Restoration" section of [Navigator].
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.push}
///
/// {@template flutter.widgets.Navigator.restorablePush}
/// The method takes a _static_ [RestorableRouteBuilder] as argument, which
/// must instantiate and return a new [Route] object that will be added to
/// the navigator. The provided `arguments` object is passed to the
/// `routeBuilder`. The navigator calls the static `routeBuilder` function
/// again during state restoration to re-create the route object.
///
/// Any object that is serializable via the [StandardMessageCodec] can be
/// passed as `arguments`. Often, a Map is used to pass key-value pairs.
/// {@endtemplate}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool dartpad --template=stateful_widget_material}
/// Typical usage is as follows:
///
/// ** See code in examples/api/lib/widgets/navigator/navigator.restorable_push.0.dart **
/// {@end-tool}
@optionalTypeArgs
static String restorablePush<T extends Object?>(BuildContext context, RestorableRouteBuilder<T> routeBuilder, {Object? arguments}) {
return Navigator.of(context).restorablePush(routeBuilder, arguments: arguments);
}
/// Replace the current route of the navigator that most tightly encloses the
/// given context by pushing the given route and then disposing the previous
/// route once the new route has finished animating in.
///
/// {@template flutter.widgets.navigator.pushReplacement}
/// If non-null, `result` will be used as the result of the route that is
/// removed; the future that had been returned from pushing that old route will
/// complete with `result`. Routes such as dialogs or popup menus typically
/// use this mechanism to return the value selected by the user to the widget
/// that created their route. The type of `result`, if provided, must match
/// the type argument of the class of the old route (`TO`).
///
/// The new route and the route below the removed route are notified (see
/// [Route.didPush] and [Route.didChangeNext]). If the [Navigator] has any
/// [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didReplace]). The removed route is notified once the
/// new route has finished animating (see [Route.didComplete]).
///
/// Ongoing gestures within the current route are canceled when a new route is
/// pushed.
///
/// Returns a [Future] that completes to the `result` value passed to [pop]
/// when the pushed route is popped off the navigator.
///
/// The `T` type argument is the type of the return value of the new route,
/// and `TO` is the type of the return value of the old route.
/// {@endtemplate}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _completeLogin() {
/// Navigator.pushReplacement<void, void>(
/// context,
/// MaterialPageRoute<void>(
/// builder: (BuildContext context) => const MyHomePage(),
/// ),
/// );
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePushReplacement], which pushes a replacement route that can
/// be restored during state restoration.
@optionalTypeArgs
static Future<T?> pushReplacement<T extends Object?, TO extends Object?>(BuildContext context, Route<T> newRoute, { TO? result }) {
return Navigator.of(context).pushReplacement<T, TO>(newRoute, result: result);
}
/// Replace the current route of the navigator that most tightly encloses the
/// given context by pushing a new route and then disposing the previous
/// route once the new route has finished animating in.
///
/// {@template flutter.widgets.navigator.restorablePushReplacement}
/// Unlike [Route]s pushed via [pushReplacement], [Route]s pushed with this
/// method are restored during state restoration according to the rules
/// outlined in the "State Restoration" section of [Navigator].
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.pushReplacement}
///
/// {@macro flutter.widgets.Navigator.restorablePush}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool dartpad --template=stateful_widget_material}
/// Typical usage is as follows:
///
/// ** See code in examples/api/lib/widgets/navigator/navigator.restorable_push_replacement.0.dart **
/// {@end-tool}
@optionalTypeArgs
static String restorablePushReplacement<T extends Object?, TO extends Object?>(BuildContext context, RestorableRouteBuilder<T> routeBuilder, { TO? result, Object? arguments }) {
return Navigator.of(context).restorablePushReplacement<T, TO>(routeBuilder, result: result, arguments: arguments);
}
/// Push the given route onto the navigator that most tightly encloses the
/// given context, and then remove all the previous routes until the
/// `predicate` returns true.
///
/// {@template flutter.widgets.navigator.pushAndRemoveUntil}
/// The predicate may be applied to the same route more than once if
/// [Route.willHandlePopInternally] is true.
///
/// To remove routes until a route with a certain name, use the
/// [RoutePredicate] returned from [ModalRoute.withName].
///
/// To remove all the routes below the pushed route, use a [RoutePredicate]
/// that always returns false (e.g. `(Route<dynamic> route) => false`).
///
/// The removed routes are removed without being completed, so this method
/// does not take a return value argument.
///
/// The newly pushed route and its preceding route are notified for
/// [Route.didPush]. After removal, the new route and its new preceding route,
/// (the route below the bottommost removed route) are notified through
/// [Route.didChangeNext]). If the [Navigator] has any [Navigator.observers],
/// they will be notified as well (see [NavigatorObserver.didPush] and
/// [NavigatorObserver.didRemove]). The removed routes are disposed of and
/// notified, once the new route has finished animating. The futures that had
/// been returned from pushing those routes will not complete.
///
/// Ongoing gestures within the current route are canceled when a new route is
/// pushed.
///
/// Returns a [Future] that completes to the `result` value passed to [pop]
/// when the pushed route is popped off the navigator.
///
/// The `T` type argument is the type of the return value of the new route.
/// {@endtemplate}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _finishAccountCreation() {
/// Navigator.pushAndRemoveUntil<void>(
/// context,
/// MaterialPageRoute<void>(builder: (BuildContext context) => const MyHomePage()),
/// ModalRoute.withName('/'),
/// );
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePushAndRemoveUntil], which pushes a route that can be
/// restored during state restoration.
@optionalTypeArgs
static Future<T?> pushAndRemoveUntil<T extends Object?>(BuildContext context, Route<T> newRoute, RoutePredicate predicate) {
return Navigator.of(context).pushAndRemoveUntil<T>(newRoute, predicate);
}
/// Push a new route onto the navigator that most tightly encloses the
/// given context, and then remove all the previous routes until the
/// `predicate` returns true.
///
/// {@template flutter.widgets.navigator.restorablePushAndRemoveUntil}
/// Unlike [Route]s pushed via [pushAndRemoveUntil], [Route]s pushed with this
/// method are restored during state restoration according to the rules
/// outlined in the "State Restoration" section of [Navigator].
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.pushAndRemoveUntil}
///
/// {@macro flutter.widgets.Navigator.restorablePush}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool dartpad --template=stateful_widget_material}
/// Typical usage is as follows:
///
/// ** See code in examples/api/lib/widgets/navigator/navigator.restorable_push_and_remove_until.0.dart **
/// {@end-tool}
@optionalTypeArgs
static String restorablePushAndRemoveUntil<T extends Object?>(BuildContext context, RestorableRouteBuilder<T> newRouteBuilder, RoutePredicate predicate, {Object? arguments}) {
return Navigator.of(context).restorablePushAndRemoveUntil<T>(newRouteBuilder, predicate, arguments: arguments);
}
/// Replaces a route on the navigator that most tightly encloses the given
/// context with a new route.
///
/// {@template flutter.widgets.navigator.replace}
/// The old route must not be currently visible, as this method skips the
/// animations and therefore the removal would be jarring if it was visible.
/// To replace the top-most route, consider [pushReplacement] instead, which
/// _does_ animate the new route, and delays removing the old route until the
/// new route has finished animating.
///
/// The removed route is removed without being completed, so this method does
/// not take a return value argument.
///
/// The new route, the route below the new route (if any), and the route above
/// the new route, are all notified (see [Route.didReplace],
/// [Route.didChangeNext], and [Route.didChangePrevious]). If the [Navigator]
/// has any [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didReplace]). The removed route is disposed without
/// being notified. The future that had been returned from pushing that routes
/// will not complete.
///
/// This can be useful in combination with [removeRouteBelow] when building a
/// non-linear user experience.
///
/// The `T` type argument is the type of the return value of the new route.
/// {@endtemplate}
///
/// See also:
///
/// * [replaceRouteBelow], which is the same but identifies the route to be
/// removed by reference to the route above it, rather than directly.
/// * [restorableReplace], which adds a replacement route that can be
/// restored during state restoration.
@optionalTypeArgs
static void replace<T extends Object?>(BuildContext context, { required Route<dynamic> oldRoute, required Route<T> newRoute }) {
return Navigator.of(context).replace<T>(oldRoute: oldRoute, newRoute: newRoute);
}
/// Replaces a route on the navigator that most tightly encloses the given
/// context with a new route.
///
/// {@template flutter.widgets.navigator.restorableReplace}
/// Unlike [Route]s added via [replace], [Route]s added with this method are
/// restored during state restoration according to the rules outlined in the
/// "State Restoration" section of [Navigator].
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.replace}
///
/// {@macro flutter.widgets.Navigator.restorablePush}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
@optionalTypeArgs
static String restorableReplace<T extends Object?>(BuildContext context, { required Route<dynamic> oldRoute, required RestorableRouteBuilder<T> newRouteBuilder, Object? arguments }) {
return Navigator.of(context).restorableReplace<T>(oldRoute: oldRoute, newRouteBuilder: newRouteBuilder, arguments: arguments);
}
/// Replaces a route on the navigator that most tightly encloses the given
/// context with a new route. The route to be replaced is the one below the
/// given `anchorRoute`.
///
/// {@template flutter.widgets.navigator.replaceRouteBelow}
/// The old route must not be current visible, as this method skips the
/// animations and therefore the removal would be jarring if it was visible.
/// To replace the top-most route, consider [pushReplacement] instead, which
/// _does_ animate the new route, and delays removing the old route until the
/// new route has finished animating.
///
/// The removed route is removed without being completed, so this method does
/// not take a return value argument.
///
/// The new route, the route below the new route (if any), and the route above
/// the new route, are all notified (see [Route.didReplace],
/// [Route.didChangeNext], and [Route.didChangePrevious]). If the [Navigator]
/// has any [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didReplace]). The removed route is disposed without
/// being notified. The future that had been returned from pushing that routes
/// will not complete.
///
/// The `T` type argument is the type of the return value of the new route.
/// {@endtemplate}
///
/// See also:
///
/// * [replace], which is the same but identifies the route to be removed
/// directly.
/// * [restorableReplaceRouteBelow], which adds a replacement route that can
/// be restored during state restoration.
@optionalTypeArgs
static void replaceRouteBelow<T extends Object?>(BuildContext context, { required Route<dynamic> anchorRoute, required Route<T> newRoute }) {
return Navigator.of(context).replaceRouteBelow<T>(anchorRoute: anchorRoute, newRoute: newRoute);
}
/// Replaces a route on the navigator that most tightly encloses the given
/// context with a new route. The route to be replaced is the one below the
/// given `anchorRoute`.
///
/// {@template flutter.widgets.navigator.restorableReplaceRouteBelow}
/// Unlike [Route]s added via [restorableReplaceRouteBelow], [Route]s added
/// with this method are restored during state restoration according to the
/// rules outlined in the "State Restoration" section of [Navigator].
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.replaceRouteBelow}
///
/// {@macro flutter.widgets.Navigator.restorablePush}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
@optionalTypeArgs
static String restorableReplaceRouteBelow<T extends Object?>(BuildContext context, { required Route<dynamic> anchorRoute, required RestorableRouteBuilder<T> newRouteBuilder, Object? arguments }) {
return Navigator.of(context).restorableReplaceRouteBelow<T>(anchorRoute: anchorRoute, newRouteBuilder: newRouteBuilder, arguments: arguments);
}
/// Whether the navigator that most tightly encloses the given context can be
/// popped.
///
/// {@template flutter.widgets.navigator.canPop}
/// The initial route cannot be popped off the navigator, which implies that
/// this function returns true only if popping the navigator would not remove
/// the initial route.
///
/// If there is no [Navigator] in scope, returns false.
/// {@endtemplate}
///
/// See also:
///
/// * [Route.isFirst], which returns true for routes for which [canPop]
/// returns false.
static bool canPop(BuildContext context) {
final NavigatorState? navigator = Navigator.maybeOf(context);
return navigator != null && navigator.canPop();
}
/// Consults the current route's [Route.willPop] method, and acts accordingly,
/// potentially popping the route as a result; returns whether the pop request
/// should be considered handled.
///
/// {@template flutter.widgets.navigator.maybePop}
/// If [Route.willPop] returns [RoutePopDisposition.pop], then the [pop]
/// method is called, and this method returns true, indicating that it handled
/// the pop request.
///
/// If [Route.willPop] returns [RoutePopDisposition.doNotPop], then this
/// method returns true, but does not do anything beyond that.
///
/// If [Route.willPop] returns [RoutePopDisposition.bubble], then this method
/// returns false, and the caller is responsible for sending the request to
/// the containing scope (e.g. by closing the application).
///
/// This method is typically called for a user-initiated [pop]. For example on
/// Android it's called by the binding for the system's back button.
///
/// The `T` type argument is the type of the return value of the current
/// route. (Typically this isn't known; consider specifying `dynamic` or
/// `Null`.)
/// {@endtemplate}
///
/// See also:
///
/// * [Form], which provides an `onWillPop` callback that enables the form
/// to veto a [pop] initiated by the app's back button.
/// * [ModalRoute], which provides a `scopedWillPopCallback` that can be used
/// to define the route's `willPop` method.
@optionalTypeArgs
static Future<bool> maybePop<T extends Object?>(BuildContext context, [ T? result ]) {
return Navigator.of(context).maybePop<T>(result);
}
/// Pop the top-most route off the navigator that most tightly encloses the
/// given context.
///
/// {@template flutter.widgets.navigator.pop}
/// The current route's [Route.didPop] method is called first. If that method
/// returns false, then the route remains in the [Navigator]'s history (the
/// route is expected to have popped some internal state; see e.g.
/// [LocalHistoryRoute]). Otherwise, the rest of this description applies.
///
/// If non-null, `result` will be used as the result of the route that is
/// popped; the future that had been returned from pushing the popped route
/// will complete with `result`. Routes such as dialogs or popup menus
/// typically use this mechanism to return the value selected by the user to
/// the widget that created their route. The type of `result`, if provided,
/// must match the type argument of the class of the popped route (`T`).
///
/// The popped route and the route below it are notified (see [Route.didPop],
/// [Route.didComplete], and [Route.didPopNext]). If the [Navigator] has any
/// [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didPop]).
///
/// The `T` type argument is the type of the return value of the popped route.
///
/// The type of `result`, if provided, must match the type argument of the
/// class of the popped route (`T`).
/// {@endtemplate}
///
/// {@tool snippet}
///
/// Typical usage for closing a route is as follows:
///
/// ```dart
/// void _close() {
/// Navigator.pop(context);
/// }
/// ```
/// {@end-tool}
///
/// A dialog box might be closed with a result:
///
/// ```dart
/// void _accept() {
/// Navigator.pop(context, true); // dialog returns true
/// }
/// ```
@optionalTypeArgs
static void pop<T extends Object?>(BuildContext context, [ T? result ]) {
Navigator.of(context).pop<T>(result);
}
/// Calls [pop] repeatedly on the navigator that most tightly encloses the
/// given context until the predicate returns true.
///
/// {@template flutter.widgets.navigator.popUntil}
/// The predicate may be applied to the same route more than once if
/// [Route.willHandlePopInternally] is true.
///
/// To pop until a route with a certain name, use the [RoutePredicate]
/// returned from [ModalRoute.withName].
///
/// The routes are closed with null as their `return` value.
///
/// See [pop] for more details of the semantics of popping a route.
/// {@endtemplate}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _logout() {
/// Navigator.popUntil(context, ModalRoute.withName('/login'));
/// }
/// ```
/// {@end-tool}
static void popUntil(BuildContext context, RoutePredicate predicate) {
Navigator.of(context).popUntil(predicate);
}
/// Immediately remove `route` from the navigator that most tightly encloses
/// the given context, and [Route.dispose] it.
///
/// {@template flutter.widgets.navigator.removeRoute}
/// The removed route is removed without being completed, so this method does
/// not take a return value argument. No animations are run as a result of
/// this method call.
///
/// The routes below and above the removed route are notified (see
/// [Route.didChangeNext] and [Route.didChangePrevious]). If the [Navigator]
/// has any [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didRemove]). The removed route is disposed without
/// being notified. The future that had been returned from pushing that routes
/// will not complete.
///
/// The given `route` must be in the history; this method will throw an
/// exception if it is not.
///
/// Ongoing gestures within the current route are canceled.
/// {@endtemplate}
///
/// This method is used, for example, to instantly dismiss dropdown menus that
/// are up when the screen's orientation changes.
static void removeRoute(BuildContext context, Route<dynamic> route) {
return Navigator.of(context).removeRoute(route);
}
/// Immediately remove a route from the navigator that most tightly encloses
/// the given context, and [Route.dispose] it. The route to be removed is the
/// one below the given `anchorRoute`.
///
/// {@template flutter.widgets.navigator.removeRouteBelow}
/// The removed route is removed without being completed, so this method does
/// not take a return value argument. No animations are run as a result of
/// this method call.
///
/// The routes below and above the removed route are notified (see
/// [Route.didChangeNext] and [Route.didChangePrevious]). If the [Navigator]
/// has any [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didRemove]). The removed route is disposed without
/// being notified. The future that had been returned from pushing that routes
/// will not complete.
///
/// The given `anchorRoute` must be in the history and must have a route below
/// it; this method will throw an exception if it is not or does not.
///
/// Ongoing gestures within the current route are canceled.
/// {@endtemplate}
static void removeRouteBelow(BuildContext context, Route<dynamic> anchorRoute) {
return Navigator.of(context).removeRouteBelow(anchorRoute);
}
/// The state from the closest instance of this class that encloses the given
/// context.
///
/// Typical usage is as follows:
///
/// ```dart
/// Navigator.of(context)
/// ..pop()
/// ..pop()
/// ..pushNamed('/settings');
/// ```
///
/// If `rootNavigator` is set to true, the state from the furthest instance of
/// this class is given instead. Useful for pushing contents above all
/// subsequent instances of [Navigator].
///
/// If there is no [Navigator] in the give `context`, this function will throw
/// a [FlutterError] in debug mode, and an exception in release mode.
///
/// This method can be expensive (it walks the element tree).
static NavigatorState of(
BuildContext context, {
bool rootNavigator = false,
}) {
// Handles the case where the input context is a navigator element.
NavigatorState? navigator;
if (context is StatefulElement && context.state is NavigatorState) {
navigator = context.state as NavigatorState;
}
if (rootNavigator) {
navigator = context.findRootAncestorStateOfType<NavigatorState>() ?? navigator;
} else {
navigator = navigator ?? context.findAncestorStateOfType<NavigatorState>();
}
assert(() {
if (navigator == null) {
throw FlutterError(
'Navigator operation requested with a context that does not include a Navigator.\n'
'The context used to push or pop routes from the Navigator must be that of a '
'widget that is a descendant of a Navigator widget.',
);
}
return true;
}());
return navigator!;
}
/// The state from the closest instance of this class that encloses the given
/// context, if any.
///
/// Typical usage is as follows:
///
/// ```dart
/// NavigatorState? navigatorState = Navigator.maybeOf(context);
/// if (navigatorState != null) {
/// navigatorState
/// ..pop()
/// ..pop()
/// ..pushNamed('/settings');
/// }
/// ```
///
/// If `rootNavigator` is set to true, the state from the furthest instance of
/// this class is given instead. Useful for pushing contents above all
/// subsequent instances of [Navigator].
///
/// Will return null if there is no ancestor [Navigator] in the `context`.
///
/// This method can be expensive (it walks the element tree).
static NavigatorState? maybeOf(
BuildContext context, {
bool rootNavigator = false,
}) {
// Handles the case where the input context is a navigator element.
NavigatorState? navigator;
if (context is StatefulElement && context.state is NavigatorState) {
navigator = context.state as NavigatorState;
}
if (rootNavigator) {
navigator = context.findRootAncestorStateOfType<NavigatorState>() ?? navigator;
} else {
navigator = navigator ?? context.findAncestorStateOfType<NavigatorState>();
}
return navigator;
}
/// Turn a route name into a set of [Route] objects.
///
/// This is the default value of [onGenerateInitialRoutes], which is used if
/// [initialRoute] is not null.
///
/// If this string starts with a `/` character and has multiple `/` characters
/// in it, then the string is split on those characters and substrings from
/// the start of the string up to each such character are, in turn, used as
/// routes to push.
///
/// For example, if the route `/stocks/HOOLI` was used as the [initialRoute],
/// then the [Navigator] would push the following routes on startup: `/`,
/// `/stocks`, `/stocks/HOOLI`. This enables deep linking while allowing the
/// application to maintain a predictable route history.
static List<Route<dynamic>> defaultGenerateInitialRoutes(NavigatorState navigator, String initialRouteName) {
final List<Route<dynamic>?> result = <Route<dynamic>?>[];
if (initialRouteName.startsWith('/') && initialRouteName.length > 1) {
initialRouteName = initialRouteName.substring(1); // strip leading '/'
assert(Navigator.defaultRouteName == '/');
List<String>? debugRouteNames;
assert(() {
debugRouteNames = <String>[ Navigator.defaultRouteName ];
return true;
}());
result.add(navigator._routeNamed<dynamic>(Navigator.defaultRouteName, arguments: null, allowNull: true));
final List<String> routeParts = initialRouteName.split('/');
if (initialRouteName.isNotEmpty) {
String routeName = '';
for (final String part in routeParts) {
routeName += '/$part';
assert(() {
debugRouteNames!.add(routeName);
return true;
}());
result.add(navigator._routeNamed<dynamic>(routeName, arguments: null, allowNull: true));
}
}
if (result.last == null) {
assert(() {
FlutterError.reportError(
FlutterErrorDetails(
exception:
'Could not navigate to initial route.\n'
'The requested route name was: "/$initialRouteName"\n'
'There was no corresponding route in the app, and therefore the initial route specified will be '
'ignored and "${Navigator.defaultRouteName}" will be used instead.',
),
);
return true;
}());
result.clear();
}
} else if (initialRouteName != Navigator.defaultRouteName) {
// If initialRouteName wasn't '/', then we try to get it with allowNull:true, so that if that fails,
// we fall back to '/' (without allowNull:true, see below).
result.add(navigator._routeNamed<dynamic>(initialRouteName, arguments: null, allowNull: true));
}
// Null route might be a result of gap in initialRouteName
//
// For example, routes = ['A', 'A/B/C'], and initialRouteName = 'A/B/C'
// This should result in result = ['A', null,'A/B/C'] where 'A/B' produces
// the null. In this case, we want to filter out the null and return
// result = ['A', 'A/B/C'].
result.removeWhere((Route<dynamic>? route) => route == null);
if (result.isEmpty)
result.add(navigator._routeNamed<dynamic>(Navigator.defaultRouteName, arguments: null));
return result.cast<Route<dynamic>>();
}
@override
NavigatorState createState() => NavigatorState();
}
// The _RouteLifecycle state machine (only goes down):
//
// [creation of a _RouteEntry]
// |
// +
// |\
// | \
// | staging
// | /
// |/
// +-+----------+--+-------+
// / | | |
// / | | |
// / | | |
// / | | |
// / | | |
// pushReplace push* add* replace*
// \ | | |
// \ | | /
// +--pushing# adding /
// \ / /
// \ / /
// idle--+-----+
// / \
// / \
// pop* remove*
// / \
// / removing#
// popping# |
// | |
// [finalizeRoute] |
// \ |
// dispose*
// |
// |
// disposed
// |
// |
// [_RouteEntry garbage collected]
// (terminal state)
//
// * These states are transient; as soon as _flushHistoryUpdates is run the
// route entry will exit that state.
// # These states await futures or other events, then transition automatically.
enum _RouteLifecycle {
staging, // we will wait for transition delegate to decide what to do with this route.
//
// routes that are present:
//
add, // we'll want to run install, didAdd, etc; a route created by onGenerateInitialRoutes or by the initial widget.pages
adding, // we'll waiting for the future from didPush of top-most route to complete
// routes that are ready for transition.
push, // we'll want to run install, didPush, etc; a route added via push() and friends
pushReplace, // we'll want to run install, didPush, etc; a route added via pushReplace() and friends
pushing, // we're waiting for the future from didPush to complete
replace, // we'll want to run install, didReplace, etc; a route added via replace() and friends
idle, // route is being harmless
//
// routes that are not present:
//
// routes that should be included in route announcement and should still listen to transition changes.
pop, // we'll want to call didPop
remove, // we'll want to run didReplace/didRemove etc
// routes should not be included in route announcement but should still listen to transition changes.
popping, // we're waiting for the route to call finalizeRoute to switch to dispose
removing, // we are waiting for subsequent routes to be done animating, then will switch to dispose
// routes that are completely removed from the navigator and overlay.
dispose, // we will dispose the route momentarily
disposed, // we have disposed the route
}
typedef _RouteEntryPredicate = bool Function(_RouteEntry entry);
class _NotAnnounced extends Route<void> {
// A placeholder for the lastAnnouncedPreviousRoute, the
// lastAnnouncedPoppedNextRoute, and the lastAnnouncedNextRoute before any
// change has been announced.
}
class _RouteEntry extends RouteTransitionRecord {
_RouteEntry(
this.route, {
required _RouteLifecycle initialState,
this.restorationInformation,
}) : assert(route != null),
assert(initialState != null),
assert(
initialState == _RouteLifecycle.staging ||
initialState == _RouteLifecycle.add ||
initialState == _RouteLifecycle.push ||
initialState == _RouteLifecycle.pushReplace ||
initialState == _RouteLifecycle.replace,
),
currentState = initialState;
@override
final Route<dynamic> route;
final _RestorationInformation? restorationInformation;
static Route<dynamic> notAnnounced = _NotAnnounced();
_RouteLifecycle currentState;
Route<dynamic>? lastAnnouncedPreviousRoute = notAnnounced; // last argument to Route.didChangePrevious
Route<dynamic> lastAnnouncedPoppedNextRoute = notAnnounced; // last argument to Route.didPopNext
Route<dynamic>? lastAnnouncedNextRoute = notAnnounced; // last argument to Route.didChangeNext
/// Restoration ID to be used for the encapsulating route when restoration is
/// enabled for it or null if restoration cannot be enabled for it.
String? get restorationId {
// User-provided restoration ids of Pages are prefixed with 'p+'. Generated
// ids for pageless routes are prefixed with 'r+' to avoid clashes.
if (hasPage) {
final Page<Object?> page = route.settings as Page<Object?>;
return page.restorationId != null ? 'p+${page.restorationId}' : null;
}
if (restorationInformation != null) {
return 'r+${restorationInformation!.restorationScopeId}';
}
return null;
}
bool get hasPage => route.settings is Page;
bool canUpdateFrom(Page<dynamic> page) {
if (currentState.index > _RouteLifecycle.idle.index)
return false;
if (!hasPage)
return false;
final Page<dynamic> routePage = route.settings as Page<dynamic>;
return page.canUpdate(routePage);
}
void handleAdd({ required NavigatorState navigator, required Route<dynamic>? previousPresent }) {
assert(currentState == _RouteLifecycle.add);
assert(navigator != null);
assert(navigator._debugLocked);
assert(route._navigator == null);
route._navigator = navigator;
route.install();
assert(route.overlayEntries.isNotEmpty);
currentState = _RouteLifecycle.adding;
navigator._observedRouteAdditions.add(
_NavigatorPushObservation(route, previousPresent),
);
}
void handlePush({ required NavigatorState navigator, required bool isNewFirst, required Route<dynamic>? previous, required Route<dynamic>? previousPresent }) {
assert(currentState == _RouteLifecycle.push || currentState == _RouteLifecycle.pushReplace || currentState == _RouteLifecycle.replace);
assert(navigator != null);
assert(navigator._debugLocked);
assert(
route._navigator == null,
'The pushed route has already been used. When pushing a route, a new '
'Route object must be provided.',
);
final _RouteLifecycle previousState = currentState;
route._navigator = navigator;
route.install();
assert(route.overlayEntries.isNotEmpty);
if (currentState == _RouteLifecycle.push || currentState == _RouteLifecycle.pushReplace) {
final TickerFuture routeFuture = route.didPush();
currentState = _RouteLifecycle.pushing;
routeFuture.whenCompleteOrCancel(() {
if (currentState == _RouteLifecycle.pushing) {
currentState = _RouteLifecycle.idle;
assert(!navigator._debugLocked);
assert(() { navigator._debugLocked = true; return true; }());
navigator._flushHistoryUpdates();
assert(() { navigator._debugLocked = false; return true; }());
}
});
} else {
assert(currentState == _RouteLifecycle.replace);
route.didReplace(previous);
currentState = _RouteLifecycle.idle;
}
if (isNewFirst) {
route.didChangeNext(null);
}
if (previousState == _RouteLifecycle.replace || previousState == _RouteLifecycle.pushReplace) {
navigator._observedRouteAdditions.add(
_NavigatorReplaceObservation(route, previousPresent),
);
} else {
assert(previousState == _RouteLifecycle.push);
navigator._observedRouteAdditions.add(
_NavigatorPushObservation(route, previousPresent),
);
}
}
void handleDidPopNext(Route<dynamic> poppedRoute) {
route.didPopNext(poppedRoute);
lastAnnouncedPoppedNextRoute = poppedRoute;
}
void handlePop({ required NavigatorState navigator, required Route<dynamic>? previousPresent }) {
assert(navigator != null);
assert(navigator._debugLocked);
assert(route._navigator == navigator);
currentState = _RouteLifecycle.popping;
navigator._observedRouteDeletions.add(
_NavigatorPopObservation(route, previousPresent),
);
}
void handleRemoval({ required NavigatorState navigator, required Route<dynamic>? previousPresent }) {
assert(navigator != null);
assert(navigator._debugLocked);
assert(route._navigator == navigator);
currentState = _RouteLifecycle.removing;
if (_reportRemovalToObserver) {
navigator._observedRouteDeletions.add(
_NavigatorRemoveObservation(route, previousPresent),
);
}
}
bool doingPop = false;
void didAdd({ required NavigatorState navigator, required bool isNewFirst}) {
route.didAdd();
currentState = _RouteLifecycle.idle;
if (isNewFirst) {
route.didChangeNext(null);
}
}
void pop<T>(T? result) {
assert(isPresent);
doingPop = true;
if (route.didPop(result) && doingPop) {
currentState = _RouteLifecycle.pop;
}
doingPop = false;
}
bool _reportRemovalToObserver = true;
// Route is removed without being completed.
void remove({ bool isReplaced = false }) {
assert(
!hasPage || isWaitingForExitingDecision,
'A page-based route cannot be completed using imperative api, provide a '
'new list without the corresponding Page to Navigator.pages instead. ',
);
if (currentState.index >= _RouteLifecycle.remove.index)
return;
assert(isPresent);
_reportRemovalToObserver = !isReplaced;
currentState = _RouteLifecycle.remove;
}
// Route completes with `result` and is removed.
void complete<T>(T result, { bool isReplaced = false }) {
assert(
!hasPage || isWaitingForExitingDecision,
'A page-based route cannot be completed using imperative api, provide a '
'new list without the corresponding Page to Navigator.pages instead. ',
);
if (currentState.index >= _RouteLifecycle.remove.index)
return;
assert(isPresent);
_reportRemovalToObserver = !isReplaced;
route.didComplete(result);
assert(route._popCompleter.isCompleted); // implies didComplete was called
currentState = _RouteLifecycle.remove;
}
void finalize() {
assert(currentState.index < _RouteLifecycle.dispose.index);
currentState = _RouteLifecycle.dispose;
}
void dispose() {
assert(currentState.index < _RouteLifecycle.disposed.index);
currentState = _RouteLifecycle.disposed;
// If the overlay entries are still mounted, widgets in the route's subtree
// may still reference resources from the route and we delay disposal of
// the route until the overlay entries are no longer mounted.
// Since the overlay entry is the root of the route's subtree it will only
// get unmounted after every other widget in the subtree has been unmounted.
final Iterable<OverlayEntry> mountedEntries = route.overlayEntries.where((OverlayEntry e) => e.mounted);
if (mountedEntries.isEmpty) {
route.dispose();
} else {
int mounted = mountedEntries.length;
assert(mounted > 0);
for (final OverlayEntry entry in mountedEntries) {
late VoidCallback listener;
listener = () {
assert(mounted > 0);
assert(!entry.mounted);
mounted--;
entry.removeListener(listener);
if (mounted == 0) {
assert(route.overlayEntries.every((OverlayEntry e) => !e.mounted));
route.dispose();
}
};
entry.addListener(listener);
}
}
}
bool get willBePresent {
return currentState.index <= _RouteLifecycle.idle.index &&
currentState.index >= _RouteLifecycle.add.index;
}
bool get isPresent {
return currentState.index <= _RouteLifecycle.remove.index &&
currentState.index >= _RouteLifecycle.add.index;
}
bool get isPresentForRestoration => currentState.index <= _RouteLifecycle.idle.index;
bool get suitableForAnnouncement {
return currentState.index <= _RouteLifecycle.removing.index &&
currentState.index >= _RouteLifecycle.push.index;
}
bool get suitableForTransitionAnimation {
return currentState.index <= _RouteLifecycle.remove.index &&
currentState.index >= _RouteLifecycle.push.index;
}
bool shouldAnnounceChangeToNext(Route<dynamic>? nextRoute) {
assert(nextRoute != lastAnnouncedNextRoute);
// Do not announce if `next` changes from a just popped route to null. We
// already announced this change by calling didPopNext.
return !(
nextRoute == null &&
lastAnnouncedPoppedNextRoute != null &&
lastAnnouncedPoppedNextRoute == lastAnnouncedNextRoute
);
}
static bool isPresentPredicate(_RouteEntry entry) => entry.isPresent;
static bool suitableForTransitionAnimationPredicate(_RouteEntry entry) => entry.suitableForTransitionAnimation;
static bool willBePresentPredicate(_RouteEntry entry) => entry.willBePresent;
static _RouteEntryPredicate isRoutePredicate(Route<dynamic> route) {
return (_RouteEntry entry) => entry.route == route;
}
@override
bool get isWaitingForEnteringDecision => currentState == _RouteLifecycle.staging;
@override
bool get isWaitingForExitingDecision => _isWaitingForExitingDecision;
bool _isWaitingForExitingDecision = false;
void markNeedsExitingDecision() => _isWaitingForExitingDecision = true;
@override
void markForPush() {
assert(
isWaitingForEnteringDecision && !isWaitingForExitingDecision,
'This route cannot be marked for push. Either a decision has already been '
'made or it does not require an explicit decision on how to transition in.',
);
currentState = _RouteLifecycle.push;
}
@override
void markForAdd() {
assert(
isWaitingForEnteringDecision && !isWaitingForExitingDecision,
'This route cannot be marked for add. Either a decision has already been '
'made or it does not require an explicit decision on how to transition in.',
);
currentState = _RouteLifecycle.add;
}
@override
void markForPop([dynamic result]) {
assert(
!isWaitingForEnteringDecision && isWaitingForExitingDecision && isPresent,
'This route cannot be marked for pop. Either a decision has already been '
'made or it does not require an explicit decision on how to transition out.',
);
pop<dynamic>(result);
_isWaitingForExitingDecision = false;
}
@override
void markForComplete([dynamic result]) {
assert(
!isWaitingForEnteringDecision && isWaitingForExitingDecision && isPresent,
'This route cannot be marked for complete. Either a decision has already '
'been made or it does not require an explicit decision on how to transition '
'out.',
);
complete<dynamic>(result);
_isWaitingForExitingDecision = false;
}
@override
void markForRemove() {
assert(
!isWaitingForEnteringDecision && isWaitingForExitingDecision && isPresent,
'This route cannot be marked for remove. Either a decision has already '
'been made or it does not require an explicit decision on how to transition '
'out.',
);
remove();
_isWaitingForExitingDecision = false;
}
bool get restorationEnabled => route.restorationScopeId.value != null;
set restorationEnabled(bool value) {
assert(!value || restorationId != null);
route._updateRestorationId(value ? restorationId : null);
}
}
abstract class _NavigatorObservation {
_NavigatorObservation(
this.primaryRoute,
this.secondaryRoute,
);
final Route<dynamic> primaryRoute;
final Route<dynamic>? secondaryRoute;
void notify(NavigatorObserver observer);
}
class _NavigatorPushObservation extends _NavigatorObservation {
_NavigatorPushObservation(
Route<dynamic> primaryRoute,
Route<dynamic>? secondaryRoute,
) : super(primaryRoute, secondaryRoute);
@override
void notify(NavigatorObserver observer) {
observer.didPush(primaryRoute, secondaryRoute);
}
}
class _NavigatorPopObservation extends _NavigatorObservation {
_NavigatorPopObservation(
Route<dynamic> primaryRoute,
Route<dynamic>? secondaryRoute,
) : super(primaryRoute, secondaryRoute);
@override
void notify(NavigatorObserver observer) {
observer.didPop(primaryRoute, secondaryRoute);
}
}
class _NavigatorRemoveObservation extends _NavigatorObservation {
_NavigatorRemoveObservation(
Route<dynamic> primaryRoute,
Route<dynamic>? secondaryRoute,
) : super(primaryRoute, secondaryRoute);
@override
void notify(NavigatorObserver observer) {
observer.didRemove(primaryRoute, secondaryRoute);
}
}
class _NavigatorReplaceObservation extends _NavigatorObservation {
_NavigatorReplaceObservation(
Route<dynamic> primaryRoute,
Route<dynamic>? secondaryRoute,
) : super(primaryRoute, secondaryRoute);
@override
void notify(NavigatorObserver observer) {
observer.didReplace(newRoute: primaryRoute, oldRoute: secondaryRoute);
}
}
/// The state for a [Navigator] widget.
///
/// A reference to this class can be obtained by calling [Navigator.of].
class NavigatorState extends State<Navigator> with TickerProviderStateMixin, RestorationMixin {
late GlobalKey<OverlayState> _overlayKey;
List<_RouteEntry> _history = <_RouteEntry>[];
final _HistoryProperty _serializableHistory = _HistoryProperty();
final Queue<_NavigatorObservation> _observedRouteAdditions = Queue<_NavigatorObservation>();
final Queue<_NavigatorObservation> _observedRouteDeletions = Queue<_NavigatorObservation>();
/// The [FocusScopeNode] for the [FocusScope] that encloses the routes.
final FocusScopeNode focusScopeNode = FocusScopeNode(debugLabel: 'Navigator Scope');
bool _debugLocked = false; // used to prevent re-entrant calls to push, pop, and friends
HeroController? _heroControllerFromScope;
late List<NavigatorObserver> _effectiveObservers;
@override
void initState() {
super.initState();
assert(() {
if (widget.pages != const <Page<dynamic>>[]) {
// This navigator uses page API.
if (widget.pages.isEmpty) {
FlutterError.reportError(
FlutterErrorDetails(
exception: FlutterError(
'The Navigator.pages must not be empty to use the '
'Navigator.pages API',
),
library: 'widget library',
stack: StackTrace.current,
),
);
} else if (widget.onPopPage == null) {
FlutterError.reportError(
FlutterErrorDetails(
exception: FlutterError(
'The Navigator.onPopPage must be provided to use the '
'Navigator.pages API',
),
library: 'widget library',
stack: StackTrace.current,
),
);
}
}
return true;
}());
for (final NavigatorObserver observer in widget.observers) {
assert(observer.navigator == null);
observer._navigator = this;
}
_effectiveObservers = widget.observers;
// We have to manually extract the inherited widget in initState because
// the current context is not fully initialized.
final HeroControllerScope? heroControllerScope = context
.getElementForInheritedWidgetOfExactType<HeroControllerScope>()
?.widget as HeroControllerScope?;
_updateHeroController(heroControllerScope?.controller);
if (widget.reportsRouteUpdateToEngine) {
SystemNavigator.selectSingleEntryHistory();
}
}
// Use [_nextPagelessRestorationScopeId] to get the next id.
final RestorableNum<int> _rawNextPagelessRestorationScopeId = RestorableNum<int>(0);
int get _nextPagelessRestorationScopeId => _rawNextPagelessRestorationScopeId.value++;
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_rawNextPagelessRestorationScopeId, 'id');
registerForRestoration(_serializableHistory, 'history');
// Delete everything in the old history and clear the overlay.
while (_history.isNotEmpty) {
_history.removeLast().dispose();
}
assert(_history.isEmpty);
_overlayKey = GlobalKey<OverlayState>();
// Populate the new history from restoration data.
_history.addAll(_serializableHistory.restoreEntriesForPage(null, this));
for (final Page<dynamic> page in widget.pages) {
final _RouteEntry entry = _RouteEntry(
page.createRoute(context),
initialState: _RouteLifecycle.add,
);
assert(
entry.route.settings == page,
'The settings getter of a page-based Route must return a Page object. '
'Please set the settings to the Page in the Page.createRoute method.',
);
_history.add(entry);
_history.addAll(_serializableHistory.restoreEntriesForPage(entry, this));
}
// If there was nothing to restore, we need to process the initial route.
if (!_serializableHistory.hasData) {
String? initialRoute = widget.initialRoute;
if (widget.pages.isEmpty) {
initialRoute = initialRoute ?? Navigator.defaultRouteName;
}
if (initialRoute != null) {
_history.addAll(
widget.onGenerateInitialRoutes(
this,
widget.initialRoute ?? Navigator.defaultRouteName,
).map((Route<dynamic> route) => _RouteEntry(
route,
initialState: _RouteLifecycle.add,
restorationInformation: route.settings.name != null
? _RestorationInformation.named(
name: route.settings.name!,
arguments: null,
restorationScopeId: _nextPagelessRestorationScopeId,
)
: null,
),
),
);
}
}
assert(
_history.isNotEmpty,
'All routes returned by onGenerateInitialRoutes are not restorable. '
'Please make sure that all routes returned by onGenerateInitialRoutes '
'have their RouteSettings defined with names that are defined in the '
"app's routes table.",
);
assert(!_debugLocked);
assert(() { _debugLocked = true; return true; }());
_flushHistoryUpdates();
assert(() { _debugLocked = false; return true; }());
}
@override
void didToggleBucket(RestorationBucket? oldBucket) {
super.didToggleBucket(oldBucket);
if (bucket != null) {
_serializableHistory.update(_history);
} else {
_serializableHistory.clear();
}
}
@override
String? get restorationId => widget.restorationScopeId;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_updateHeroController(HeroControllerScope.of(context));
for (final _RouteEntry entry in _history)
entry.route.changedExternalState();
}
void _updateHeroController(HeroController? newHeroController) {
if (_heroControllerFromScope != newHeroController) {
if (newHeroController != null) {
// Makes sure the same hero controller is not shared between two navigators.
assert(() {
// It is possible that the hero controller subscribes to an existing
// navigator. We are fine as long as that navigator gives up the hero
// controller at the end of the build.
if (newHeroController.navigator != null) {
final NavigatorState previousOwner = newHeroController.navigator!;
ServicesBinding.instance!.addPostFrameCallback((Duration timestamp) {
// We only check if this navigator still owns the hero controller.
if (_heroControllerFromScope == newHeroController) {
final bool hasHeroControllerOwnerShip = _heroControllerFromScope!._navigator == this;
if (!hasHeroControllerOwnerShip ||
previousOwner._heroControllerFromScope == newHeroController) {
final NavigatorState otherOwner = hasHeroControllerOwnerShip
? previousOwner
: _heroControllerFromScope!._navigator!;
FlutterError.reportError(
FlutterErrorDetails(
exception: FlutterError(
'A HeroController can not be shared by multiple Navigators. '
'The Navigators that share the same HeroController are:\n'
'- $this\n'
'- $otherOwner\n'
'Please create a HeroControllerScope for each Navigator or '
'use a HeroControllerScope.none to prevent subtree from '
'receiving a HeroController.',
),
library: 'widget library',
stack: StackTrace.current,
),
);
}
}
});
}
return true;
}());
newHeroController._navigator = this;
}
// Only unsubscribe the hero controller when it is currently subscribe to
// this navigator.
if (_heroControllerFromScope?._navigator == this)
_heroControllerFromScope?._navigator = null;
_heroControllerFromScope = newHeroController;
_updateEffectiveObservers();
}
}
void _updateEffectiveObservers() {
if (_heroControllerFromScope != null)
_effectiveObservers = widget.observers + <NavigatorObserver>[_heroControllerFromScope!];
else
_effectiveObservers = widget.observers;
}
@override
void didUpdateWidget(Navigator oldWidget) {
super.didUpdateWidget(oldWidget);
assert(() {
if (widget.pages != const <Page<dynamic>>[]) {
// This navigator uses page API.
if (widget.pages.isEmpty) {
FlutterError.reportError(
FlutterErrorDetails(
exception: FlutterError(
'The Navigator.pages must not be empty to use the '
'Navigator.pages API',
),
library: 'widget library',
stack: StackTrace.current,
),
);
} else if (widget.onPopPage == null) {
FlutterError.reportError(
FlutterErrorDetails(
exception: FlutterError(
'The Navigator.onPopPage must be provided to use the '
'Navigator.pages API',
),
library: 'widget library',
stack: StackTrace.current,
),
);
}
}
return true;
}());
if (oldWidget.observers != widget.observers) {
for (final NavigatorObserver observer in oldWidget.observers)
observer._navigator = null;
for (final NavigatorObserver observer in widget.observers) {
assert(observer.navigator == null);
observer._navigator = this;
}
_updateEffectiveObservers();
}
if (oldWidget.pages != widget.pages && !restorePending) {
assert(() {
if (widget.pages.isEmpty) {
FlutterError.reportError(
FlutterErrorDetails(
exception: FlutterError(
'The Navigator.pages must not be empty to use the '
'Navigator.pages API',
),
library: 'widget library',
stack: StackTrace.current,
),
);
}
return true;
}());
_updatePages();
}
for (final _RouteEntry entry in _history)
entry.route.changedExternalState();
}
void _debugCheckDuplicatedPageKeys() {
assert(() {
final Set<Key> keyReservation = <Key>{};
for (final Page<dynamic> page in widget.pages) {
final LocalKey? key = page.key;
if (key != null) {
assert(!keyReservation.contains(key));
keyReservation.add(key);
}
}
return true;
}());
}
@override
void deactivate() {
for (final NavigatorObserver observer in _effectiveObservers)
observer._navigator = null;
super.deactivate();
}
@override
void activate() {
super.activate();
for (final NavigatorObserver observer in _effectiveObservers) {
assert(observer.navigator == null);
observer._navigator = this;
}
}
@override
void dispose() {
assert(!_debugLocked);
assert(() {
_debugLocked = true;
return true;
}());
assert(() {
for (final NavigatorObserver observer in _effectiveObservers)
assert(observer._navigator != this);
return true;
}());
_updateHeroController(null);
focusScopeNode.dispose();
for (final _RouteEntry entry in _history)
entry.dispose();
super.dispose();
// don't unlock, so that the object becomes unusable
assert(_debugLocked);
}
/// The overlay this navigator uses for its visual presentation.
OverlayState? get overlay => _overlayKey.currentState;
Iterable<OverlayEntry> get _allRouteOverlayEntries sync* {
for (final _RouteEntry entry in _history)
yield* entry.route.overlayEntries;
}
String? _lastAnnouncedRouteName;
bool _debugUpdatingPage = false;
void _updatePages() {
assert(() {
assert(!_debugUpdatingPage);
_debugCheckDuplicatedPageKeys();
_debugUpdatingPage = true;
return true;
}());
// This attempts to diff the new pages list (widget.pages) with
// the old _RouteEntry[s] list (_history), and produces a new list of
// _RouteEntry[s] to be the new list of _history. This method roughly
// follows the same outline of RenderObjectElement.updateChildren.
//
// The cases it tries to optimize for are:
// - the old list is empty
// - All the pages in the new list can match the page-based routes in the old
// list, and their orders are the same.
// - there is an insertion or removal of one or more page-based route in
// only one place in the list
// If a page-based route with a key is in both lists, it will be synced.
// Page-based routes without keys might be synced but there is no guarantee.
// The general approach is to sync the entire new list backwards, as follows:
// 1. Walk the lists from the bottom, syncing nodes, and record pageless routes,
// until you no longer have matching nodes.
// 2. Walk the lists from the top, without syncing nodes, until you no
// longer have matching nodes. We'll sync these nodes at the end. We
// don't sync them now because we want to sync all the nodes in order
// from beginning to end.
// At this point we narrowed the old and new lists to the point
// where the nodes no longer match.
// 3. Walk the narrowed part of the old list to get the list of
// keys.
// 4. Walk the narrowed part of the new list forwards:
// * Create a new _RouteEntry for non-keyed items and record them for
// transitionDelegate.
// * Sync keyed items with the source if it exists.
// 5. Walk the narrowed part of the old list again to records the
// _RouteEntry[s], as well as pageless routes, needed to be removed for
// transitionDelegate.
// 5. Walk the top of the list again, syncing the nodes and recording
// pageless routes.
// 6. Use transitionDelegate for explicit decisions on how _RouteEntry[s]
// transition in or off the screens.
// 7. Fill pageless routes back into the new history.
bool needsExplicitDecision = false;
int newPagesBottom = 0;
int oldEntriesBottom = 0;
int newPagesTop = widget.pages.length - 1;
int oldEntriesTop = _history.length - 1;
final List<_RouteEntry> newHistory = <_RouteEntry>[];
final Map<_RouteEntry?, List<_RouteEntry>> pageRouteToPagelessRoutes = <_RouteEntry?, List<_RouteEntry>>{};
// Updates the bottom of the list.
_RouteEntry? previousOldPageRouteEntry;
while (oldEntriesBottom <= oldEntriesTop) {
final _RouteEntry oldEntry = _history[oldEntriesBottom];
assert(oldEntry != null && oldEntry.currentState != _RouteLifecycle.disposed);
// Records pageless route. The bottom most pageless routes will be
// stored in key = null.
if (!oldEntry.hasPage) {
final List<_RouteEntry> pagelessRoutes = pageRouteToPagelessRoutes.putIfAbsent(
previousOldPageRouteEntry,
() => <_RouteEntry>[],
);
pagelessRoutes.add(oldEntry);
oldEntriesBottom += 1;
continue;
}
if (newPagesBottom > newPagesTop)
break;
final Page<dynamic> newPage = widget.pages[newPagesBottom];
if (!oldEntry.canUpdateFrom(newPage))
break;
previousOldPageRouteEntry = oldEntry;
oldEntry.route._updateSettings(newPage);
newHistory.add(oldEntry);
newPagesBottom += 1;
oldEntriesBottom += 1;
}
int pagelessRoutesToSkip = 0;
// Scans the top of the list until we found a page-based route that cannot be
// updated.
while ((oldEntriesBottom <= oldEntriesTop) && (newPagesBottom <= newPagesTop)) {
final _RouteEntry oldEntry = _history[oldEntriesTop];
assert(oldEntry != null && oldEntry.currentState != _RouteLifecycle.disposed);
if (!oldEntry.hasPage) {
// This route might need to be skipped if we can not find a page above.
pagelessRoutesToSkip += 1;
oldEntriesTop -= 1;
continue;
}
final Page<dynamic> newPage = widget.pages[newPagesTop];
if (!oldEntry.canUpdateFrom(newPage))
break;
// We found the page for all the consecutive pageless routes below. Those
// pageless routes do not need to be skipped.
pagelessRoutesToSkip = 0;
oldEntriesTop -= 1;
newPagesTop -= 1;
}
// Reverts the pageless routes that cannot be updated.
oldEntriesTop += pagelessRoutesToSkip;
// Scans middle of the old entries and records the page key to old entry map.
int oldEntriesBottomToScan = oldEntriesBottom;
final Map<LocalKey, _RouteEntry> pageKeyToOldEntry = <LocalKey, _RouteEntry>{};
while (oldEntriesBottomToScan <= oldEntriesTop) {
final _RouteEntry oldEntry = _history[oldEntriesBottomToScan];
oldEntriesBottomToScan += 1;
assert(
oldEntry != null &&
oldEntry.currentState != _RouteLifecycle.disposed,
);
// Pageless routes will be recorded when we update the middle of the old
// list.
if (!oldEntry.hasPage)
continue;
assert(oldEntry.hasPage);
final Page<dynamic> page = oldEntry.route.settings as Page<dynamic>;
if (page.key == null)
continue;
assert(!pageKeyToOldEntry.containsKey(page.key));
pageKeyToOldEntry[page.key!] = oldEntry;
}
// Updates the middle of the list.
while (newPagesBottom <= newPagesTop) {
final Page<dynamic> nextPage = widget.pages[newPagesBottom];
newPagesBottom += 1;
if (
nextPage.key == null ||
!pageKeyToOldEntry.containsKey(nextPage.key) ||
!pageKeyToOldEntry[nextPage.key]!.canUpdateFrom(nextPage)
) {
// There is no matching key in the old history, we need to create a new
// route and wait for the transition delegate to decide how to add
// it into the history.
final _RouteEntry newEntry = _RouteEntry(
nextPage.createRoute(context),
initialState: _RouteLifecycle.staging,
);
needsExplicitDecision = true;
assert(
newEntry.route.settings == nextPage,
'The settings getter of a page-based Route must return a Page object. '
'Please set the settings to the Page in the Page.createRoute method.',
);
newHistory.add(newEntry);
} else {
// Removes the key from pageKeyToOldEntry to indicate it is taken.
final _RouteEntry matchingEntry = pageKeyToOldEntry.remove(nextPage.key)!;
assert(matchingEntry.canUpdateFrom(nextPage));
matchingEntry.route._updateSettings(nextPage);
newHistory.add(matchingEntry);
}
}
// Any remaining old routes that do not have a match will need to be removed.
final Map<RouteTransitionRecord?, RouteTransitionRecord> locationToExitingPageRoute = <RouteTransitionRecord?, RouteTransitionRecord>{};
while (oldEntriesBottom <= oldEntriesTop) {
final _RouteEntry potentialEntryToRemove = _history[oldEntriesBottom];
oldEntriesBottom += 1;
if (!potentialEntryToRemove.hasPage) {
assert(previousOldPageRouteEntry != null);
final List<_RouteEntry> pagelessRoutes = pageRouteToPagelessRoutes
.putIfAbsent(
previousOldPageRouteEntry,
() => <_RouteEntry>[],
);
pagelessRoutes.add(potentialEntryToRemove);
if (previousOldPageRouteEntry!.isWaitingForExitingDecision && potentialEntryToRemove.isPresent)
potentialEntryToRemove.markNeedsExitingDecision();
continue;
}
final Page<dynamic> potentialPageToRemove = potentialEntryToRemove.route.settings as Page<dynamic>;
// Marks for transition delegate to remove if this old page does not have
// a key or was not taken during updating the middle of new page.
if (
potentialPageToRemove.key == null ||
pageKeyToOldEntry.containsKey(potentialPageToRemove.key)
) {
locationToExitingPageRoute[previousOldPageRouteEntry] = potentialEntryToRemove;
// We only need a decision if it has not already been popped.
if (potentialEntryToRemove.isPresent)
potentialEntryToRemove.markNeedsExitingDecision();
}
previousOldPageRouteEntry = potentialEntryToRemove;
}
// We've scanned the whole list.
assert(oldEntriesBottom == oldEntriesTop + 1);
assert(newPagesBottom == newPagesTop + 1);
newPagesTop = widget.pages.length - 1;
oldEntriesTop = _history.length - 1;
// Verifies we either reach the bottom or the oldEntriesBottom must be updatable
// by newPagesBottom.
assert(() {
if (oldEntriesBottom <= oldEntriesTop)
return newPagesBottom <= newPagesTop &&
_history[oldEntriesBottom].hasPage &&
_history[oldEntriesBottom].canUpdateFrom(widget.pages[newPagesBottom]);
else
return newPagesBottom > newPagesTop;
}());
// Updates the top of the list.
while ((oldEntriesBottom <= oldEntriesTop) && (newPagesBottom <= newPagesTop)) {
final _RouteEntry oldEntry = _history[oldEntriesBottom];
assert(oldEntry != null && oldEntry.currentState != _RouteLifecycle.disposed);
if (!oldEntry.hasPage) {
assert(previousOldPageRouteEntry != null);
final List<_RouteEntry> pagelessRoutes = pageRouteToPagelessRoutes
.putIfAbsent(
previousOldPageRouteEntry,
() => <_RouteEntry>[],
);
pagelessRoutes.add(oldEntry);
continue;
}
previousOldPageRouteEntry = oldEntry;
final Page<dynamic> newPage = widget.pages[newPagesBottom];
assert(oldEntry.canUpdateFrom(newPage));
oldEntry.route._updateSettings(newPage);
newHistory.add(oldEntry);
oldEntriesBottom += 1;
newPagesBottom += 1;
}
// Finally, uses transition delegate to make explicit decision if needed.
needsExplicitDecision = needsExplicitDecision || locationToExitingPageRoute.isNotEmpty;
Iterable<_RouteEntry> results = newHistory;
if (needsExplicitDecision) {
results = widget.transitionDelegate._transition(
newPageRouteHistory: newHistory,
locationToExitingPageRoute: locationToExitingPageRoute,
pageRouteToPagelessRoutes: pageRouteToPagelessRoutes,
).cast<_RouteEntry>();
}
_history = <_RouteEntry>[];
// Adds the leading pageless routes if there is any.
if (pageRouteToPagelessRoutes.containsKey(null)) {
_history.addAll(pageRouteToPagelessRoutes[null]!);
}
for (final _RouteEntry result in results) {
_history.add(result);
if (pageRouteToPagelessRoutes.containsKey(result)) {
_history.addAll(pageRouteToPagelessRoutes[result]!);
}
}
assert(() {_debugUpdatingPage = false; return true;}());
assert(() { _debugLocked = true; return true; }());
_flushHistoryUpdates();
assert(() { _debugLocked = false; return true; }());
}
void _flushHistoryUpdates({bool rearrangeOverlay = true}) {
assert(_debugLocked && !_debugUpdatingPage);
// Clean up the list, sending updates to the routes that changed. Notably,
// we don't send the didChangePrevious/didChangeNext updates to those that
// did not change at this point, because we're not yet sure exactly what the
// routes will be at the end of the day (some might get disposed).
int index = _history.length - 1;
_RouteEntry? next;
_RouteEntry? entry = _history[index];
_RouteEntry? previous = index > 0 ? _history[index - 1] : null;
bool canRemoveOrAdd = false; // Whether there is a fully opaque route on top to silently remove or add route underneath.
Route<dynamic>? poppedRoute; // The route that should trigger didPopNext on the top active route.
bool seenTopActiveRoute = false; // Whether we've seen the route that would get didPopNext.
final List<_RouteEntry> toBeDisposed = <_RouteEntry>[];
while (index >= 0) {
switch (entry!.currentState) {
case _RouteLifecycle.add:
assert(rearrangeOverlay);
entry.handleAdd(
navigator: this,
previousPresent: _getRouteBefore(index - 1, _RouteEntry.isPresentPredicate)?.route,
);
assert(entry.currentState == _RouteLifecycle.adding);
continue;
case _RouteLifecycle.adding:
if (canRemoveOrAdd || next == null) {
entry.didAdd(
navigator: this,
isNewFirst: next == null,
);
assert(entry.currentState == _RouteLifecycle.idle);
continue;
}
break;
case _RouteLifecycle.push:
case _RouteLifecycle.pushReplace:
case _RouteLifecycle.replace:
assert(rearrangeOverlay);
entry.handlePush(
navigator: this,
previous: previous?.route,
previousPresent: _getRouteBefore(index - 1, _RouteEntry.isPresentPredicate)?.route,
isNewFirst: next == null,
);
assert(entry.currentState != _RouteLifecycle.push);
assert(entry.currentState != _RouteLifecycle.pushReplace);
assert(entry.currentState != _RouteLifecycle.replace);
if (entry.currentState == _RouteLifecycle.idle) {
continue;
}
break;
case _RouteLifecycle.pushing: // Will exit this state when animation completes.
if (!seenTopActiveRoute && poppedRoute != null)
entry.handleDidPopNext(poppedRoute);
seenTopActiveRoute = true;
break;
case _RouteLifecycle.idle:
if (!seenTopActiveRoute && poppedRoute != null)
entry.handleDidPopNext(poppedRoute);
seenTopActiveRoute = true;
// This route is idle, so we are allowed to remove subsequent (earlier)
// routes that are waiting to be removed silently:
canRemoveOrAdd = true;
break;
case _RouteLifecycle.pop:
if (!seenTopActiveRoute) {
if (poppedRoute != null)
entry.handleDidPopNext(poppedRoute);
poppedRoute = entry.route;
}
entry.handlePop(
navigator: this,
previousPresent: _getRouteBefore(index, _RouteEntry.willBePresentPredicate)?.route,
);
assert(entry.currentState == _RouteLifecycle.popping);
canRemoveOrAdd = true;
break;
case _RouteLifecycle.popping:
// Will exit this state when animation completes.
break;
case _RouteLifecycle.remove:
if (!seenTopActiveRoute) {
if (poppedRoute != null)
entry.route.didPopNext(poppedRoute);
poppedRoute = null;
}
entry.handleRemoval(
navigator: this,
previousPresent: _getRouteBefore(index, _RouteEntry.willBePresentPredicate)?.route,
);
assert(entry.currentState == _RouteLifecycle.removing);
continue;
case _RouteLifecycle.removing:
if (!canRemoveOrAdd && next != null) {
// We aren't allowed to remove this route yet.
break;
}
entry.currentState = _RouteLifecycle.dispose;
continue;
case _RouteLifecycle.dispose:
// Delay disposal until didChangeNext/didChangePrevious have been sent.
toBeDisposed.add(_history.removeAt(index));
entry = next;
break;
case _RouteLifecycle.disposed:
case _RouteLifecycle.staging:
assert(false);
break;
}
index -= 1;
next = entry;
entry = previous;
previous = index > 0 ? _history[index - 1] : null;
}
// Informs navigator observers about route changes.
_flushObserverNotifications();
// Now that the list is clean, send the didChangeNext/didChangePrevious
// notifications.
_flushRouteAnnouncement();
// Announce route name changes.
if (widget.reportsRouteUpdateToEngine) {
final _RouteEntry? lastEntry = _history.cast<_RouteEntry?>().lastWhere(
(_RouteEntry? e) => e != null && _RouteEntry.isPresentPredicate(e), orElse: () => null,
);
final String? routeName = lastEntry?.route.settings.name;
if (routeName != null && routeName != _lastAnnouncedRouteName) {
SystemNavigator.routeInformationUpdated(location: routeName);
_lastAnnouncedRouteName = routeName;
}
}
// Lastly, removes the overlay entries of all marked entries and disposes
// them.
for (final _RouteEntry entry in toBeDisposed) {
for (final OverlayEntry overlayEntry in entry.route.overlayEntries)
overlayEntry.remove();
entry.dispose();
}
if (rearrangeOverlay) {
overlay?.rearrange(_allRouteOverlayEntries);
}
if (bucket != null) {
_serializableHistory.update(_history);
}
}
void _flushObserverNotifications() {
if (_effectiveObservers.isEmpty) {
_observedRouteDeletions.clear();
_observedRouteAdditions.clear();
return;
}
while (_observedRouteAdditions.isNotEmpty) {
final _NavigatorObservation observation = _observedRouteAdditions.removeLast();
_effectiveObservers.forEach(observation.notify);
}
while (_observedRouteDeletions.isNotEmpty) {
final _NavigatorObservation observation = _observedRouteDeletions.removeFirst();
_effectiveObservers.forEach(observation.notify);
}
}
void _flushRouteAnnouncement() {
int index = _history.length - 1;
while (index >= 0) {
final _RouteEntry entry = _history[index];
if (!entry.suitableForAnnouncement) {
index -= 1;
continue;
}
final _RouteEntry? next = _getRouteAfter(index + 1, _RouteEntry.suitableForTransitionAnimationPredicate);
if (next?.route != entry.lastAnnouncedNextRoute) {
if (entry.shouldAnnounceChangeToNext(next?.route)) {
entry.route.didChangeNext(next?.route);
}
entry.lastAnnouncedNextRoute = next?.route;
}
final _RouteEntry? previous = _getRouteBefore(index - 1, _RouteEntry.suitableForTransitionAnimationPredicate);
if (previous?.route != entry.lastAnnouncedPreviousRoute) {
entry.route.didChangePrevious(previous?.route);
entry.lastAnnouncedPreviousRoute = previous?.route;
}
index -= 1;
}
}
_RouteEntry? _getRouteBefore(int index, _RouteEntryPredicate predicate) {
index = _getIndexBefore(index, predicate);
return index >= 0 ? _history[index] : null;
}
int _getIndexBefore(int index, _RouteEntryPredicate predicate) {
while(index >= 0 && !predicate(_history[index])) {
index -= 1;
}
return index;
}
_RouteEntry? _getRouteAfter(int index, _RouteEntryPredicate predicate) {
while (index < _history.length && !predicate(_history[index])) {
index += 1;
}
return index < _history.length ? _history[index] : null;
}
Route<T>? _routeNamed<T>(String name, { required Object? arguments, bool allowNull = false }) {
assert(!_debugLocked);
assert(name != null);
if (allowNull && widget.onGenerateRoute == null)
return null;
assert(() {
if (widget.onGenerateRoute == null) {
throw FlutterError(
'Navigator.onGenerateRoute was null, but the route named "$name" was referenced.\n'
'To use the Navigator API with named routes (pushNamed, pushReplacementNamed, or '
'pushNamedAndRemoveUntil), the Navigator must be provided with an '
'onGenerateRoute handler.\n'
'The Navigator was:\n'
' $this',
);
}
return true;
}());
final RouteSettings settings = RouteSettings(
name: name,
arguments: arguments,
);
Route<T>? route = widget.onGenerateRoute!(settings) as Route<T>?;
if (route == null && !allowNull) {
assert(() {
if (widget.onUnknownRoute == null) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Navigator.onGenerateRoute returned null when requested to build route "$name".'),
ErrorDescription(
'The onGenerateRoute callback must never return null, unless an onUnknownRoute '
'callback is provided as well.',
),
DiagnosticsProperty<NavigatorState>('The Navigator was', this, style: DiagnosticsTreeStyle.errorProperty),
]);
}
return true;
}());
route = widget.onUnknownRoute!(settings) as Route<T>?;
assert(() {
if (route == null) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Navigator.onUnknownRoute returned null when requested to build route "$name".'),
ErrorDescription('The onUnknownRoute callback must never return null.'),
DiagnosticsProperty<NavigatorState>('The Navigator was', this, style: DiagnosticsTreeStyle.errorProperty),
]);
}
return true;
}());
}
assert(route != null || allowNull);
return route;
}
/// Push a named route onto the navigator.
///
/// {@macro flutter.widgets.navigator.pushNamed}
///
/// {@macro flutter.widgets.Navigator.pushNamed}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _aaronBurrSir() {
/// navigator.pushNamed('/nyc/1776');
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePushNamed], which pushes a route that can be restored
/// during state restoration.
@optionalTypeArgs
Future<T?> pushNamed<T extends Object?>(
String routeName, {
Object? arguments,
}) {
return push<T>(_routeNamed<T>(routeName, arguments: arguments)!);
}
/// Push a named route onto the navigator.
///
/// {@macro flutter.widgets.navigator.restorablePushNamed}
///
/// {@macro flutter.widgets.navigator.pushNamed}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.arguments}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _openDetails() {
/// navigator.restorablePushNamed('/nyc/1776');
/// }
/// ```
/// {@end-tool}
@optionalTypeArgs
String restorablePushNamed<T extends Object?>(
String routeName, {
Object? arguments,
}) {
assert(routeName != null);
assert(debugIsSerializableForRestoration(arguments), 'The arguments object must be serializable via the StandardMessageCodec.');
final _RouteEntry entry = _RestorationInformation.named(
name: routeName,
arguments: arguments,
restorationScopeId: _nextPagelessRestorationScopeId,
).toRouteEntry(this, initialState: _RouteLifecycle.push);
_pushEntry(entry);
return entry.restorationId!;
}
/// Replace the current route of the navigator by pushing the route named
/// [routeName] and then disposing the previous route once the new route has
/// finished animating in.
///
/// {@macro flutter.widgets.navigator.pushReplacementNamed}
///
/// {@macro flutter.widgets.Navigator.pushNamed}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _startBike() {
/// navigator.pushReplacementNamed('/jouett/1781');
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePushReplacementNamed], which pushes a replacement route that
/// can be restored during state restoration.
@optionalTypeArgs
Future<T?> pushReplacementNamed<T extends Object?, TO extends Object?>(
String routeName, {
TO? result,
Object? arguments,
}) {
return pushReplacement<T, TO>(_routeNamed<T>(routeName, arguments: arguments)!, result: result);
}
/// Replace the current route of the navigator by pushing the route named
/// [routeName] and then disposing the previous route once the new route has
/// finished animating in.
///
/// {@macro flutter.widgets.navigator.restorablePushReplacementNamed}
///
/// {@macro flutter.widgets.navigator.pushReplacementNamed}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.arguments}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _startCar() {
/// navigator.restorablePushReplacementNamed('/jouett/1781');
/// }
/// ```
/// {@end-tool}
@optionalTypeArgs
String restorablePushReplacementNamed<T extends Object?, TO extends Object?>(
String routeName, {
TO? result,
Object? arguments,
}) {
assert(routeName != null);
assert(debugIsSerializableForRestoration(arguments), 'The arguments object must be serializable via the StandardMessageCodec.');
final _RouteEntry entry = _RestorationInformation.named(
name: routeName,
arguments: arguments,
restorationScopeId: _nextPagelessRestorationScopeId,
).toRouteEntry(this, initialState: _RouteLifecycle.pushReplace);
_pushReplacementEntry(entry, result);
return entry.restorationId!;
}
/// Pop the current route off the navigator and push a named route in its
/// place.
///
/// {@macro flutter.widgets.navigator.popAndPushNamed}
///
/// {@macro flutter.widgets.Navigator.pushNamed}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _begin() {
/// navigator.popAndPushNamed('/nyc/1776');
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePopAndPushNamed], which pushes a new route that can be
/// restored during state restoration.
@optionalTypeArgs
Future<T?> popAndPushNamed<T extends Object?, TO extends Object?>(
String routeName, {
TO? result,
Object? arguments,
}) {
pop<TO>(result);
return pushNamed<T>(routeName, arguments: arguments);
}
/// Pop the current route off the navigator and push a named route in its
/// place.
///
/// {@macro flutter.widgets.navigator.restorablePopAndPushNamed}
///
/// {@macro flutter.widgets.navigator.popAndPushNamed}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.arguments}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _end() {
/// navigator.restorablePopAndPushNamed('/nyc/1776');
/// }
/// ```
/// {@end-tool}
@optionalTypeArgs
String restorablePopAndPushNamed<T extends Object?, TO extends Object?>(
String routeName, {
TO? result,
Object? arguments,
}) {
pop<TO>(result);
return restorablePushNamed(routeName, arguments: arguments);
}
/// Push the route with the given name onto the navigator, and then remove all
/// the previous routes until the `predicate` returns true.
///
/// {@macro flutter.widgets.navigator.pushNamedAndRemoveUntil}
///
/// {@macro flutter.widgets.Navigator.pushNamed}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _handleOpenCalendar() {
/// navigator.pushNamedAndRemoveUntil('/calendar', ModalRoute.withName('/'));
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePushNamedAndRemoveUntil], which pushes a new route that can
/// be restored during state restoration.
@optionalTypeArgs
Future<T?> pushNamedAndRemoveUntil<T extends Object?>(
String newRouteName,
RoutePredicate predicate, {
Object? arguments,
}) {
return pushAndRemoveUntil<T>(_routeNamed<T>(newRouteName, arguments: arguments)!, predicate);
}
/// Push the route with the given name onto the navigator, and then remove all
/// the previous routes until the `predicate` returns true.
///
/// {@macro flutter.widgets.navigator.restorablePushNamedAndRemoveUntil}
///
/// {@macro flutter.widgets.navigator.pushNamedAndRemoveUntil}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.arguments}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _openCalendar() {
/// navigator.restorablePushNamedAndRemoveUntil('/calendar', ModalRoute.withName('/'));
/// }
/// ```
/// {@end-tool}
@optionalTypeArgs
String restorablePushNamedAndRemoveUntil<T extends Object?>(
String newRouteName,
RoutePredicate predicate, {
Object? arguments,
}) {
assert(newRouteName != null);
assert(debugIsSerializableForRestoration(arguments), 'The arguments object must be serializable via the StandardMessageCodec.');
final _RouteEntry entry = _RestorationInformation.named(
name: newRouteName,
arguments: arguments,
restorationScopeId: _nextPagelessRestorationScopeId,
).toRouteEntry(this, initialState: _RouteLifecycle.push);
_pushEntryAndRemoveUntil(entry, predicate);
return entry.restorationId!;
}
/// Push the given route onto the navigator.
///
/// {@macro flutter.widgets.navigator.push}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _openPage() {
/// navigator.push<void>(
/// MaterialPageRoute<void>(
/// builder: (BuildContext context) => const MyPage(),
/// ),
/// );
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePush], which pushes a route that can be restored during
/// state restoration.
@optionalTypeArgs
Future<T?> push<T extends Object?>(Route<T> route) {
assert(_debugCheckIsPagelessRoute(route));
_pushEntry(_RouteEntry(route, initialState: _RouteLifecycle.push));
return route.popped;
}
bool _debugCheckIsPagelessRoute(Route<dynamic> route) {
assert(() {
if (route.settings is Page) {
FlutterError.reportError(
FlutterErrorDetails(
exception: FlutterError(
'A page-based route should not be added using the imperative api. '
'Provide a new list with the corresponding Page to Navigator.pages instead.',
),
library: 'widget library',
stack: StackTrace.current,
),
);
}
return true;
}());
return true;
}
bool _debugIsStaticCallback(Function callback) {
bool result = false;
assert(() {
// TODO(goderbauer): remove the kIsWeb check when https://github.com/flutter/flutter/issues/33615 is resolved.
result = kIsWeb || ui.PluginUtilities.getCallbackHandle(callback) != null;
return true;
}());
return result;
}
/// Push a new route onto the navigator.
///
/// {@macro flutter.widgets.navigator.restorablePush}
///
/// {@macro flutter.widgets.navigator.push}
///
/// {@macro flutter.widgets.Navigator.restorablePush}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool dartpad --template=stateful_widget_material}
/// Typical usage is as follows:
///
/// ** See code in examples/api/lib/widgets/navigator/navigator_state.restorable_push.0.dart **
/// {@end-tool}
@optionalTypeArgs
String restorablePush<T extends Object?>(RestorableRouteBuilder<T> routeBuilder, {Object? arguments}) {
assert(routeBuilder != null);
assert(_debugIsStaticCallback(routeBuilder), 'The provided routeBuilder must be a static function.');
assert(debugIsSerializableForRestoration(arguments), 'The arguments object must be serializable via the StandardMessageCodec.');
final _RouteEntry entry = _RestorationInformation.anonymous(
routeBuilder: routeBuilder,
arguments: arguments,
restorationScopeId: _nextPagelessRestorationScopeId,
).toRouteEntry(this, initialState: _RouteLifecycle.push);
_pushEntry(entry);
return entry.restorationId!;
}
void _pushEntry(_RouteEntry entry) {
assert(!_debugLocked);
assert(() {
_debugLocked = true;
return true;
}());
assert(entry.route != null);
assert(entry.route._navigator == null);
assert(entry.currentState == _RouteLifecycle.push);
_history.add(entry);
_flushHistoryUpdates();
assert(() {
_debugLocked = false;
return true;
}());
_afterNavigation(entry.route);
}
void _afterNavigation(Route<dynamic>? route) {
if (!kReleaseMode) {
// Among other uses, performance tools use this event to ensure that perf
// stats reflect the time interval since the last navigation event
// occurred, ensuring that stats only reflect the current page.
Map<String, dynamic>? routeJsonable;
if (route != null) {
routeJsonable = <String, dynamic>{};
final String description;
if (route is TransitionRoute<dynamic>) {
final TransitionRoute<dynamic> transitionRoute = route;
description = transitionRoute.debugLabel;
} else {
description = '$route';
}
routeJsonable['description'] = description;
final RouteSettings settings = route.settings;
final Map<String, dynamic> settingsJsonable = <String, dynamic> {
'name': settings.name,
};
if (settings.arguments != null) {
settingsJsonable['arguments'] = jsonEncode(
settings.arguments,
toEncodable: (Object? object) => '$object',
);
}
routeJsonable['settings'] = settingsJsonable;
}
developer.postEvent('Flutter.Navigation', <String, dynamic>{
'route': routeJsonable,
});
}
_cancelActivePointers();
}
/// Replace the current route of the navigator by pushing the given route and
/// then disposing the previous route once the new route has finished
/// animating in.
///
/// {@macro flutter.widgets.navigator.pushReplacement}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _doOpenPage() {
/// navigator.pushReplacement<void, void>(
/// MaterialPageRoute<void>(
/// builder: (BuildContext context) => const MyHomePage(),
/// ),
/// );
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePushReplacement], which pushes a replacement route that can
/// be restored during state restoration.
@optionalTypeArgs
Future<T?> pushReplacement<T extends Object?, TO extends Object?>(Route<T> newRoute, { TO? result }) {
assert(newRoute != null);
assert(newRoute._navigator == null);
assert(_debugCheckIsPagelessRoute(newRoute));
_pushReplacementEntry(_RouteEntry(newRoute, initialState: _RouteLifecycle.pushReplace), result);
return newRoute.popped;
}
/// Replace the current route of the navigator by pushing a new route and
/// then disposing the previous route once the new route has finished
/// animating in.
///
/// {@macro flutter.widgets.navigator.restorablePushReplacement}
///
/// {@macro flutter.widgets.navigator.pushReplacement}
///
/// {@macro flutter.widgets.Navigator.restorablePush}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool dartpad --template=stateful_widget_material}
/// Typical usage is as follows:
///
/// ** See code in examples/api/lib/widgets/navigator/navigator_state.restorable_push_replacement.0.dart **
/// {@end-tool}
@optionalTypeArgs
String restorablePushReplacement<T extends Object?, TO extends Object?>(RestorableRouteBuilder<T> routeBuilder, { TO? result, Object? arguments }) {
assert(routeBuilder != null);
assert(_debugIsStaticCallback(routeBuilder), 'The provided routeBuilder must be a static function.');
assert(debugIsSerializableForRestoration(arguments), 'The arguments object must be serializable via the StandardMessageCodec.');
final _RouteEntry entry = _RestorationInformation.anonymous(
routeBuilder: routeBuilder,
arguments: arguments,
restorationScopeId: _nextPagelessRestorationScopeId,
).toRouteEntry(this, initialState: _RouteLifecycle.pushReplace);
_pushReplacementEntry(entry, result);
return entry.restorationId!;
}
void _pushReplacementEntry<TO extends Object?>(_RouteEntry entry, TO? result) {
assert(!_debugLocked);
assert(() {
_debugLocked = true;
return true;
}());
assert(entry.route != null);
assert(entry.route._navigator == null);
assert(_history.isNotEmpty);
assert(_history.any(_RouteEntry.isPresentPredicate), 'Navigator has no active routes to replace.');
assert(entry.currentState == _RouteLifecycle.pushReplace);
_history.lastWhere(_RouteEntry.isPresentPredicate).complete(result, isReplaced: true);
_history.add(entry);
_flushHistoryUpdates();
assert(() {
_debugLocked = false;
return true;
}());
_afterNavigation(entry.route);
}
/// Push the given route onto the navigator, and then remove all the previous
/// routes until the `predicate` returns true.
///
/// {@macro flutter.widgets.navigator.pushAndRemoveUntil}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _resetAndOpenPage() {
/// navigator.pushAndRemoveUntil<void>(
/// MaterialPageRoute<void>(builder: (BuildContext context) => const MyHomePage()),
/// ModalRoute.withName('/'),
/// );
/// }
/// ```
/// {@end-tool}
///
///
/// See also:
///
/// * [restorablePushAndRemoveUntil], which pushes a route that can be
/// restored during state restoration.
@optionalTypeArgs
Future<T?> pushAndRemoveUntil<T extends Object?>(Route<T> newRoute, RoutePredicate predicate) {
assert(newRoute != null);
assert(newRoute._navigator == null);
assert(newRoute.overlayEntries.isEmpty);
assert(_debugCheckIsPagelessRoute(newRoute));
_pushEntryAndRemoveUntil(_RouteEntry(newRoute, initialState: _RouteLifecycle.push), predicate);
return newRoute.popped;
}
/// Push a new route onto the navigator, and then remove all the previous
/// routes until the `predicate` returns true.
///
/// {@macro flutter.widgets.navigator.restorablePushAndRemoveUntil}
///
/// {@macro flutter.widgets.navigator.pushAndRemoveUntil}
///
/// {@macro flutter.widgets.Navigator.restorablePush}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool dartpad --template=stateful_widget_material}
/// Typical usage is as follows:
///
/// ** See code in examples/api/lib/widgets/navigator/navigator_state.restorable_push_and_remove_until.0.dart **
/// {@end-tool}
@optionalTypeArgs
String restorablePushAndRemoveUntil<T extends Object?>(RestorableRouteBuilder<T> newRouteBuilder, RoutePredicate predicate, {Object? arguments}) {
assert(newRouteBuilder != null);
assert(_debugIsStaticCallback(newRouteBuilder), 'The provided routeBuilder must be a static function.');
assert(debugIsSerializableForRestoration(arguments), 'The arguments object must be serializable via the StandardMessageCodec.');
final _RouteEntry entry = _RestorationInformation.anonymous(
routeBuilder: newRouteBuilder,
arguments: arguments,
restorationScopeId: _nextPagelessRestorationScopeId,
).toRouteEntry(this, initialState: _RouteLifecycle.push);
_pushEntryAndRemoveUntil(entry, predicate);
return entry.restorationId!;
}
void _pushEntryAndRemoveUntil(_RouteEntry entry, RoutePredicate predicate) {
assert(!_debugLocked);
assert(() {
_debugLocked = true;
return true;
}());
assert(entry.route != null);
assert(entry.route._navigator == null);
assert(entry.route.overlayEntries.isEmpty);
assert(predicate != null);
assert(entry.currentState == _RouteLifecycle.push);
int index = _history.length - 1;
_history.add(entry);
while (index >= 0 && !predicate(_history[index].route)) {
if (_history[index].isPresent)
_history[index].remove();
index -= 1;
}
_flushHistoryUpdates();
assert(() {
_debugLocked = false;
return true;
}());
_afterNavigation(entry.route);
}
/// Replaces a route on the navigator with a new route.
///
/// {@macro flutter.widgets.navigator.replace}
///
/// See also:
///
/// * [replaceRouteBelow], which is the same but identifies the route to be
/// removed by reference to the route above it, rather than directly.
/// * [restorableReplace], which adds a replacement route that can be
/// restored during state restoration.
@optionalTypeArgs
void replace<T extends Object?>({ required Route<dynamic> oldRoute, required Route<T> newRoute }) {
assert(!_debugLocked);
assert(oldRoute != null);
assert(oldRoute._navigator == this);
assert(newRoute != null);
_replaceEntry(_RouteEntry(newRoute, initialState: _RouteLifecycle.replace), oldRoute);
}
/// Replaces a route on the navigator with a new route.
///
/// {@macro flutter.widgets.navigator.restorableReplace}
///
/// {@macro flutter.widgets.navigator.replace}
///
/// {@macro flutter.widgets.Navigator.restorablePush}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
@optionalTypeArgs
String restorableReplace<T extends Object?>({ required Route<dynamic> oldRoute, required RestorableRouteBuilder<T> newRouteBuilder, Object? arguments }) {
assert(oldRoute != null);
assert(oldRoute._navigator == this);
assert(newRouteBuilder != null);
assert(_debugIsStaticCallback(newRouteBuilder), 'The provided routeBuilder must be a static function.');
assert(debugIsSerializableForRestoration(arguments), 'The arguments object must be serializable via the StandardMessageCodec.');
assert(oldRoute != null);
final _RouteEntry entry = _RestorationInformation.anonymous(
routeBuilder: newRouteBuilder,
arguments: arguments,
restorationScopeId: _nextPagelessRestorationScopeId,
).toRouteEntry(this, initialState: _RouteLifecycle.replace);
_replaceEntry(entry, oldRoute);
return entry.restorationId!;
}
void _replaceEntry(_RouteEntry entry, Route<dynamic> oldRoute) {
assert(!_debugLocked);
if (oldRoute == entry.route)
return;
assert(() {
_debugLocked = true;
return true;
}());
assert(entry.currentState == _RouteLifecycle.replace);
assert(entry.route._navigator == null);
final int index = _history.indexWhere(_RouteEntry.isRoutePredicate(oldRoute));
assert(index >= 0, 'This Navigator does not contain the specified oldRoute.');
assert(_history[index].isPresent, 'The specified oldRoute has already been removed from the Navigator.');
final bool wasCurrent = oldRoute.isCurrent;
_history.insert(index + 1, entry);
_history[index].remove(isReplaced: true);
_flushHistoryUpdates();
assert(() {
_debugLocked = false;
return true;
}());
if (wasCurrent)
_afterNavigation(entry.route);
}
/// Replaces a route on the navigator with a new route. The route to be
/// replaced is the one below the given `anchorRoute`.
///
/// {@macro flutter.widgets.navigator.replaceRouteBelow}
///
/// See also:
///
/// * [replace], which is the same but identifies the route to be removed
/// directly.
/// * [restorableReplaceRouteBelow], which adds a replacement route that can
/// be restored during state restoration.
@optionalTypeArgs
void replaceRouteBelow<T extends Object?>({ required Route<dynamic> anchorRoute, required Route<T> newRoute }) {
assert(newRoute != null);
assert(newRoute._navigator == null);
assert(anchorRoute != null);
assert(anchorRoute._navigator == this);
_replaceEntryBelow(_RouteEntry(newRoute, initialState: _RouteLifecycle.replace), anchorRoute);
}
/// Replaces a route on the navigator with a new route. The route to be
/// replaced is the one below the given `anchorRoute`.
///
/// {@macro flutter.widgets.navigator.restorableReplaceRouteBelow}
///
/// {@macro flutter.widgets.navigator.replaceRouteBelow}
///
/// {@macro flutter.widgets.Navigator.restorablePush}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
@optionalTypeArgs
String restorableReplaceRouteBelow<T extends Object?>({ required Route<dynamic> anchorRoute, required RestorableRouteBuilder<T> newRouteBuilder, Object? arguments }) {
assert(anchorRoute != null);
assert(anchorRoute._navigator == this);
assert(newRouteBuilder != null);
assert(_debugIsStaticCallback(newRouteBuilder), 'The provided routeBuilder must be a static function.');
assert(debugIsSerializableForRestoration(arguments), 'The arguments object must be serializable via the StandardMessageCodec.');
assert(anchorRoute != null);
final _RouteEntry entry = _RestorationInformation.anonymous(
routeBuilder: newRouteBuilder,
arguments: arguments,
restorationScopeId: _nextPagelessRestorationScopeId,
).toRouteEntry(this, initialState: _RouteLifecycle.replace);
_replaceEntryBelow(entry, anchorRoute);
return entry.restorationId!;
}
void _replaceEntryBelow(_RouteEntry entry, Route<dynamic> anchorRoute) {
assert(!_debugLocked);
assert(() { _debugLocked = true; return true; }());
final int anchorIndex = _history.indexWhere(_RouteEntry.isRoutePredicate(anchorRoute));
assert(anchorIndex >= 0, 'This Navigator does not contain the specified anchorRoute.');
assert(_history[anchorIndex].isPresent, 'The specified anchorRoute has already been removed from the Navigator.');
int index = anchorIndex - 1;
while (index >= 0) {
if (_history[index].isPresent)
break;
index -= 1;
}
assert(index >= 0, 'There are no routes below the specified anchorRoute.');
_history.insert(index + 1, entry);
_history[index].remove(isReplaced: true);
_flushHistoryUpdates();
assert(() { _debugLocked = false; return true; }());
}
/// Whether the navigator can be popped.
///
/// {@macro flutter.widgets.navigator.canPop}
///
/// See also:
///
/// * [Route.isFirst], which returns true for routes for which [canPop]
/// returns false.
bool canPop() {
final Iterator<_RouteEntry> iterator = _history.where(_RouteEntry.isPresentPredicate).iterator;
if (!iterator.moveNext())
return false; // we have no active routes, so we can't pop
if (iterator.current.route.willHandlePopInternally)
return true; // the first route can handle pops itself, so we can pop
if (!iterator.moveNext())
return false; // there's only one route, so we can't pop
return true; // there's at least two routes, so we can pop
}
/// Consults the current route's [Route.willPop] method, and acts accordingly,
/// potentially popping the route as a result; returns whether the pop request
/// should be considered handled.
///
/// {@macro flutter.widgets.navigator.maybePop}
///
/// See also:
///
/// * [Form], which provides an `onWillPop` callback that enables the form
/// to veto a [pop] initiated by the app's back button.
/// * [ModalRoute], which provides a `scopedWillPopCallback` that can be used
/// to define the route's `willPop` method.
@optionalTypeArgs
Future<bool> maybePop<T extends Object?>([ T? result ]) async {
final _RouteEntry? lastEntry = _history.cast<_RouteEntry?>().lastWhere(
(_RouteEntry? e) => e != null && _RouteEntry.isPresentPredicate(e),
orElse: () => null,
);
if (lastEntry == null)
return false;
assert(lastEntry.route._navigator == this);
final RoutePopDisposition disposition = await lastEntry.route.willPop(); // this is asynchronous
assert(disposition != null);
if (!mounted)
return true; // forget about this pop, we were disposed in the meantime
final _RouteEntry? newLastEntry = _history.cast<_RouteEntry?>().lastWhere(
(_RouteEntry? e) => e != null && _RouteEntry.isPresentPredicate(e),
orElse: () => null,
);
if (lastEntry != newLastEntry)
return true; // forget about this pop, something happened to our history in the meantime
switch (disposition) {
case RoutePopDisposition.bubble:
return false;
case RoutePopDisposition.pop:
pop(result);
return true;
case RoutePopDisposition.doNotPop:
return true;
}
}
/// Pop the top-most route off the navigator.
///
/// {@macro flutter.widgets.navigator.pop}
///
/// {@tool snippet}
///
/// Typical usage for closing a route is as follows:
///
/// ```dart
/// void _handleClose() {
/// navigator.pop();
/// }
/// ```
/// {@end-tool}
/// {@tool snippet}
///
/// A dialog box might be closed with a result:
///
/// ```dart
/// void _handleAccept() {
/// navigator.pop(true); // dialog returns true
/// }
/// ```
/// {@end-tool}
@optionalTypeArgs
void pop<T extends Object?>([ T? result ]) {
assert(!_debugLocked);
assert(() {
_debugLocked = true;
return true;
}());
final _RouteEntry entry = _history.lastWhere(_RouteEntry.isPresentPredicate);
if (entry.hasPage) {
if (widget.onPopPage!(entry.route, result))
entry.currentState = _RouteLifecycle.pop;
} else {
entry.pop<T>(result);
}
if (entry.currentState == _RouteLifecycle.pop) {
// Flush the history if the route actually wants to be popped (the pop
// wasn't handled internally).
_flushHistoryUpdates(rearrangeOverlay: false);
assert(entry.route._popCompleter.isCompleted);
}
assert(() {
_debugLocked = false;
return true;
}());
_afterNavigation(entry.route);
}
/// Calls [pop] repeatedly until the predicate returns true.
///
/// {@macro flutter.widgets.navigator.popUntil}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _doLogout() {
/// navigator.popUntil(ModalRoute.withName('/login'));
/// }
/// ```
/// {@end-tool}
void popUntil(RoutePredicate predicate) {
_RouteEntry? candidate = _history.cast<_RouteEntry?>().lastWhere(
(_RouteEntry? e) => e != null && _RouteEntry.isPresentPredicate(e),
orElse: () => null,
);
while(candidate != null) {
if (predicate(candidate.route))
return;
pop();
candidate = _history.cast<_RouteEntry?>().lastWhere(
(_RouteEntry? e) => e != null && _RouteEntry.isPresentPredicate(e),
orElse: () => null,
);
}
}
/// Immediately remove `route` from the navigator, and [Route.dispose] it.
///
/// {@macro flutter.widgets.navigator.removeRoute}
void removeRoute(Route<dynamic> route) {
assert(route != null);
assert(!_debugLocked);
assert(() {
_debugLocked = true;
return true;
}());
assert(route._navigator == this);
final bool wasCurrent = route.isCurrent;
final _RouteEntry entry = _history.firstWhere(_RouteEntry.isRoutePredicate(route));
assert(entry != null);
entry.remove();
_flushHistoryUpdates(rearrangeOverlay: false);
assert(() {
_debugLocked = false;
return true;
}());
if (wasCurrent)
_afterNavigation(
_history.cast<_RouteEntry?>().lastWhere(
(_RouteEntry? e) => e != null && _RouteEntry.isPresentPredicate(e),
orElse: () => null,
)?.route,
);
}
/// Immediately remove a route from the navigator, and [Route.dispose] it. The
/// route to be removed is the one below the given `anchorRoute`.
///
/// {@macro flutter.widgets.navigator.removeRouteBelow}
void removeRouteBelow(Route<dynamic> anchorRoute) {
assert(!_debugLocked);
assert(() {
_debugLocked = true;
return true;
}());
assert(anchorRoute != null);
assert(anchorRoute._navigator == this);
final int anchorIndex = _history.indexWhere(_RouteEntry.isRoutePredicate(anchorRoute));
assert(anchorIndex >= 0, 'This Navigator does not contain the specified anchorRoute.');
assert(_history[anchorIndex].isPresent, 'The specified anchorRoute has already been removed from the Navigator.');
int index = anchorIndex - 1;
while (index >= 0) {
if (_history[index].isPresent)
break;
index -= 1;
}
assert(index >= 0, 'There are no routes below the specified anchorRoute.');
_history[index].remove();
_flushHistoryUpdates(rearrangeOverlay: false);
assert(() {
_debugLocked = false;
return true;
}());
}
/// Complete the lifecycle for a route that has been popped off the navigator.
///
/// When the navigator pops a route, the navigator retains a reference to the
/// route in order to call [Route.dispose] if the navigator itself is removed
/// from the tree. When the route is finished with any exit animation, the
/// route should call this function to complete its lifecycle (e.g., to
/// receive a call to [Route.dispose]).
///
/// The given `route` must have already received a call to [Route.didPop].
/// This function may be called directly from [Route.didPop] if [Route.didPop]
/// will return true.
void finalizeRoute(Route<dynamic> route) {
// FinalizeRoute may have been called while we were already locked as a
// responds to route.didPop(). Make sure to leave in the state we were in
// before the call.
bool? wasDebugLocked;
assert(() { wasDebugLocked = _debugLocked; _debugLocked = true; return true; }());
assert(_history.where(_RouteEntry.isRoutePredicate(route)).length == 1);
final _RouteEntry entry = _history.firstWhere(_RouteEntry.isRoutePredicate(route));
if (entry.doingPop) {
// We were called synchronously from Route.didPop(), but didn't process
// the pop yet. Let's do that now before finalizing.
entry.currentState = _RouteLifecycle.pop;
_flushHistoryUpdates(rearrangeOverlay: false);
}
assert(entry.currentState != _RouteLifecycle.pop);
entry.finalize();
_flushHistoryUpdates(rearrangeOverlay: false);
assert(() { _debugLocked = wasDebugLocked!; return true; }());
}
@optionalTypeArgs
Route<T>? _getRouteById<T>(String id) {
assert(id != null);
return _history.cast<_RouteEntry?>().firstWhere(
(_RouteEntry? entry) => entry!.restorationId == id,
orElse: () => null,
)?.route as Route<T>?;
}
int get _userGesturesInProgress => _userGesturesInProgressCount;
int _userGesturesInProgressCount = 0;
set _userGesturesInProgress(int value) {
_userGesturesInProgressCount = value;
userGestureInProgressNotifier.value = _userGesturesInProgress > 0;
}
/// Whether a route is currently being manipulated by the user, e.g.
/// as during an iOS back gesture.
///
/// See also:
///
/// * [userGestureInProgressNotifier], which notifies its listeners if
/// the value of [userGestureInProgress] changes.
bool get userGestureInProgress => userGestureInProgressNotifier.value;
/// Notifies its listeners if the value of [userGestureInProgress] changes.
final ValueNotifier<bool> userGestureInProgressNotifier = ValueNotifier<bool>(false);
/// The navigator is being controlled by a user gesture.
///
/// For example, called when the user beings an iOS back gesture.
///
/// When the gesture finishes, call [didStopUserGesture].
void didStartUserGesture() {
_userGesturesInProgress += 1;
if (_userGesturesInProgress == 1) {
final int routeIndex = _getIndexBefore(
_history.length - 1,
_RouteEntry.willBePresentPredicate,
);
assert(routeIndex != null);
final Route<dynamic> route = _history[routeIndex].route;
Route<dynamic>? previousRoute;
if (!route.willHandlePopInternally && routeIndex > 0) {
previousRoute = _getRouteBefore(
routeIndex - 1,
_RouteEntry.willBePresentPredicate,
)!.route;
}
for (final NavigatorObserver observer in _effectiveObservers)
observer.didStartUserGesture(route, previousRoute);
}
}
/// A user gesture completed.
///
/// Notifies the navigator that a gesture regarding which the navigator was
/// previously notified with [didStartUserGesture] has completed.
void didStopUserGesture() {
assert(_userGesturesInProgress > 0);
_userGesturesInProgress -= 1;
if (_userGesturesInProgress == 0) {
for (final NavigatorObserver observer in _effectiveObservers)
observer.didStopUserGesture();
}
}
final Set<int> _activePointers = <int>{};
void _handlePointerDown(PointerDownEvent event) {
_activePointers.add(event.pointer);
}
void _handlePointerUpOrCancel(PointerEvent event) {
_activePointers.remove(event.pointer);
}
void _cancelActivePointers() {
// TODO(abarth): This mechanism is far from perfect. See https://github.com/flutter/flutter/issues/4770
if (SchedulerBinding.instance!.schedulerPhase == SchedulerPhase.idle) {
// If we're between frames (SchedulerPhase.idle) then absorb any
// subsequent pointers from this frame. The absorbing flag will be
// reset in the next frame, see build().
final RenderAbsorbPointer? absorber = _overlayKey.currentContext?.findAncestorRenderObjectOfType<RenderAbsorbPointer>();
setState(() {
absorber?.absorbing = true;
// We do this in setState so that we'll reset the absorbing value back
// to false on the next frame.
});
}
_activePointers.toList().forEach(WidgetsBinding.instance!.cancelPointer);
}
@override
Widget build(BuildContext context) {
assert(!_debugLocked);
assert(_history.isNotEmpty);
// Hides the HeroControllerScope for the widget subtree so that the other
// nested navigator underneath will not pick up the hero controller above
// this level.
return HeroControllerScope.none(
child: Listener(
onPointerDown: _handlePointerDown,
onPointerUp: _handlePointerUpOrCancel,
onPointerCancel: _handlePointerUpOrCancel,
child: AbsorbPointer(
absorbing: false, // it's mutated directly by _cancelActivePointers above
child: FocusScope(
node: focusScopeNode,
autofocus: true,
child: UnmanagedRestorationScope(
bucket: bucket,
child: Overlay(
key: _overlayKey,
initialEntries: overlay == null ? _allRouteOverlayEntries.toList(growable: false) : const <OverlayEntry>[],
),
),
),
),
),
);
}
}
enum _RouteRestorationType {
named,
anonymous,
}
abstract class _RestorationInformation {
_RestorationInformation(this.type) : assert(type != null);
factory _RestorationInformation.named({
required String name,
required Object? arguments,
required int restorationScopeId,
}) = _NamedRestorationInformation;
factory _RestorationInformation.anonymous({
required RestorableRouteBuilder routeBuilder,
required Object? arguments,
required int restorationScopeId,
}) = _AnonymousRestorationInformation;
factory _RestorationInformation.fromSerializableData(Object data) {
assert(data != null);
final List<Object?> casted = data as List<Object?>;
assert(casted.isNotEmpty);
final _RouteRestorationType type = _RouteRestorationType.values[casted[0]! as int];
assert(type != null);
switch (type) {
case _RouteRestorationType.named:
return _NamedRestorationInformation.fromSerializableData(casted.sublist(1));
case _RouteRestorationType.anonymous:
return _AnonymousRestorationInformation.fromSerializableData(casted.sublist(1));
}
}
final _RouteRestorationType type;
int get restorationScopeId;
Object? _serializableData;
bool get isRestorable => true;
Object getSerializableData() {
_serializableData ??= computeSerializableData();
return _serializableData!;
}
@mustCallSuper
List<Object> computeSerializableData() {
return <Object>[type.index];
}
@protected
Route<dynamic> createRoute(NavigatorState navigator);
_RouteEntry toRouteEntry(NavigatorState navigator, {_RouteLifecycle initialState = _RouteLifecycle.add}) {
assert(navigator != null);
assert(initialState != null);
final Route<Object?> route = createRoute(navigator);
assert(route != null);
return _RouteEntry(
route,
initialState: initialState,
restorationInformation: this,
);
}
}
class _NamedRestorationInformation extends _RestorationInformation {
_NamedRestorationInformation({
required this.name,
required this.arguments,
required this.restorationScopeId,
}) : assert(name != null), super(_RouteRestorationType.named);
factory _NamedRestorationInformation.fromSerializableData(List<Object?> data) {
assert(data.length >= 2);
return _NamedRestorationInformation(
restorationScopeId: data[0]! as int,
name: data[1]! as String,
arguments: data.length > 2 ? data[2] : null,
);
}
@override
List<Object> computeSerializableData() {
return super.computeSerializableData()..addAll(<Object>[
restorationScopeId,
name,
if (arguments != null)
arguments!,
]);
}
@override
final int restorationScopeId;
final String name;
final Object? arguments;
@override
Route<dynamic> createRoute(NavigatorState navigator) {
final Route<dynamic> route = navigator._routeNamed<dynamic>(name, arguments: arguments, allowNull: false)!;
assert(route != null);
return route;
}
}
class _AnonymousRestorationInformation extends _RestorationInformation {
_AnonymousRestorationInformation({
required this.routeBuilder,
required this.arguments,
required this.restorationScopeId,
}) : assert(routeBuilder != null), super(_RouteRestorationType.anonymous);
factory _AnonymousRestorationInformation.fromSerializableData(List<Object?> data) {
assert(data.length > 1);
final RestorableRouteBuilder routeBuilder = ui.PluginUtilities.getCallbackFromHandle(ui.CallbackHandle.fromRawHandle(data[1]! as int))! as RestorableRouteBuilder;
return _AnonymousRestorationInformation(
restorationScopeId: data[0]! as int,
routeBuilder: routeBuilder,
arguments: data.length > 2 ? data[2] : null,
);
}
@override
// TODO(goderbauer): remove the kIsWeb check when https://github.com/flutter/flutter/issues/33615 is resolved.
bool get isRestorable => !kIsWeb;
@override
List<Object> computeSerializableData() {
assert(isRestorable);
final ui.CallbackHandle? handle = ui.PluginUtilities.getCallbackHandle(routeBuilder);
assert(handle != null);
return super.computeSerializableData()..addAll(<Object>[
restorationScopeId,
handle!.toRawHandle(),
if (arguments != null)
arguments!,
]);
}
@override
final int restorationScopeId;
final RestorableRouteBuilder routeBuilder;
final Object? arguments;
@override
Route<dynamic> createRoute(NavigatorState navigator) {
final Route<dynamic> result = routeBuilder(navigator.context, arguments);
assert(result != null);
return result;
}
}
class _HistoryProperty extends RestorableProperty<Map<String?, List<Object>>?> {
// Routes not associated with a page are stored under key 'null'.
Map<String?, List<Object>>? _pageToPagelessRoutes;
// Updating.
void update(List<_RouteEntry> history) {
assert(isRegistered);
final bool wasUninitialized = _pageToPagelessRoutes == null;
bool needsSerialization = wasUninitialized;
_pageToPagelessRoutes ??= <String, List<Object>>{};
_RouteEntry? currentPage;
List<Object> newRoutesForCurrentPage = <Object>[];
List<Object> oldRoutesForCurrentPage = _pageToPagelessRoutes![null] ?? const <Object>[];
bool restorationEnabled = true;
final Map<String?, List<Object>> newMap = <String?, List<Object>>{};
final Set<String?> removedPages = _pageToPagelessRoutes!.keys.toSet();
for (final _RouteEntry entry in history) {
if (!entry.isPresentForRestoration) {
entry.restorationEnabled = false;
continue;
}
assert(entry.isPresentForRestoration);
if (entry.hasPage) {
needsSerialization = needsSerialization || newRoutesForCurrentPage.length != oldRoutesForCurrentPage.length;
_finalizePage(newRoutesForCurrentPage, currentPage, newMap, removedPages);
currentPage = entry;
restorationEnabled = entry.restorationId != null;
entry.restorationEnabled = restorationEnabled;
if (restorationEnabled) {
assert(entry.restorationId != null);
newRoutesForCurrentPage = <Object>[];
oldRoutesForCurrentPage = _pageToPagelessRoutes![entry.restorationId] ?? const <Object>[];
} else {
newRoutesForCurrentPage = const <Object>[];
oldRoutesForCurrentPage = const <Object>[];
}
continue;
}
assert(!entry.hasPage);
restorationEnabled = restorationEnabled && entry.restorationInformation?.isRestorable == true;
entry.restorationEnabled = restorationEnabled;
if (restorationEnabled) {
assert(entry.restorationId != null);
assert(currentPage == null || currentPage.restorationId != null);
assert(entry.restorationInformation != null);
final Object serializedData = entry.restorationInformation!.getSerializableData();
needsSerialization = needsSerialization
|| oldRoutesForCurrentPage.length <= newRoutesForCurrentPage.length
|| oldRoutesForCurrentPage[newRoutesForCurrentPage.length] != serializedData;
newRoutesForCurrentPage.add(serializedData);
}
}
needsSerialization = needsSerialization || newRoutesForCurrentPage.length != oldRoutesForCurrentPage.length;
_finalizePage(newRoutesForCurrentPage, currentPage, newMap, removedPages);
needsSerialization = needsSerialization || removedPages.isNotEmpty;
assert(wasUninitialized || _debugMapsEqual(_pageToPagelessRoutes!, newMap) != needsSerialization);
if (needsSerialization) {
_pageToPagelessRoutes = newMap;
notifyListeners();
}
}
void _finalizePage(
List<Object> routes,
_RouteEntry? page,
Map<String?, List<Object>> pageToRoutes,
Set<String?> pagesToRemove,
) {
assert(page == null || page.hasPage);
assert(pageToRoutes != null);
assert(!pageToRoutes.containsKey(page?.restorationId));
if (routes != null && routes.isNotEmpty) {
assert(page == null || page.restorationId != null);
final String? restorationId = page?.restorationId;
pageToRoutes[restorationId] = routes;
pagesToRemove.remove(restorationId);
}
}
bool _debugMapsEqual(Map<String?, List<Object>> a, Map<String?, List<Object>> b) {
if (!setEquals(a.keys.toSet(), b.keys.toSet())) {
return false;
}
for (final String? key in a.keys) {
if (!listEquals(a[key], b[key])) {
return false;
}
}
return true;
}
void clear() {
assert(isRegistered);
if (_pageToPagelessRoutes == null) {
return;
}
_pageToPagelessRoutes = null;
notifyListeners();
}
// Restoration.
bool get hasData => _pageToPagelessRoutes != null;
List<_RouteEntry> restoreEntriesForPage(_RouteEntry? page, NavigatorState navigator) {
assert(isRegistered);
assert(page == null || page.hasPage);
final List<_RouteEntry> result = <_RouteEntry>[];
if (_pageToPagelessRoutes == null || (page != null && page.restorationId == null)) {
return result;
}
final List<Object>? serializedData = _pageToPagelessRoutes![page?.restorationId];
if (serializedData == null) {
return result;
}
for (final Object data in serializedData) {
result.add(_RestorationInformation.fromSerializableData(data).toRouteEntry(navigator));
}
return result;
}
// RestorableProperty overrides.
@override
Map<String?, List<Object>>? createDefaultValue() {
return null;
}
@override
Map<String?, List<Object>>? fromPrimitives(Object? data) {
final Map<dynamic, dynamic> casted = data! as Map<dynamic, dynamic>;
return casted.map<String?, List<Object>>((dynamic key, dynamic value) => MapEntry<String?, List<Object>>(
key as String?,
List<Object>.from(value as List<dynamic>, growable: true),
));
}
@override
void initWithValue(Map<String?, List<Object>>? value) {
_pageToPagelessRoutes = value;
}
@override
Object? toPrimitives() {
return _pageToPagelessRoutes;
}
@override
bool get enabled => hasData;
}
/// A callback that given a [BuildContext] finds a [NavigatorState].
///
/// Used by [RestorableRouteFuture.navigatorFinder] to determine the navigator
/// to which a new route should be added.
typedef NavigatorFinderCallback = NavigatorState Function(BuildContext context);
/// A callback that given some `arguments` and a `navigator` adds a new
/// restorable route to that `navigator` and returns the opaque ID of that
/// new route.
///
/// Usually, this callback calls one of the imperative methods on the Navigator
/// that have "restorable" in the name and returns their return value.
///
/// Used by [RestorableRouteFuture.onPresent].
typedef RoutePresentationCallback = String Function(NavigatorState navigator, Object? arguments);
/// A callback to handle the result of a completed [Route].
///
/// The return value of the route (which can be null for e.g. void routes) is
/// passed to the callback.
///
/// Used by [RestorableRouteFuture.onComplete].
typedef RouteCompletionCallback<T> = void Function(T result);
/// Gives access to a [Route] object and its return value that was added to a
/// navigator via one of its "restorable" API methods.
///
/// When a [State] object wants access to the return value of a [Route] object
/// it has pushed onto the [Navigator], a [RestorableRouteFuture] ensures that
/// it will also have access to that value after state restoration.
///
/// To show a new route on the navigator defined by the [navigatorFinder], call
/// [present], which will invoke the [onPresent] callback. The [onPresent]
/// callback must add a new route to the navigator provided to it using one
/// of the "restorable" API methods. When the newly added route completes, the
/// [onComplete] callback executes. It is given the return value of the route,
/// which may be null.
///
/// While the route added via [present] is shown on the navigator, it can be
/// accessed via the [route] getter.
///
/// If the property is restored to a state in which [present] had been called on
/// it, but the route has not completed yet, the [RestorableRouteFuture] will
/// obtain the restored route object from the navigator again and call
/// [onComplete] once it completes.
///
/// The [RestorableRouteFuture] can only keep track of one active [route].
/// When [present] has been called to add a route, it may only be called again
/// after the previously added route has completed.
///
/// {@tool dartpad --template=freeform}
/// This example uses a [RestorableRouteFuture] in the `_MyHomeState` to push a
/// new `MyCounter` route and to retrieve its return value.
///
/// ** See code in examples/api/lib/widgets/navigator/restorable_route_future.0.dart **
/// {@end-tool}
class RestorableRouteFuture<T> extends RestorableProperty<String?> {
/// Creates a [RestorableRouteFuture].
///
/// The [onPresent] and [navigatorFinder] arguments must not be null.
RestorableRouteFuture({
this.navigatorFinder = _defaultNavigatorFinder,
required this.onPresent,
this.onComplete,
}) : assert(onPresent != null), assert(navigatorFinder != null);
/// A callback that given the [BuildContext] of the [State] object to which
/// this property is registered returns the [NavigatorState] of the navigator
/// to which the route instantiated in [onPresent] is added.
final NavigatorFinderCallback navigatorFinder;
/// A callback that add a new [Route] to the provided navigator.
///
/// The callback must use one of the API methods on the [NavigatorState] that
/// have "restorable" in their name (e.g. [NavigatorState.restorablePush],
/// [NavigatorState.restorablePushNamed], etc.) and return the opaque ID
/// returned by those methods.
///
/// This callback is invoked when [present] is called with the `arguments`
/// Object that was passed to that method and the [NavigatorState] obtained
/// from [navigatorFinder].
final RoutePresentationCallback onPresent;
/// A callback that is invoked when the [Route] added via [onPresent]
/// completes.
///
/// The return value of that route is passed to this method.
final RouteCompletionCallback<T>? onComplete;
/// Shows the route created by [onPresent] and invoke [onComplete] when it
/// completes.
///
/// The `arguments` object is passed to [onPresent] and can be used to
/// customize the route. It must be serializable via the
/// [StandardMessageCodec]. Often, a [Map] is used to pass key-value pairs.
void present([Object? arguments]) {
assert(!isPresent);
assert(isRegistered);
final String routeId = onPresent(_navigator, arguments);
assert(routeId != null);
_hookOntoRouteFuture(routeId);
notifyListeners();
}
/// Whether the [Route] created by [present] is currently shown.
///
/// Returns true after [present] has been called until the [Route] completes.
bool get isPresent => route != null;
/// The route that [present] added to the Navigator.
///
/// Returns null when currently no route is shown
Route<T>? get route => _route;
Route<T>? _route;
@override
String? createDefaultValue() => null;
@override
void initWithValue(String? value) {
if (value != null) {
_hookOntoRouteFuture(value);
}
}
@override
Object? toPrimitives() {
assert(route != null);
assert(enabled);
return route?.restorationScopeId.value;
}
@override
String fromPrimitives(Object? data) {
assert(data != null);
return data! as String;
}
bool _disposed = false;
@override
void dispose() {
super.dispose();
_route?.restorationScopeId.removeListener(notifyListeners);
_disposed = true;
}
@override
bool get enabled => route?.restorationScopeId.value != null;
NavigatorState get _navigator {
final NavigatorState navigator = navigatorFinder(state.context);
assert(navigator != null);
return navigator;
}
void _hookOntoRouteFuture(String id) {
assert(id != null);
_route = _navigator._getRouteById<T>(id);
assert(_route != null);
route!.restorationScopeId.addListener(notifyListeners);
route!.popped.then((dynamic result) {
if (_disposed) {
return;
}
_route?.restorationScopeId.removeListener(notifyListeners);
_route = null;
notifyListeners();
onComplete?.call(result as T);
});
}
static NavigatorState _defaultNavigatorFinder(BuildContext context) => Navigator.of(context);
}