waft-widgets 0.10.1

Widget framework and widgets for Waft
Documentation
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
//! Flutter counterpart: `widgets/form.dart`.
//!
//! A [`Form`] groups the [`FormField`]s below it: each field's state registers with the form's
//! [`FormState`] while it builds, and the form saves, resets and validates them together.
//!
//! [`FormField`] and [`FormFieldState`] are Dart classes that Material subclasses
//! (`TextFormField`, `DropdownButtonFormField`, `DropdownMenuFormField`). A subclass is a leaf:
//! its widget carries a [`FormFieldData`] and implements [`FormFieldLeaf`], its state carries a
//! [`FormFieldStateData`] and implements [`FormFieldStateLeaf`], and the bodies Dart inherits
//! are associated functions on [`FormFieldState`] that a leaf calls where Dart writes `super`.
//! A form holds its fields erased, as [`DynamicFormFieldState`]s, Dart's
//! `FormFieldState<dynamic>`, and a field's builder is handed its state as
//! [`AnyFormFieldState`], Dart's `FormFieldState<T>`; both dispatch the virtuals to the leaf.

use std::any::Any;
use std::fmt::{self, Debug};
use std::rc::Rc;

use indexmap::IndexSet;
use waft_embedder::{SemanticsRole, SemanticsValidationResult};
use waft_foundation::{App, Handle, HandleId, OptionRetained, VoidCallback};
use waft_scheduler::{FrameCallback, SchedulerBinding};
use waft_services::RestorationBucket;

use crate::framework::{
    BuildContext, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
};
use crate::view::View;
use crate::widgets::basic::Semantics;
use crate::widgets::focus_manager::FocusNode;
use crate::widgets::focus_manager::FocusNodeLeaf;
use crate::widgets::focus_scope::Focus;
use crate::widgets::navigator::RouteResult;
use crate::widgets::pop_scope::PopScope;
use crate::widgets::restoration::{RestorableProperty, RestorationMixin, RestorationMixinData};
use crate::widgets::restoration_properties::{RestorableBool, RestorableStringN, RestorableValue};
use crate::widgets::routes::PopInvokedWithResultCallback;
use waft_foundation::Ref;

// ---------------------------------------------------------------------------------------------
// Form

/// An optional container for grouping together multiple form field widgets (e.g. `TextField`
/// widgets).
///
/// Each individual form field should be wrapped in a [`FormField`] widget, with the [`Form`]
/// widget as a common ancestor of all of those. Call methods on [`FormState`] to save, reset, or
/// validate each [`FormField`] that is a descendant of this [`Form`]. To obtain the
/// [`FormState`], you may use [`Form::of`] with a context whose ancestor is the [`Form`], or pass
/// a `GlobalKey` to the [`Form`] constructor and call `GlobalKey::current_state`.
///
/// See also:
///
///  * `GlobalKey`, a key that is unique across the entire app.
///  * [`FormField`], a single form field widget that maintains the current state.
///  * `TextFormField`, a convenience widget that wraps a `TextField` widget in a [`FormField`].
pub struct Form {
    /// See [`StatefulWidget::key`].
    pub key: Option<KeyRef>,

    /// The widget below this widget in the tree.
    ///
    /// This is the root of the widget hierarchy that contains this form.
    pub child: WidgetRef,

    /// When false, blocks the current route from being popped.
    ///
    /// See also:
    ///
    ///  * [`on_pop_invoked_with_result`](Self::on_pop_invoked_with_result), which also comes
    ///    from [`PopScope`] and is often used in conjunction with this parameter.
    ///  * [`PopScope::can_pop`], which is what [`Form`] delegates to internally.
    pub can_pop: Option<bool>,

    /// Called after a route pop was handled; see [`PopScope::on_pop_invoked_with_result`].
    ///
    /// See also:
    ///
    ///  * [`can_pop`](Self::can_pop), which also comes from [`PopScope`] and is often used in
    ///    conjunction with this parameter.
    ///  * [`PopScope::on_pop_invoked_with_result`], which is what [`Form`] delegates to
    ///    internally.
    pub on_pop_invoked_with_result: Option<PopInvokedWithResultCallback>,

    /// Called when one of the form fields changes.
    ///
    /// In addition to this callback being invoked, all the form fields themselves will rebuild.
    pub on_changed: Option<VoidCallback>,

    /// Used to enable/disable form fields auto validation and update their error text.
    ///
    /// If [`AutovalidateMode::OnUserInteraction`], this form will only auto-validate after its
    /// content changes. If [`AutovalidateMode::Always`], it will auto-validate even without user
    /// interaction. If [`AutovalidateMode::Disabled`], auto-validation will be disabled.
    ///
    /// Defaults to [`AutovalidateMode::Disabled`].
    pub autovalidate_mode: AutovalidateMode,
}

impl Form {
    /// Creates a container for form fields.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn new<K>(child: impl IntoWidget<K>) -> Form {
        Form {
            key: None,
            child: child.into_widget(),
            can_pop: None,
            on_pop_invoked_with_result: None,
            on_changed: None,
            autovalidate_mode: AutovalidateMode::Disabled,
        }
    }

    /// Dart `Form(key:)`.
    pub fn key(mut self, key: KeyRef) -> Form {
        self.key = Some(key);
        self
    }

    /// Dart `Form(canPop:)`.
    pub fn can_pop(mut self, can_pop: bool) -> Form {
        self.can_pop = Some(can_pop);
        self
    }

    /// Dart `Form(onPopInvokedWithResult:)`.
    pub fn on_pop_invoked_with_result(
        mut self,
        on_pop_invoked_with_result: PopInvokedWithResultCallback,
    ) -> Form {
        self.on_pop_invoked_with_result = Some(on_pop_invoked_with_result);
        self
    }

    /// Dart `Form(onChanged:)`.
    pub fn on_changed(mut self, on_changed: impl Fn(&mut App) + 'static) -> Form {
        self.on_changed = Some(Rc::new(on_changed));
        self
    }

    /// Dart `Form(autovalidateMode:)`.
    pub fn autovalidate_mode(mut self, autovalidate_mode: AutovalidateMode) -> Form {
        self.autovalidate_mode = autovalidate_mode;
        self
    }

    /// Returns the [`FormState`] of the closest [`Form`] widget which encloses the given
    /// context, or `None` if none is found.
    ///
    /// Calling this method will create a dependency on the closest [`Form`] in the `context`,
    /// if there is one.
    ///
    /// See also:
    ///
    /// * [`Form::of`], which is similar to this method, but panics if no [`Form`] ancestor is
    ///   found.
    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<Handle<FormState>> {
        context
            .depend_on_inherited_widget_of_exact_type::<FormScope>(app)
            .map(|scope| scope.form_state)
    }

    /// Returns the [`FormState`] of the closest [`Form`] widget which encloses the given
    /// context.
    ///
    /// If no [`Form`] ancestor is found, this panics.
    ///
    /// Calling this method will create a dependency on the closest [`Form`] in the `context`.
    ///
    /// See also:
    ///
    /// * [`Form::maybe_of`], which is similar to this method, but returns `None` if no [`Form`]
    ///   ancestor is found.
    pub fn of(app: &mut App, context: BuildContext) -> Handle<FormState> {
        let form_state = Form::maybe_of(app, context);
        form_state.unwrap_or_else(|| {
            panic!(
                "Form.of() was called with a context that does not contain a Form widget.\n\
                 No Form widget ancestor could be found starting from the context that was \
                 passed to Form.of(). This can happen because you are using a widget that looks \
                 for a Form ancestor, but no such ancestor exists.\n\
                 The context used was:\n  {}",
                context.widget(app).type_name()
            )
        })
    }

    /// Dart's `_callPopInvoked` tear-off, which the form hands its [`PopScope`].
    fn call_pop_invoked(&self) -> PopInvokedWithResultCallback {
        let on_pop_invoked_with_result = self.on_pop_invoked_with_result.clone();
        Rc::new(move |app: &mut App, did_pop: bool, result: RouteResult| {
            if let Some(on_pop_invoked_with_result) = &on_pop_invoked_with_result {
                on_pop_invoked_with_result(app, did_pop, result);
            }
        })
    }
}

impl Debug for Form {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Form")
            .field("can_pop", &self.can_pop)
            .field("autovalidate_mode", &self.autovalidate_mode)
            .finish_non_exhaustive()
    }
}

impl StatefulWidget for Form {
    type State = FormState;

    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn create_state(&self) -> FormState {
        FormState {
            state: StateData::new(),
            generation: 0,
            has_interacted_by_user: false,
            fields: IndexSet::new(),
        }
    }
}

/// State associated with a [`Form`] widget.
///
/// A [`FormState`] object can be used to [`save`](Self::save), [`reset`](Self::reset), and
/// [`validate`](Self::validate) every [`FormField`] that is a descendant of the associated
/// [`Form`].
///
/// Typically obtained via [`Form::of`].
pub struct FormState {
    state: StateData<Form>,
    generation: i64,
    has_interacted_by_user: bool,
    fields: IndexSet<DynamicFormFieldState>,
}

impl FormState {
    /// The [`FormFieldState`] objects that are currently registered with this [`Form`].
    pub fn fields(self: Handle<Self>, app: &App) -> Vec<DynamicFormFieldState> {
        app.get(self).fields.iter().copied().collect()
    }

    // Called when a form field has changed. This will cause all form fields
    // to rebuild, useful if form fields have interdependencies.
    fn field_did_change(self: Handle<Self>, app: &mut App) {
        if let Some(on_changed) = self.widget(app).on_changed.clone() {
            on_changed(app);
        }

        let fields = self.fields(app);
        let has_interacted_by_user = fields
            .into_iter()
            .any(|field| field.has_interacted_by_user(app));
        app.get_mut(self).has_interacted_by_user = has_interacted_by_user;

        self.force_rebuild(app);
    }

    fn force_rebuild(self: Handle<Self>, app: &mut App) {
        self.set_state(app, |state| {
            state.generation += 1;
        });
    }

    fn register(self: Handle<Self>, app: &mut App, field: DynamicFormFieldState) {
        app.get_mut(self).fields.insert(field);
    }

    fn unregister(self: Handle<Self>, app: &mut App, field: DynamicFormFieldState) {
        app.get_mut(self).fields.shift_remove(&field);
    }

    /// Saves every [`FormField`] that is a descendant of this [`Form`].
    pub fn save(self: Handle<Self>, app: &mut App) {
        for field in self.fields(app) {
            field.save(app);
        }
    }

    /// Resets every [`FormField`] that is a descendant of this [`Form`] back to its
    /// [`FormFieldData::initial_value`].
    ///
    /// The [`Form::on_changed`] callback will be called.
    ///
    /// If the form's [`Form::autovalidate_mode`] property is [`AutovalidateMode::Always`], the
    /// fields will all be revalidated after being reset.
    pub fn reset(self: Handle<Self>, app: &mut App) {
        for field in self.fields(app) {
            field.reset(app);
        }
        app.get_mut(self).has_interacted_by_user = false;
        self.field_did_change(app);
    }

    /// Clears the validation errors for all [`FormField`]s in this [`Form`] without resetting
    /// their values.
    ///
    /// See also:
    ///
    ///  * [`FormFieldStateLeaf::clear_error`], which clears the error for a single form field.
    pub fn clear_error(self: Handle<Self>, app: &mut App) {
        for field in self.fields(app) {
            field.clear_error_internal(app);
        }
        self.field_did_change(app);
    }

    /// Validates every [`FormField`] that is a descendant of this [`Form`], and returns true if
    /// there are no errors.
    ///
    /// The form will rebuild to report the results.
    ///
    /// See also:
    ///  * [`validate_granularly`](Self::validate_granularly), which also validates descendant
    ///    [`FormField`]s, but instead returns a set of fields with errors.
    pub fn validate(self: Handle<Self>, app: &mut App) -> bool {
        app.get_mut(self).has_interacted_by_user = true;
        self.force_rebuild(app);
        self.validate_fields(app, None)
    }

    /// Validates every [`FormField`] that is a descendant of this [`Form`], and returns a set
    /// of [`DynamicFormFieldState`] of the invalid field(s) only, if any.
    ///
    /// This method can be useful to highlight field(s) with errors.
    ///
    /// The form will rebuild to report the results.
    ///
    /// See also:
    ///  * [`validate`](Self::validate), which also validates descendant [`FormField`]s, and
    ///    return true if there are no errors.
    pub fn validate_granularly(
        self: Handle<Self>,
        app: &mut App,
    ) -> IndexSet<DynamicFormFieldState> {
        let mut invalid_fields = IndexSet::new();
        app.get_mut(self).has_interacted_by_user = true;
        self.force_rebuild(app);
        self.validate_fields(app, Some(&mut invalid_fields));
        invalid_fields
    }

    /// Dart's `_validate`.
    fn validate_fields(
        self: Handle<Self>,
        app: &mut App,
        mut invalid_fields: Option<&mut IndexSet<DynamicFormFieldState>>,
    ) -> bool {
        let mut has_error = false;
        let validate_on_focus_change =
            self.widget(app).autovalidate_mode == AutovalidateMode::OnUnfocus;

        for field in self.fields(app) {
            let has_focus = field.focus_node(app).as_node().has_focus(app);

            if !validate_on_focus_change || !has_focus || (validate_on_focus_change && has_focus) {
                let is_field_valid = field.validate(app);
                has_error |= !is_field_valid;
                if let Some(invalid_fields) = invalid_fields.as_deref_mut()
                    && !is_field_valid
                {
                    invalid_fields.insert(field);
                }
            }
        }

        !has_error
    }
}

impl State for FormState {
    type Widget = Form;
    crate::state_accessors!();

    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
        let has_error = self
            .fields(app)
            .into_iter()
            .any(|field| field.has_error(app));

        match self.widget(app).autovalidate_mode {
            AutovalidateMode::Always => {
                self.validate_fields(app, None);
            }
            AutovalidateMode::OnUserInteraction => {
                if app.get(self).has_interacted_by_user {
                    self.validate_fields(app, None);
                }
            }
            AutovalidateMode::OnUserInteractionIfError => {
                if app.get(self).has_interacted_by_user && has_error {
                    self.validate_fields(app, None);
                }
            }
            AutovalidateMode::OnUnfocus | AutovalidateMode::Disabled => {}
        }

        let generation = app.get(self).generation;
        let widget = self.widget(app);
        let scope = FormScope {
            form_state: self,
            generation,
            child: widget.child.clone(),
        };
        let form = if widget.can_pop.is_some() || widget.on_pop_invoked_with_result.is_some() {
            PopScope::new(scope)
                .can_pop(widget.can_pop.unwrap_or(true))
                .on_pop_invoked_with_result(widget.call_pop_invoked())
                .into_widget()
        } else {
            scope.into_widget()
        };
        Semantics::new()
            .container(true)
            .explicit_child_nodes(true)
            .role(SemanticsRole::Form)
            .child(form)
            .into_widget()
    }
}

/// Dart's `_FormScope`: hands a [`Form`]'s state to the fields below it, and rebuilds them
/// each time a field changes.
#[derive(Debug)]
struct FormScope {
    form_state: Handle<FormState>,

    /// Incremented every time a form field has changed. This lets us know when to rebuild the
    /// form.
    generation: i64,

    child: WidgetRef,
}

impl InheritedWidget for FormScope {
    fn child(&self) -> &WidgetRef {
        &self.child
    }

    fn update_should_notify(&self, old: &FormScope) -> bool {
        self.generation != old.generation
    }
}

// ---------------------------------------------------------------------------------------------
// FormField

/// Signature for validating a form field.
///
/// Returns an error string to display if the input is invalid, or `None` otherwise.
///
/// Used by [`FormFieldData::validator`].
pub type FormFieldValidator<T> = Rc<dyn Fn(&mut App, Option<&T>) -> Option<String>>;

/// Signature for a callback that builds an error widget.
///
/// See also:
///
///  * [`FormFieldData::error_builder`], which is of this type, and passes the result error
///    given by `TextFormField.validator`.
pub type FormFieldErrorBuilder = Rc<dyn Fn(&mut App, BuildContext, String) -> WidgetRef>;

/// Signature for being notified when a form field changes value.
///
/// Used by [`FormFieldData::on_saved`].
pub type FormFieldSetter<T> = Rc<dyn Fn(&mut App, Option<T>)>;

/// Signature for building the widget representing the form field.
///
/// Used by [`FormFieldData::builder`].
pub type FormFieldBuilder<T> = Rc<dyn Fn(&mut App, AnyFormFieldState<T>) -> WidgetRef>;

/// The fields of Dart's `FormField<T>`, which [`FormField`] and its subclasses carry under the
/// field `form_field`.
pub struct FormFieldData<T: 'static> {
    /// See [`StatefulWidget::key`].
    pub key: Option<KeyRef>,

    /// Function that returns the widget representing this form field.
    ///
    /// It is passed the form field state as input, containing the current value and validation
    /// state of this field.
    pub builder: FormFieldBuilder<T>,

    /// An optional method to call with the final value when the form is saved via
    /// [`FormState::save`].
    pub on_saved: Option<FormFieldSetter<T>>,

    /// An optional method to call when the form field is reset via
    /// [`FormFieldStateLeaf::reset`].
    pub on_reset: Option<VoidCallback>,

    /// An optional property that forces the [`FormFieldState`] into an error state by directly
    /// setting the [`FormFieldStateLeaf::error_text`] property without running the validator
    /// function.
    ///
    /// When the [`force_error_text`](Self::force_error_text) property is provided, the
    /// [`FormFieldStateLeaf::error_text`] will be set to the provided value, causing the form
    /// field to be considered invalid and to display the error message specified.
    ///
    /// When [`validator`](Self::validator) is provided,
    /// [`force_error_text`](Self::force_error_text) will override any error that it returns.
    /// [`validator`](Self::validator) will not be called unless
    /// [`force_error_text`](Self::force_error_text) is `None`.
    pub force_error_text: Option<String>,

    /// An optional method that validates an input. Returns an error string to display if the
    /// input is invalid, or `None` otherwise.
    ///
    /// The returned value is exposed by the [`FormFieldStateLeaf::error_text`] property. The
    /// `TextFormField` uses this to override the `InputDecoration.errorText` value.
    ///
    /// Alternating between error and normal state can cause the height of the `TextFormField`
    /// to change if no other subtext decoration is set on the field. To create a field whose
    /// height is fixed regardless of whether or not an error is displayed, either wrap the
    /// `TextFormField` in a fixed height parent like `SizedBox`, or set the
    /// `InputDecoration.helperText` parameter to a space.
    pub validator: Option<FormFieldValidator<T>>,

    /// Function that returns the widget representing the error to display.
    ///
    /// It is passed the form field validator error string as input. The resulting widget is
    /// passed to `InputDecoration.error`.
    ///
    /// If `None`, the validator error string is passed to `InputDecoration.errorText`.
    pub error_builder: Option<FormFieldErrorBuilder>,

    /// An optional value to initialize the form field to, or `None` otherwise.
    ///
    /// The `initial_value` affects the form field's state in two cases:
    /// 1. When the form field is first built, `initial_value` determines the field's initial
    ///    state.
    /// 2. When [`FormFieldStateLeaf::reset`] is called (either directly or by calling
    ///    [`FormState::reset`]), the form field is reset to this `initial_value`.
    pub initial_value: Option<T>,

    /// Whether the form is able to receive user input.
    ///
    /// Defaults to true. If [`autovalidate_mode`](Self::autovalidate_mode) is not
    /// [`AutovalidateMode::Disabled`], the field will be auto validated. Likewise, if this field
    /// is false, the widget will not be validated regardless of
    /// [`autovalidate_mode`](Self::autovalidate_mode).
    pub enabled: bool,

    /// Used to enable/disable this form field auto validation and update its error text.
    ///
    /// If [`AutovalidateMode::OnUserInteraction`], this FormField will only auto-validate after
    /// its content changes. If [`AutovalidateMode::Always`], it will auto-validate even without
    /// user interaction. If [`AutovalidateMode::Disabled`], auto-validation will be disabled.
    ///
    /// Defaults to [`AutovalidateMode::Disabled`].
    pub autovalidate_mode: AutovalidateMode,

    /// Restoration ID to save and restore the state of the form field.
    ///
    /// Setting the restoration ID to a non-`None` value results in whether or not the form field
    /// validation persists.
    ///
    /// The state of this widget is persisted in a [`RestorationBucket`] claimed from the
    /// surrounding `RestorationScope` using the provided restoration ID.
    ///
    /// See also:
    ///
    ///  * `RestorationManager`, which explains how state restoration works in Flutter.
    pub restoration_id: Option<String>,
}

impl<T: 'static> FormFieldData<T> {
    /// The fields of a form field built by `builder`, with Dart's defaults.
    pub fn new(builder: FormFieldBuilder<T>) -> FormFieldData<T> {
        FormFieldData {
            key: None,
            builder,
            on_saved: None,
            on_reset: None,
            force_error_text: None,
            validator: None,
            error_builder: None,
            initial_value: None,
            enabled: true,
            autovalidate_mode: AutovalidateMode::Disabled,
            restoration_id: None,
        }
    }
}

impl<T: 'static> Debug for FormFieldData<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FormField")
            .field("force_error_text", &self.force_error_text)
            .field("enabled", &self.enabled)
            .field("autovalidate_mode", &self.autovalidate_mode)
            .field("restoration_id", &self.restoration_id)
            .finish_non_exhaustive()
    }
}

/// The [`FormFieldData`] accessor a [`FormFieldLeaf`] implementor writes; the bag lives under
/// the field `form_field`.
#[macro_export]
macro_rules! form_field_accessors {
    () => {
        fn form_field_data(&self) -> &$crate::FormFieldData<Self::Value> {
            &self.form_field
        }
    };
}

/// The trait every form-field widget implements: [`FormField`] and its subclasses, such as
/// `TextFormField`.
///
/// Its [`State`] is a [`FormFieldStateLeaf`].
pub trait FormFieldLeaf: StatefulWidget {
    /// Dart's `T` of `FormField<T>`.
    type Value: Clone + 'static;

    /// The [`FormFieldData`] bag ([`form_field_accessors!`](crate::form_field_accessors)).
    fn form_field_data(&self) -> &FormFieldData<Self::Value>;
}

/// A single form field.
///
/// This widget maintains the current state of the form field, so that updates and validation
/// errors are visually reflected in the UI.
///
/// When used inside a [`Form`], you can use methods on [`FormState`] to query or manipulate the
/// form data as a whole. For example, calling [`FormState::save`] will invoke each
/// [`FormField`]'s [`on_saved`](FormFieldData::on_saved) callback in turn.
///
/// Use a `GlobalKey` with [`FormField`] if you want to retrieve its current state, for example
/// if you want one form field to depend on another.
///
/// A [`Form`] ancestor is not required. The [`Form`] allows one to save, reset, or validate
/// multiple fields at once. To use without a [`Form`], pass a `GlobalKey` to the constructor
/// and use `GlobalKey::current_state` to save or reset the form field.
///
/// See also:
///
///  * [`Form`], which is the widget that aggregates the form fields.
///  * `TextField`, which is a commonly used form field for entering text.
pub struct FormField<T: 'static> {
    form_field: FormFieldData<T>,
}

impl<T: Clone + 'static> FormField<T> {
    /// Creates a single form field.
    pub fn new(
        builder: impl Fn(&mut App, AnyFormFieldState<T>) -> WidgetRef + 'static,
    ) -> FormField<T> {
        FormField {
            form_field: FormFieldData::new(Rc::new(builder)),
        }
    }

    /// Dart `FormField(key:)`.
    pub fn key(mut self, key: KeyRef) -> FormField<T> {
        self.form_field.key = Some(key);
        self
    }

    /// Dart `FormField(onSaved:)`.
    pub fn on_saved(mut self, on_saved: impl Fn(&mut App, Option<T>) + 'static) -> FormField<T> {
        self.form_field.on_saved = Some(Rc::new(on_saved));
        self
    }

    /// Dart `FormField(onReset:)`.
    pub fn on_reset(mut self, on_reset: impl Fn(&mut App) + 'static) -> FormField<T> {
        self.form_field.on_reset = Some(Rc::new(on_reset));
        self
    }

    /// Dart `FormField(forceErrorText:)`.
    pub fn force_error_text(mut self, force_error_text: impl Into<String>) -> FormField<T> {
        self.form_field.force_error_text = Some(force_error_text.into());
        self
    }

    /// Dart `FormField(validator:)`.
    pub fn validator(
        mut self,
        validator: impl Fn(&mut App, Option<&T>) -> Option<String> + 'static,
    ) -> FormField<T> {
        self.form_field.validator = Some(Rc::new(validator));
        self
    }

    /// Dart `FormField(errorBuilder:)`.
    pub fn error_builder(
        mut self,
        error_builder: impl Fn(&mut App, BuildContext, String) -> WidgetRef + 'static,
    ) -> FormField<T> {
        self.form_field.error_builder = Some(Rc::new(error_builder));
        self
    }

    /// Dart `FormField(initialValue:)`.
    pub fn initial_value(mut self, initial_value: T) -> FormField<T> {
        self.form_field.initial_value = Some(initial_value);
        self
    }

    /// Dart `FormField(enabled:)`.
    pub fn enabled(mut self, enabled: bool) -> FormField<T> {
        self.form_field.enabled = enabled;
        self
    }

    /// Dart `FormField(autovalidateMode:)`.
    pub fn autovalidate_mode(mut self, autovalidate_mode: AutovalidateMode) -> FormField<T> {
        self.form_field.autovalidate_mode = autovalidate_mode;
        self
    }

    /// Dart `FormField(restorationId:)`.
    pub fn restoration_id(mut self, restoration_id: impl Into<String>) -> FormField<T> {
        self.form_field.restoration_id = Some(restoration_id.into());
        self
    }
}

impl<T: 'static> Debug for FormField<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.form_field.fmt(f)
    }
}

impl<T: Clone + 'static> FormFieldLeaf for FormField<T> {
    type Value = T;
    crate::form_field_accessors!();
}

impl<T: Clone + 'static> StatefulWidget for FormField<T> {
    type State = FormFieldState<T>;

    fn key(&self) -> Option<&KeyRef> {
        self.form_field.key.as_ref()
    }

    fn create_state(&self) -> FormFieldState<T> {
        FormFieldState {
            state: StateData::new(),
            restoration: RestorationMixinData::new(),
            form_field_state: FormFieldStateData::new(&self.form_field),
        }
    }
}

// ---------------------------------------------------------------------------------------------
// FormFieldState

/// The value type of a form-field state: its widget's `T`.
pub type FormFieldValue<S> = <<S as State>::Widget as FormFieldLeaf>::Value;

/// The fields of Dart's `FormFieldState<T>`, which [`FormFieldState`] and its subclasses carry
/// under the field `form_field_state`.
///
/// The restorable properties and the focus node need the [`App`], so
/// [`FormFieldState::init_state`] creates them.
pub struct FormFieldStateData<T> {
    value: Option<T>,
    error_text: Option<Ref<RestorableStringN>>,
    has_interacted_by_user: Option<Ref<RestorableBool>>,
    focus_node: Option<Ref<FocusNode>>,
}

impl<T: Clone + 'static> FormFieldStateData<T> {
    /// The state of a field created for `widget`: Dart's `late T? _value = widget.initialValue`,
    /// read when the state is created.
    pub fn new(widget: &FormFieldData<T>) -> FormFieldStateData<T> {
        FormFieldStateData {
            value: widget.initial_value.clone(),
            error_text: None,
            has_interacted_by_user: None,
            focus_node: None,
        }
    }

    fn error_text_property(&self) -> Handle<RestorableStringN> {
        self.error_text.handle().expect("created in init_state")
    }

    fn has_interacted_by_user_property(&self) -> Handle<RestorableBool> {
        self.has_interacted_by_user
            .handle()
            .expect("created in init_state")
    }

    fn focus_node(&self) -> Handle<FocusNode> {
        self.focus_node.handle().expect("created in init_state")
    }
}

/// The [`FormFieldStateData`] accessors a [`FormFieldStateLeaf`] implementor writes; the bag
/// lives under the field `form_field_state`.
#[macro_export]
macro_rules! form_field_state_accessors {
    () => {
        fn form_field_state_data(
            self: ::waft_foundation::Handle<Self>,
            app: &::waft_foundation::App,
        ) -> &$crate::FormFieldStateData<$crate::FormFieldValue<Self>> {
            &app.get(self).form_field_state
        }

        fn form_field_state_data_mut(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
        ) -> &mut $crate::FormFieldStateData<$crate::FormFieldValue<Self>> {
            &mut app.get_mut(self).form_field_state
        }
    };
}

/// The trait every form-field state implements: [`FormFieldState`] and its subclasses, such as
/// `TextFormField`'s state.
///
/// The virtuals a subclass overrides are the members with a default body here; the shared
/// bodies, and the lifecycle bodies a leaf's own [`State`] and [`RestorationMixin`] impls call,
/// are associated functions on [`FormFieldState`], which an override calls where Dart writes
/// `super.…`.
pub trait FormFieldStateLeaf: RestorationMixin<Widget: FormFieldLeaf> {
    /// Dart's `FormFieldState` fields, held under the field `form_field_state`
    /// ([`form_field_state_accessors!`](crate::form_field_state_accessors)).
    fn form_field_state_data(
        self: Handle<Self>,
        app: &App,
    ) -> &FormFieldStateData<FormFieldValue<Self>>;

    /// See [`form_field_state_data`](Self::form_field_state_data).
    fn form_field_state_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut FormFieldStateData<FormFieldValue<Self>>;

    /// The current value of the form field.
    fn value(self: Handle<Self>, app: &App) -> Option<&FormFieldValue<Self>> {
        self.form_field_state_data(app).value.as_ref()
    }

    /// The current validation error returned by the [`FormFieldData::validator`] callback, or
    /// the manually provided error message using the [`FormFieldData::force_error_text`]
    /// property.
    ///
    /// This property is automatically updated when [`validate`](Self::validate) is called and
    /// the [`FormFieldData::validator`] callback is invoked, or If
    /// [`FormFieldData::force_error_text`] is set directly to a non-`None` value.
    fn error_text(self: Handle<Self>, app: &App) -> Option<String> {
        let property = self.form_field_state_data(app).error_text_property();
        RestorableValue::value(property, app).clone()
    }

    /// True if this field has any validation errors.
    fn has_error(self: Handle<Self>, app: &App) -> bool {
        let property = self.form_field_state_data(app).error_text_property();
        RestorableValue::value(property, app).is_some()
    }

    /// Returns true if the user has modified the value of this field.
    ///
    /// This only updates to true once [`did_change`](Self::did_change) has been called and
    /// resets to false when [`reset`](Self::reset) is called.
    fn has_interacted_by_user(self: Handle<Self>, app: &App) -> bool {
        let property = self
            .form_field_state_data(app)
            .has_interacted_by_user_property();
        *RestorableValue::value(property, app)
    }

    /// True if the current value is valid.
    ///
    /// This will not set [`error_text`](Self::error_text) or [`has_error`](Self::has_error) and
    /// it will not update error display.
    ///
    /// See also:
    ///
    ///  * [`validate`](Self::validate), which may update [`error_text`](Self::error_text) and
    ///    [`has_error`](Self::has_error).
    ///
    ///  * [`FormFieldData::force_error_text`], which also may update
    ///    [`error_text`](Self::error_text) and [`has_error`](Self::has_error).
    fn is_valid(self: Handle<Self>, app: &mut App) -> bool {
        let widget = self.widget(app).form_field_data();
        if widget.force_error_text.is_some() {
            return false;
        }
        let Some(validator) = widget.validator.clone() else {
            return true;
        };
        let value = self.value(app).cloned();
        validator(app, value.as_ref()).is_none()
    }

    /// Calls the [`FormField`]'s on_saved method with the current value.
    fn save(self: Handle<Self>, app: &mut App) {
        FormFieldState::save(self, app);
    }

    /// Resets the field to its initial value.
    fn reset(self: Handle<Self>, app: &mut App) {
        FormFieldState::reset(self, app);
    }

    /// Clears any visible validation error for this field without resetting the field's value.
    ///
    /// This sets [`error_text`](Self::error_text) to `None` and
    /// [`has_interacted_by_user`](Self::has_interacted_by_user) to false.
    ///
    /// If [`AutovalidateMode::Always`] is used, the error may reappear immediately because the
    /// field will trigger a new validation cycle during the next build.
    /// See also:
    ///
    ///  * [`FormState::clear_error`], which clears errors across all fields in the form.
    fn clear_error(self: Handle<Self>, app: &mut App) {
        FormFieldState::clear_error(self, app);
    }

    /// Calls [`FormFieldData::validator`] to set the [`error_text`](Self::error_text) only if
    /// [`FormFieldData::force_error_text`] is `None`. When
    /// [`FormFieldData::force_error_text`] is not `None`, [`FormFieldData::validator`] will not
    /// be called.
    ///
    /// Returns true if there were no errors.
    /// See also:
    ///
    ///  * [`is_valid`](Self::is_valid), which passively gets the validity without setting
    ///    [`error_text`](Self::error_text) or [`has_error`](Self::has_error).
    fn validate(self: Handle<Self>, app: &mut App) -> bool {
        FormFieldState::validate(self, app)
    }

    /// Updates this field's state to the new value. Useful for responding to child widget
    /// changes, e.g. `Slider`'s `Slider.onChanged` argument.
    ///
    /// Triggers the [`Form::on_changed`] callback and, if [`Form::autovalidate_mode`] is
    /// [`AutovalidateMode::Always`] or [`AutovalidateMode::OnUserInteraction`], revalidates all
    /// the fields of the form.
    fn did_change(self: Handle<Self>, app: &mut App, value: Option<FormFieldValue<Self>>) {
        FormFieldState::did_change(self, app, value);
    }

    /// Sets the value associated with this form field.
    ///
    /// This method should only be called by subclasses that need to update the form field value
    /// due to state changes identified during the widget build phase, when calling `set_state`
    /// is prohibited. In all other cases, the value should be set by a call to
    /// [`did_change`](Self::did_change), which ensures that `set_state` is called.
    fn set_value(self: Handle<Self>, app: &mut App, value: Option<FormFieldValue<Self>>) {
        self.form_field_state_data_mut(app).value = value;
    }

    /// This state as the erased [`AnyFormFieldState`]: what to pass where a Dart API takes a
    /// `FormFieldState<T>`.
    fn as_form_field_state(self: Handle<Self>) -> AnyFormFieldState<FormFieldValue<Self>> {
        AnyFormFieldState {
            id: self.id(),
            vtable: const { &FormFieldStateVTable::<FormFieldValue<Self>>::of::<Self>() },
        }
    }

    /// This state as the erased [`DynamicFormFieldState`]: what to pass where a Dart API takes
    /// a `FormFieldState<dynamic>`.
    fn as_dynamic_form_field_state(self: Handle<Self>) -> DynamicFormFieldState {
        self.as_form_field_state().as_dynamic()
    }
}

/// The current state of a [`FormField`]. Passed to the [`FormFieldBuilder`] method for use in
/// constructing the form field's widget.
///
/// Its associated functions are the bodies Dart's `FormFieldState<T>` gives its subclasses:
/// the virtuals' defaults, which an override calls where Dart writes `super.…`, and the
/// lifecycle a subclass's [`State`] and [`RestorationMixin`] impls run at Dart's
/// `super.initState()` and the rest.
pub struct FormFieldState<T: Clone + 'static> {
    state: StateData<FormField<T>>,
    restoration: RestorationMixinData,
    form_field_state: FormFieldStateData<T>,
}

impl<T: Clone + 'static> FormFieldState<T> {
    /// See [`FormFieldStateLeaf::save`].
    pub fn save<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
        this: Handle<S>,
        app: &mut App,
    ) {
        if let Some(on_saved) = this.widget(app).form_field_data().on_saved.clone() {
            let value = this.value(app).cloned();
            on_saved(app, value);
        }
    }

    /// See [`FormFieldStateLeaf::reset`].
    pub fn reset<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
        this: Handle<S>,
        app: &mut App,
    ) {
        let initial_value = this.widget(app).form_field_data().initial_value.clone();
        this.form_field_state_data_mut(app).value = initial_value;
        clear_error_internal(this, app);
        this.set_state(app, |_state| {});
        if let Some(on_reset) = this.widget(app).form_field_data().on_reset.clone() {
            on_reset(app);
        }
        let context = this.context(app);
        if let Some(form) = Form::maybe_of(app, context) {
            form.field_did_change(app);
        }
    }

    /// See [`FormFieldStateLeaf::clear_error`].
    pub fn clear_error<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
        this: Handle<S>,
        app: &mut App,
    ) {
        clear_error_internal(this, app);
        this.set_state(app, |_state| {});
        let context = this.context(app);
        if let Some(form) = Form::maybe_of(app, context) {
            form.field_did_change(app);
        }
    }

    /// See [`FormFieldStateLeaf::validate`].
    pub fn validate<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
        this: Handle<S>,
        app: &mut App,
    ) -> bool {
        validate_field(this, app);
        this.set_state(app, |_state| {});
        !this.has_error(app)
    }

    /// See [`FormFieldStateLeaf::did_change`].
    pub fn did_change<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
        this: Handle<S>,
        app: &mut App,
        value: Option<T>,
    ) {
        this.form_field_state_data_mut(app).value = value;
        let has_interacted_by_user = this
            .form_field_state_data(app)
            .has_interacted_by_user_property();
        has_interacted_by_user.set_value(app, true);
        this.set_state(app, |_state| {});
        let context = this.context(app);
        if let Some(form) = Form::maybe_of(app, context) {
            form.field_did_change(app);
        }
    }

    /// Dart's `FormFieldState.restorationId`.
    pub fn restoration_id<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
        this: Handle<S>,
        app: &App,
    ) -> Option<&str> {
        this.widget(app).form_field_data().restoration_id.as_deref()
    }

    /// Dart's `FormFieldState.restoreState`.
    pub fn restore_state<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
        this: Handle<S>,
        app: &mut App,
        _old_bucket: Option<Handle<RestorationBucket>>,
        _initial_restore: bool,
    ) {
        let error_text = this.form_field_state_data(app).error_text_property();
        this.register_for_restoration(app, error_text.as_property(), "error_text");
        let has_interacted_by_user = this
            .form_field_state_data(app)
            .has_interacted_by_user_property();
        this.register_for_restoration(
            app,
            has_interacted_by_user.as_property(),
            "has_interacted_by_user",
        );
    }

    /// Dart's `FormFieldState.deactivate`, run where the leaf's [`State::deactivate`] would call
    /// `super.deactivate()`.
    pub fn deactivate<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
        this: Handle<S>,
        app: &mut App,
    ) {
        let context = this.context(app);
        if let Some(form) = Form::maybe_of(app, context) {
            form.unregister(app, this.as_dynamic_form_field_state());
        }
    }

    /// Dart's `FormFieldState.initState`, with the field initializers Dart runs as the state is
    /// constructed.
    pub fn init_state<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
        this: Handle<S>,
        app: &mut App,
    ) {
        let has_interacted_by_user = RestorableBool::new(app, false);
        let focus_node = FocusNode::new(app);
        let force_error_text = this.widget(app).form_field_data().force_error_text.clone();
        let error_text = RestorableStringN::new(app, force_error_text);
        let data = this.form_field_state_data_mut(app);
        data.has_interacted_by_user = Some(has_interacted_by_user);
        data.focus_node = Some(focus_node);
        data.error_text = Some(error_text);
    }

    /// Dart's `FormFieldState.didUpdateWidget`.
    pub fn did_update_widget<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
        this: Handle<S>,
        app: &mut App,
        old_widget: &S::Widget,
    ) {
        this.did_update_restoration_id(app);
        let force_error_text = this.widget(app).form_field_data().force_error_text.clone();
        if force_error_text != old_widget.form_field_data().force_error_text {
            let error_text = this.form_field_state_data(app).error_text_property();
            error_text.set_value(app, force_error_text);
        }
    }

    /// Dart's `FormFieldState.didChangeDependencies`.
    pub fn did_change_dependencies<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
        this: Handle<S>,
        app: &mut App,
    ) {
        this.did_change_dependencies_restoration(app);
        let context = this.context(app);
        let form = Form::maybe_of(app, context);
        match form.map(|form| form.widget(app).autovalidate_mode) {
            Some(AutovalidateMode::Always) => {
                let view = View::maybe_id_of(app, context);
                SchedulerBinding::add_post_frame_callback(
                    app,
                    FrameCallback::new(move |app, _time_stamp| {
                        // If the form is already validated, don't validate again.
                        if this.widget(app).form_field_data().enabled
                            && !this.has_error(app)
                            && !this.is_valid(app)
                        {
                            this.validate(app);
                        }
                    }),
                    view,
                );
            }
            Some(
                AutovalidateMode::OnUnfocus
                | AutovalidateMode::OnUserInteraction
                | AutovalidateMode::OnUserInteractionIfError
                | AutovalidateMode::Disabled,
            )
            | None => {}
        }
    }

    /// Dart's `FormFieldState.dispose`.
    pub fn dispose<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
        this: Handle<S>,
        app: &mut App,
    ) {
        let data = this.form_field_state_data(app);
        let (error_text, focus_node, has_interacted_by_user) = (
            data.error_text_property(),
            data.focus_node(),
            data.has_interacted_by_user_property(),
        );
        RestorableProperty::dispose(error_text, app);
        focus_node.as_node().dispose(app);
        RestorableProperty::dispose(has_interacted_by_user, app);
        this.dispose_restoration(app);
    }

    /// Dart's `FormFieldState.build`.
    pub fn build<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>(
        this: Handle<S>,
        app: &mut App,
        context: BuildContext,
    ) -> WidgetRef {
        let widget = this.widget(app).form_field_data();
        let (enabled, autovalidate_mode) = (widget.enabled, widget.autovalidate_mode);
        if enabled {
            match autovalidate_mode {
                AutovalidateMode::Always => {
                    validate_field(this, app);
                }
                AutovalidateMode::OnUserInteraction => {
                    if this.has_interacted_by_user(app) {
                        validate_field(this, app);
                    }
                }
                AutovalidateMode::OnUserInteractionIfError => {
                    if this.has_interacted_by_user(app) && this.has_error(app) {
                        validate_field(this, app);
                    }
                }
                AutovalidateMode::OnUnfocus | AutovalidateMode::Disabled => {}
            }
        }

        if let Some(form) = Form::maybe_of(app, context) {
            form.register(app, this.as_dynamic_form_field_state());
        }

        let builder = Rc::clone(&this.widget(app).form_field_data().builder);
        let validation_result = if this.has_error(app) {
            SemanticsValidationResult::Invalid
        } else {
            SemanticsValidationResult::Valid
        };
        let child = Semantics::new()
            .validation_result(validation_result)
            .child(builder(app, this.as_form_field_state()))
            .into_widget();

        let form_autovalidate_mode =
            Form::maybe_of(app, context).map(|form| form.widget(app).autovalidate_mode);
        if form_autovalidate_mode == Some(AutovalidateMode::OnUnfocus)
            && autovalidate_mode != AutovalidateMode::Always
            || autovalidate_mode == AutovalidateMode::OnUnfocus
        {
            let focus_node = this
                .form_field_state_data(app)
                .focus_node
                .as_ref()
                .expect("created in init_state")
                .erase();
            return Focus::new(child)
                .can_request_focus(false)
                .skip_traversal(true)
                .on_focus_change(move |app, value| {
                    if !value {
                        validate_field(this, app);
                        this.set_state(app, |_state| {});
                    }
                })
                .focus_node(focus_node)
                .into_widget();
        }

        child
    }
}

/// Dart's private `_clearErrorInternal`.
fn clear_error_internal<S: FormFieldStateLeaf>(this: Handle<S>, app: &mut App) {
    let data = this.form_field_state_data(app);
    let (error_text, has_interacted_by_user) = (
        data.error_text_property(),
        data.has_interacted_by_user_property(),
    );
    error_text.set_value(app, None);
    has_interacted_by_user.set_value(app, false);
}

/// Dart's private `FormFieldState._validate`.
fn validate_field<S: FormFieldStateLeaf>(this: Handle<S>, app: &mut App) {
    let error_text = this.form_field_state_data(app).error_text_property();
    let widget = this.widget(app).form_field_data();
    if let Some(force_error_text) = widget.force_error_text.clone() {
        error_text.set_value(app, Some(force_error_text));
        // Skip validating if error is forced.
        return;
    }
    if let Some(validator) = widget.validator.clone() {
        let value = this.value(app).cloned();
        let result = validator(app, value.as_ref());
        error_text.set_value(app, result);
    } else {
        error_text.set_value(app, None);
    }
}

impl<T: Clone + 'static> FormFieldStateLeaf for FormFieldState<T> {
    crate::form_field_state_accessors!();
}

impl<T: Clone + 'static> RestorationMixin for FormFieldState<T> {
    crate::restoration_mixin_accessors!();

    fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str> {
        FormFieldState::restoration_id(self, app)
    }

    fn restore_state(
        self: Handle<Self>,
        app: &mut App,
        old_bucket: Option<Handle<RestorationBucket>>,
        initial_restore: bool,
    ) {
        FormFieldState::restore_state(self, app, old_bucket, initial_restore);
    }
}

impl<T: Clone + 'static> State for FormFieldState<T> {
    type Widget = FormField<T>;
    crate::state_accessors!();

    fn deactivate(self: Handle<Self>, app: &mut App) {
        FormFieldState::deactivate(self, app);
    }

    fn init_state(self: Handle<Self>, app: &mut App) {
        FormFieldState::init_state(self, app);
    }

    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &FormField<T>) {
        FormFieldState::did_update_widget(self, app, old_widget);
    }

    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
        FormFieldState::did_change_dependencies(self, app);
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        FormFieldState::dispose(self, app);
    }

    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
        FormFieldState::build(self, app, context)
    }
}

// ---------------------------------------------------------------------------------------------
// The erased form-field states

/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
fn resolve<S: 'static>(id: HandleId) -> Handle<S> {
    Handle::from_id(id)
}

/// The vtable of an erased [`DynamicFormFieldState`]: what does not name the value type.
struct DynamicFormFieldStateVTable {
    type_name: fn() -> &'static str,
    typed: fn() -> &'static dyn Any,
    value: fn(&App, HandleId) -> Option<&dyn Any>,
    context: fn(&App, HandleId) -> BuildContext,
    mounted: fn(&App, HandleId) -> bool,
    error_text: fn(&App, HandleId) -> Option<String>,
    has_error: fn(&App, HandleId) -> bool,
    has_interacted_by_user: fn(&App, HandleId) -> bool,
    is_valid: fn(&mut App, HandleId) -> bool,
    save: fn(&mut App, HandleId),
    reset: fn(&mut App, HandleId),
    clear_error: fn(&mut App, HandleId),
    validate: fn(&mut App, HandleId) -> bool,
    clear_error_internal: fn(&mut App, HandleId),
    focus_node: fn(&App, HandleId) -> Handle<FocusNode>,
}

/// The vtable of an erased [`AnyFormFieldState`]: the members that name the value type, and the
/// [`DynamicFormFieldStateVTable`] of the same leaf.
struct FormFieldStateVTable<T: 'static> {
    dynamic: DynamicFormFieldStateVTable,
    value: fn(&App, HandleId) -> Option<&T>,
    did_change: fn(&mut App, HandleId, Option<T>),
}

impl<T: Clone + 'static> FormFieldStateVTable<T> {
    const fn of<S: FormFieldStateLeaf<Widget: FormFieldLeaf<Value = T>>>() -> FormFieldStateVTable<T>
    {
        FormFieldStateVTable {
            dynamic: DynamicFormFieldStateVTable {
                type_name: std::any::type_name::<S>,
                typed: || const { &FormFieldStateVTable::<T>::of::<S>() } as &dyn Any,
                value: |app, id| S::value(resolve(id), app).map(|value| value as &dyn Any),
                context: |app, id| S::context(resolve(id), app),
                mounted: |app, id| S::mounted(resolve(id), app),
                error_text: |app, id| S::error_text(resolve(id), app),
                has_error: |app, id| S::has_error(resolve(id), app),
                has_interacted_by_user: |app, id| S::has_interacted_by_user(resolve(id), app),
                is_valid: |app, id| S::is_valid(resolve(id), app),
                save: |app, id| S::save(resolve(id), app),
                reset: |app, id| S::reset(resolve(id), app),
                clear_error: |app, id| S::clear_error(resolve(id), app),
                validate: |app, id| S::validate(resolve(id), app),
                clear_error_internal: |app, id| clear_error_internal::<S>(resolve(id), app),
                focus_node: |app, id| S::form_field_state_data(resolve(id), app).focus_node(),
            },
            value: |app, id| S::value(resolve(id), app),
            did_change: |app, id, value| S::did_change(resolve(id), app, value),
        }
    }
}

/// Erased [`FormFieldStateLeaf`] whose value type is not known: what a field or parameter Dart
/// types as `FormFieldState<dynamic>` becomes, such as the fields a [`FormState`] holds.
///
/// Equality is Dart's `==` on an object reference.
#[derive(Clone, Copy)]
pub struct DynamicFormFieldState {
    id: HandleId,
    vtable: &'static DynamicFormFieldStateVTable,
}

impl PartialEq for DynamicFormFieldState {
    fn eq(&self, other: &DynamicFormFieldState) -> bool {
        self.id == other.id
    }
}

impl Eq for DynamicFormFieldState {}

impl std::hash::Hash for DynamicFormFieldState {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.id.hash(state);
    }
}

impl Debug for DynamicFormFieldState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
    }
}

impl DynamicFormFieldState {
    /// The arena id behind this handle.
    pub fn id(self) -> HandleId {
        self.id
    }

    /// The leaf state behind this handle, if it is an `S`: Dart's `field as S`.
    pub fn downcast<S: 'static>(self, app: &App) -> Option<Handle<S>> {
        app.handle::<S>(self.id)
    }

    /// This field as a `FormFieldState<T>`, if its value type is `T`: Dart's
    /// `field is FormFieldState<T>`.
    pub fn typed<T: 'static>(self) -> Option<AnyFormFieldState<T>> {
        (self.vtable.typed)()
            .downcast_ref::<FormFieldStateVTable<T>>()
            .map(|vtable| AnyFormFieldState {
                id: self.id,
                vtable,
            })
    }

    /// See [`FormFieldStateLeaf::value`].
    pub fn value(self, app: &App) -> Option<&dyn Any> {
        (self.vtable.value)(app, self.id)
    }

    /// See [`State::context`].
    pub fn context(self, app: &App) -> BuildContext {
        (self.vtable.context)(app, self.id)
    }

    /// See [`State::mounted`].
    pub fn mounted(self, app: &App) -> bool {
        (self.vtable.mounted)(app, self.id)
    }

    /// See [`FormFieldStateLeaf::error_text`].
    pub fn error_text(self, app: &App) -> Option<String> {
        (self.vtable.error_text)(app, self.id)
    }

    /// See [`FormFieldStateLeaf::has_error`].
    pub fn has_error(self, app: &App) -> bool {
        (self.vtable.has_error)(app, self.id)
    }

    /// See [`FormFieldStateLeaf::has_interacted_by_user`].
    pub fn has_interacted_by_user(self, app: &App) -> bool {
        (self.vtable.has_interacted_by_user)(app, self.id)
    }

    /// See [`FormFieldStateLeaf::is_valid`].
    pub fn is_valid(self, app: &mut App) -> bool {
        (self.vtable.is_valid)(app, self.id)
    }

    /// See [`FormFieldStateLeaf::save`].
    pub fn save(self, app: &mut App) {
        (self.vtable.save)(app, self.id);
    }

    /// See [`FormFieldStateLeaf::reset`].
    pub fn reset(self, app: &mut App) {
        (self.vtable.reset)(app, self.id);
    }

    /// See [`FormFieldStateLeaf::clear_error`].
    pub fn clear_error(self, app: &mut App) {
        (self.vtable.clear_error)(app, self.id);
    }

    /// See [`FormFieldStateLeaf::validate`].
    pub fn validate(self, app: &mut App) -> bool {
        (self.vtable.validate)(app, self.id)
    }

    fn clear_error_internal(self, app: &mut App) {
        (self.vtable.clear_error_internal)(app, self.id);
    }

    fn focus_node(self, app: &App) -> Handle<FocusNode> {
        (self.vtable.focus_node)(app, self.id)
    }
}

/// Erased [`FormFieldStateLeaf`] with value type `T`: what a field or parameter Dart types as
/// `FormFieldState<T>` becomes, such as what a [`FormFieldBuilder`] is handed.
///
/// Equality is Dart's `==` on an object reference.
pub struct AnyFormFieldState<T: 'static> {
    id: HandleId,
    vtable: &'static FormFieldStateVTable<T>,
}

impl<T: 'static> Clone for AnyFormFieldState<T> {
    fn clone(&self) -> AnyFormFieldState<T> {
        *self
    }
}

impl<T: 'static> Copy for AnyFormFieldState<T> {}

impl<T: 'static> PartialEq for AnyFormFieldState<T> {
    fn eq(&self, other: &AnyFormFieldState<T>) -> bool {
        self.id == other.id
    }
}

impl<T: 'static> Eq for AnyFormFieldState<T> {}

impl<T: 'static> Debug for AnyFormFieldState<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.as_dynamic().fmt(f)
    }
}

impl<T: 'static> AnyFormFieldState<T> {
    /// This field as a `FormFieldState<dynamic>`.
    pub fn as_dynamic(self) -> DynamicFormFieldState {
        DynamicFormFieldState {
            id: self.id,
            vtable: &self.vtable.dynamic,
        }
    }

    /// The arena id behind this handle.
    pub fn id(self) -> HandleId {
        self.id
    }

    /// The leaf state behind this handle, if it is an `S`: Dart's `field as S`.
    pub fn downcast<S: 'static>(self, app: &App) -> Option<Handle<S>> {
        app.handle::<S>(self.id)
    }

    /// See [`FormFieldStateLeaf::value`].
    pub fn value(self, app: &App) -> Option<&T> {
        (self.vtable.value)(app, self.id)
    }

    /// See [`FormFieldStateLeaf::did_change`].
    pub fn did_change(self, app: &mut App, value: Option<T>) {
        (self.vtable.did_change)(app, self.id, value);
    }

    /// See [`State::context`].
    pub fn context(self, app: &App) -> BuildContext {
        self.as_dynamic().context(app)
    }

    /// See [`State::mounted`].
    pub fn mounted(self, app: &App) -> bool {
        self.as_dynamic().mounted(app)
    }

    /// See [`FormFieldStateLeaf::error_text`].
    pub fn error_text(self, app: &App) -> Option<String> {
        self.as_dynamic().error_text(app)
    }

    /// See [`FormFieldStateLeaf::has_error`].
    pub fn has_error(self, app: &App) -> bool {
        self.as_dynamic().has_error(app)
    }

    /// See [`FormFieldStateLeaf::has_interacted_by_user`].
    pub fn has_interacted_by_user(self, app: &App) -> bool {
        self.as_dynamic().has_interacted_by_user(app)
    }

    /// See [`FormFieldStateLeaf::is_valid`].
    pub fn is_valid(self, app: &mut App) -> bool {
        self.as_dynamic().is_valid(app)
    }

    /// See [`FormFieldStateLeaf::save`].
    pub fn save(self, app: &mut App) {
        self.as_dynamic().save(app);
    }

    /// See [`FormFieldStateLeaf::reset`].
    pub fn reset(self, app: &mut App) {
        self.as_dynamic().reset(app);
    }

    /// See [`FormFieldStateLeaf::clear_error`].
    pub fn clear_error(self, app: &mut App) {
        self.as_dynamic().clear_error(app);
    }

    /// See [`FormFieldStateLeaf::validate`].
    pub fn validate(self, app: &mut App) -> bool {
        self.as_dynamic().validate(app)
    }
}

// ---------------------------------------------------------------------------------------------
// AutovalidateMode

/// Used to configure the auto validation of [`FormField`] and [`Form`] widgets.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AutovalidateMode {
    /// No auto validation will occur.
    Disabled,

    /// Used to auto-validate [`Form`] and [`FormField`] even without user interaction.
    Always,

    /// Used to auto-validate [`Form`] and [`FormField`] only after each user interaction.
    OnUserInteraction,

    /// Used to auto-validate [`Form`] and [`FormField`] only after the field has lost focus.
    ///
    /// In order to validate all fields of a [`Form`] after the first time the user interacts
    /// with one, use [`Always`](Self::Always) instead.
    OnUnfocus,

    /// Used to auto-validate [`Form`] and [`FormField`] after each user interaction, only if
    /// the field already has an error.
    ///
    /// This is useful for reducing unnecessary validation calls while still ensuring errors are
    /// re-checked when the user attempts to fix them.
    OnUserInteractionIfError,
}

#[cfg(test)]
mod tests {
    use std::cell::{Cell, RefCell};
    use waft_foundation::OptionRetained;
    use waft_foundation::Ref;

    use waft_embedder::{Size, TextDirection};
    use waft_foundation::{UniqueKey, ValueKey};
    use waft_services::RestorationMap;

    use super::*;
    use crate::framework::GlobalKey;
    use crate::testing::{
        WidgetTester, expect, find, finds_n_widgets, finds_nothing, finds_one_widget, test_widgets,
    };
    use crate::widgets::basic::{Center, Column, Directionality, SizedBox, StatefulBuilder};
    use crate::widgets::focus_manager::{AnyFocusNode, FocusNodeRef};
    use crate::widgets::restoration::RootRestorationScope;
    use crate::widgets::scroll_view::ListView;
    use crate::widgets::text::Text;

    /// Dart's `tester.pumpWidget(widget)` under the left-to-right `Directionality` the
    /// `MaterialApp` of Dart's cases gives it.
    fn pump_ltr(tester: &mut WidgetTester, widget: WidgetRef) {
        tester.pump_widget(Directionality::new(TextDirection::Ltr, widget));
    }

    fn form_state(tester: &WidgetTester, key: &GlobalKey) -> Handle<FormState> {
        key.current_state::<FormState>(&tester.cell.borrow())
            .expect("the form is mounted")
    }

    fn field_state<T: Clone + 'static>(
        tester: &WidgetTester,
        key: &GlobalKey,
    ) -> Handle<FormFieldState<T>> {
        key.current_state::<FormFieldState<T>>(&tester.cell.borrow())
            .expect("the field is mounted")
    }

    /// `tester.enterText` on a field: the value its text field would hand `didChange`.
    fn enter_text(tester: &WidgetTester, key: &GlobalKey, text: &str) {
        let field = field_state::<String>(tester, key);
        field.did_change(&mut tester.cell.borrow_mut(), Some(text.to_string()));
    }

    // ---- a minimal `TextFormField`: a `FormField<String>` showing its value and error ----

    fn show_field(app: &mut App, field: AnyFormFieldState<String>) -> WidgetRef {
        let mut children =
            vec![Text::new(field.value(app).cloned().unwrap_or_default()).into_widget()];
        if let Some(error_text) = field.error_text(app) {
            children.push(Text::new(error_text).into_widget());
        }
        Column::new().children(children).into_widget()
    }

    fn text_field(key: &GlobalKey) -> FormField<String> {
        FormField::new(show_field).key(key.clone().into())
    }

    /// A field whose subtree takes the focus through `node`, as a text field's does on a tap.
    fn focusable_text_field(key: &GlobalKey, node: FocusNodeRef) -> FormField<String> {
        FormField::new(move |app, field| {
            Focus::new(show_field(app, field))
                .focus_node(node.clone())
                .into_widget()
        })
        .key(key.clone().into())
    }

    fn error_text(value: Option<&String>) -> Option<String> {
        Some(format!(
            "{}/error",
            value.map(String::as_str).unwrap_or("null")
        ))
    }

    #[test]
    fn on_saved_is_called_with_the_value_the_field_holds() {
        test_widgets(|tester| {
            let form_key = GlobalKey::new();
            let field_key = GlobalKey::new();
            let field_value = Rc::new(RefCell::new(None));
            let saved = Rc::clone(&field_value);
            pump_ltr(
                tester,
                Form::new(text_field(&field_key).on_saved(move |_app, value| {
                    *saved.borrow_mut() = value;
                }))
                .key(form_key.clone().into())
                .into_widget(),
            );

            assert_eq!(*field_value.borrow(), None);

            for test_value in ["Test", ""] {
                enter_text(tester, &field_key, test_value);
                let form = form_state(tester, &form_key);
                form.save(&mut tester.cell.borrow_mut());
                // Pumping is unnecessary because callback happens regardless of frames.
                assert_eq!(field_value.borrow().as_deref(), Some(test_value));
            }
        });
    }

    #[test]
    fn on_reset_is_called_when_the_form_resets() {
        test_widgets(|tester| {
            let form_key = GlobalKey::new();
            let reset_called = Rc::new(Cell::new(false));
            let called = Rc::clone(&reset_called);
            pump_ltr(
                tester,
                Form::new(
                    FormField::<String>::new(|_app, _field| SizedBox::shrink().into_widget())
                        .on_reset(move |_app| called.set(true)),
                )
                .key(form_key.clone().into())
                .into_widget(),
            );

            assert!(!reset_called.get());

            let form = form_state(tester, &form_key);
            form.reset(&mut tester.cell.borrow_mut());
            tester.pump();

            assert!(reset_called.get());
        });
    }

    #[test]
    fn the_validator_sets_the_error_text_only_when_validate_is_called() {
        test_widgets(|tester| {
            let form_key = GlobalKey::new();
            let field_key = GlobalKey::new();
            let error_text = |value: Option<&String>| {
                Some(format!("{}/error", value.map(String::as_str).unwrap_or("")))
            };
            let builder = |autovalidate_mode| {
                Form::new(text_field(&field_key).validator(move |_app, value| error_text(value)))
                    .key(form_key.clone().into())
                    .autovalidate_mode(autovalidate_mode)
                    .into_widget()
            };

            // Start off not autovalidating.
            pump_ltr(tester, builder(AutovalidateMode::Disabled));

            for test_value in ["Test", ""] {
                let expected = error_text(Some(&test_value.to_string())).unwrap();
                let form = form_state(tester, &form_key);
                form.reset(&mut tester.cell.borrow_mut());
                pump_ltr(tester, builder(AutovalidateMode::Disabled));
                enter_text(tester, &field_key, test_value);
                tester.pump();

                // We have to manually validate if we're not autovalidating.
                expect(tester, &find::text(&expected), finds_nothing());
                form.validate(&mut tester.cell.borrow_mut());
                tester.pump();
                expect(tester, &find::text(&expected), finds_one_widget());

                // Try again with autovalidation. Should validate immediately.
                form.reset(&mut tester.cell.borrow_mut());
                pump_ltr(tester, builder(AutovalidateMode::Always));
                enter_text(tester, &field_key, test_value);
                tester.pump();

                expect(tester, &find::text(&expected), finds_one_widget());
            }
        });
    }

    fn valid_string_validator(value: Option<&String>) -> Option<String> {
        (value.map(String::as_str) != Some("Valid string")).then(|| "Error text".to_string())
    }

    #[test]
    fn is_valid_is_true_for_fields_that_are_valid() {
        test_widgets(|tester| {
            let field_key1 = GlobalKey::new();
            let field_key2 = GlobalKey::new();
            let field = |key: &GlobalKey| {
                text_field(key)
                    .initial_value("Valid string".to_string())
                    .validator(|_app, value| valid_string_validator(value))
                    .autovalidate_mode(AutovalidateMode::Always)
                    .into_widget()
            };
            pump_ltr(
                tester,
                Form::new(ListView::new().children([field(&field_key1), field(&field_key2)]))
                    .into_widget(),
            );

            let (field1, field2) = (
                field_state::<String>(tester, &field_key1),
                field_state::<String>(tester, &field_key2),
            );
            assert!(field1.is_valid(&mut tester.cell.borrow_mut()));
            assert!(field2.is_valid(&mut tester.cell.borrow_mut()));
        });
    }

    #[test]
    fn is_valid_is_false_for_an_invalid_field_and_does_not_change_its_error_display() {
        test_widgets(|tester| {
            let field_key1 = GlobalKey::new();
            let field_key2 = GlobalKey::new();
            let field = |key: &GlobalKey, initial_value: &str| {
                text_field(key)
                    .initial_value(initial_value.to_string())
                    .validator(|_app, value| valid_string_validator(value))
                    .autovalidate_mode(AutovalidateMode::Disabled)
                    .into_widget()
            };
            pump_ltr(
                tester,
                Form::new(
                    ListView::new()
                        .children([field(&field_key1, "Valid string"), field(&field_key2, "")]),
                )
                .into_widget(),
            );

            let (field1, field2) = (
                field_state::<String>(tester, &field_key1),
                field_state::<String>(tester, &field_key2),
            );
            assert!(field1.is_valid(&mut tester.cell.borrow_mut()));
            assert!(!field2.is_valid(&mut tester.cell.borrow_mut()));
            assert!(!field2.has_error(&tester.cell.borrow_mut()));
        });
    }

    #[test]
    fn validate_granularly_returns_a_set_of_all_and_only_the_invalid_fields() {
        test_widgets(|tester| {
            let form_key = GlobalKey::new();
            let valid_fields_key = UniqueKey::new();
            let invalid_fields_key = UniqueKey::new();
            let field = |key: UniqueKey, initial_value: &str| {
                FormField::new(show_field)
                    .key(key.into())
                    .initial_value(initial_value.to_string())
                    .validator(|_app, value| valid_string_validator(value))
                    .autovalidate_mode(AutovalidateMode::Disabled)
                    .into_widget()
            };
            pump_ltr(
                tester,
                Form::new(ListView::new().children([
                    field(valid_fields_key, "Valid string"),
                    field(invalid_fields_key, "Invalid string"),
                    field(invalid_fields_key, "Invalid string"),
                ]))
                .key(form_key.clone().into())
                .into_widget(),
            );

            let form = form_state(tester, &form_key);
            let validation_result = form.validate_granularly(&mut tester.cell.borrow_mut());

            let app = tester.cell.borrow_mut();
            let with_key = |key: UniqueKey| {
                let key = KeyRef::from(key);
                validation_result
                    .iter()
                    .filter(|field| field.context(&app).widget(&app).key() == Some(&key))
                    .count()
            };
            assert_eq!(validation_result.len(), 2);
            assert_eq!(with_key(invalid_fields_key), 2);
            assert_eq!(with_key(valid_fields_key), 0);
        });
    }

    #[test]
    fn multiple_fields_communicate() {
        test_widgets(|tester| {
            let form_key = GlobalKey::new();
            let field_key = GlobalKey::new();
            let second_key = GlobalKey::new();
            let read_key = field_key.clone();
            // Input 2's validator depends on a input 1's value.
            let builder = || {
                let read_key = read_key.clone();
                Form::new(
                    ListView::new().children([
                        text_field(&field_key).into_widget(),
                        text_field(&second_key)
                            .validator(move |app, _input| {
                                let field = read_key
                                    .current_state::<FormFieldState<String>>(app)
                                    .expect("the first field is mounted");
                                Some(format!(
                                    "{}/error",
                                    field.value(app).cloned().unwrap_or_default()
                                ))
                            })
                            .into_widget(),
                    ]),
                )
                .key(form_key.clone().into())
                .autovalidate_mode(AutovalidateMode::Always)
                .into_widget()
            };
            pump_ltr(tester, builder());

            for test_value in ["Test", ""] {
                enter_text(tester, &field_key, test_value);
                tester.pump();

                // Check for a new Text widget with our error text.
                expect(
                    tester,
                    &find::text(&format!("{test_value}/error")),
                    finds_one_widget(),
                );
            }
        });
    }

    #[test]
    fn removing_a_field_from_the_tree_does_not_crash_the_form() {
        test_widgets(|tester| {
            let form_key = GlobalKey::new();
            let field_key = GlobalKey::new();
            let field_value = Rc::new(RefCell::new(None::<String>));
            let builder = |remove: bool| {
                let saved = Rc::clone(&field_value);
                let child = if remove {
                    SizedBox::new().into_widget()
                } else {
                    text_field(&field_key)
                        .on_saved(move |_app, value| *saved.borrow_mut() = value)
                        .validator(|_app, value| {
                            value
                                .is_some_and(|value| !value.is_empty())
                                .then(|| "yes".to_string())
                        })
                        .into_widget()
                };
                Form::new(child).key(form_key.clone().into()).into_widget()
            };

            pump_ltr(tester, builder(false));
            let form = form_state(tester, &form_key);

            assert_eq!(*field_value.borrow(), None);
            assert!(form.validate(&mut tester.cell.borrow_mut()));

            enter_text(tester, &field_key, "Test");
            pump_ltr(tester, builder(false));

            // Form wasn't saved yet.
            assert_eq!(*field_value.borrow(), None);
            assert!(!form.validate(&mut tester.cell.borrow_mut()));

            form.save(&mut tester.cell.borrow_mut());

            // Now fieldValue is saved.
            assert_eq!(field_value.borrow().as_deref(), Some("Test"));
            assert!(!form.validate(&mut tester.cell.borrow_mut()));

            // Now remove the field with an error.
            pump_ltr(tester, builder(true));

            // Reset the form. Should not crash.
            form.reset(&mut tester.cell.borrow_mut());
            form.save(&mut tester.cell.borrow_mut());
            assert!(form.validate(&mut tester.cell.borrow_mut()));
        });
    }

    /// A lone field, no form above it, that records its state as its builder is handed it.
    fn recording_field(
        recorded: &Rc<Cell<Option<AnyFormFieldState<String>>>>,
        show_error: bool,
    ) -> FormField<String> {
        let recorded = Rc::clone(recorded);
        FormField::new(move |app, field| {
            recorded.set(Some(field));
            let mut children = vec![SizedBox::new().into_widget()];
            if show_error && let Some(error_text) = field.error_text(app) {
                children.push(Text::new(error_text).into_widget());
            }
            Column::new().children(children).into_widget()
        })
    }

    fn required(value: Option<&String>) -> Option<String> {
        value
            .is_none_or(|value| value.is_empty())
            .then(|| "Required".to_string())
    }

    #[test]
    fn a_field_does_not_autovalidate_before_its_value_changes_on_user_interaction() {
        test_widgets(|tester| {
            let recorded = Rc::new(Cell::new(None));
            pump_ltr(
                tester,
                recording_field(&recorded, true)
                    .initial_value("foo".to_string())
                    .autovalidate_mode(AutovalidateMode::OnUserInteraction)
                    .validator(|_app, value| error_text(value))
                    .into_widget(),
            );
            let field = recorded.get().expect("built");
            // The form field has no error.
            assert!(!field.has_error(&tester.cell.borrow_mut()));
            // No error widget is visible.
            expect(tester, &find::text("foo/error"), finds_nothing());
        });
    }

    #[test]
    fn a_field_does_not_autovalidate_before_its_value_changes_on_user_interaction_if_error() {
        test_widgets(|tester| {
            let recorded = Rc::new(Cell::new(None));
            pump_ltr(
                tester,
                recording_field(&recorded, true)
                    .initial_value("foo".to_string())
                    .autovalidate_mode(AutovalidateMode::OnUserInteractionIfError)
                    .validator(|_app, value| required(value))
                    .into_widget(),
            );
            let field = recorded.get().expect("built");
            // The form field has no error.
            assert!(!field.has_error(&tester.cell.borrow_mut()));
            // No "Required" error is visible.
            expect(tester, &find::text("Required"), finds_nothing());
        });
    }

    #[test]
    fn a_field_with_an_empty_value_does_not_autovalidate_before_it_changes_on_user_interaction_if_error()
     {
        test_widgets(|tester| {
            let recorded = Rc::new(Cell::new(None));
            pump_ltr(
                tester,
                recording_field(&recorded, true)
                    .autovalidate_mode(AutovalidateMode::OnUserInteractionIfError)
                    .validator(|_app, value| required(value))
                    .into_widget(),
            );
            let field = recorded.get().expect("built");

            assert!(!field.has_error(&tester.cell.borrow_mut()));
            expect(tester, &find::text("Required"), finds_nothing());
            assert_eq!(field.error_text(&tester.cell.borrow_mut()), None);

            field.validate(&mut tester.cell.borrow_mut());
            tester.pump();

            assert!(field.has_error(&tester.cell.borrow_mut()));
            expect(tester, &find::text("Required"), finds_one_widget());
        });
    }

    #[test]
    fn a_field_autovalidates_before_its_value_changes_when_its_mode_is_always() {
        test_widgets(|tester| {
            let recorded = Rc::new(Cell::new(None));
            pump_ltr(
                tester,
                recording_field(&recorded, false)
                    .initial_value("foo".to_string())
                    .autovalidate_mode(AutovalidateMode::Always)
                    .validator(|_app, value| error_text(value))
                    .into_widget(),
            );
            let field = recorded.get().expect("built");
            assert!(field.has_error(&tester.cell.borrow_mut()));
        });
    }

    fn error_slash(value: Option<&String>) -> Option<String> {
        Some(format!(
            "error/{}",
            value.map(String::as_str).unwrap_or("null")
        ))
    }

    #[test]
    fn a_form_autovalidates_its_fields_only_after_one_changes_on_user_interaction() {
        test_widgets(|tester| {
            let keys = [GlobalKey::new(), GlobalKey::new(), GlobalKey::new()];
            let builder = || {
                Form::new(Column::new().children(keys.iter().map(|key| {
                    text_field(key)
                        .initial_value("foo".to_string())
                        .validator(|_app, value| error_slash(value))
                        .into_widget()
                })))
                .autovalidate_mode(AutovalidateMode::OnUserInteraction)
                .into_widget()
            };

            // Makes sure the Form widget won't auto-validate the form fields
            // after rebuilds if there is not user interaction.
            pump_ltr(tester, builder());
            pump_ltr(tester, builder());

            // We expect no validation error text being shown.
            expect(tester, &find::text("error/foo"), finds_nothing());

            // Set a empty string into the first form field to
            // trigger the fields validators.
            enter_text(tester, &keys[0], "");
            tester.pump();

            // Now we expect the errors to be shown for the first Text Field and
            // for the next two form fields that have their contents unchanged.
            expect(tester, &find::text("error/"), finds_one_widget());
            expect(tester, &find::text("error/foo"), finds_n_widgets(2));
        });
    }

    #[test]
    fn a_form_autovalidates_its_fields_before_any_changes_when_its_mode_is_always() {
        test_widgets(|tester| {
            let field_key = GlobalKey::new();
            let builder = || {
                Form::new(
                    text_field(&field_key)
                        // A `TextFormField` without an initial value holds an empty string.
                        .initial_value(String::new())
                        .validator(|_app, value| error_slash(value)),
                )
                .autovalidate_mode(AutovalidateMode::Always)
                .into_widget()
            };

            // The issue only happens on the second build so we
            // need to rebuild the tree twice.
            pump_ltr(tester, builder());
            pump_ltr(tester, builder());

            // We expect validation error text being shown.
            expect(tester, &find::text("error/"), finds_one_widget());
        });
    }

    #[test]
    fn form_reset_clears_errors_and_autovalidates_again_only_on_the_next_user_interaction() {
        test_widgets(|tester| {
            let form_key = GlobalKey::new();
            let field_key = GlobalKey::new();
            pump_ltr(
                tester,
                Form::new(
                    text_field(&field_key)
                        .initial_value("foo".to_string())
                        .validator(|_app, value| error_text(value)),
                )
                .key(form_key.clone().into())
                .autovalidate_mode(AutovalidateMode::OnUserInteraction)
                .into_widget(),
            );

            // No error text is visible yet.
            expect(tester, &find::text("foo/error"), finds_nothing());

            enter_text(tester, &field_key, "bar");
            tester.pump();
            tester.pump();
            expect(tester, &find::text("bar/error"), finds_one_widget());

            // Resetting the form state should remove the error text.
            let form = form_state(tester, &form_key);
            form.reset(&mut tester.cell.borrow_mut());
            tester.pump();
            expect(tester, &find::text("bar/error"), finds_nothing());
        });
    }

    #[test]
    fn a_form_on_user_interaction_if_error_revalidates_only_once_an_error_exists() {
        test_widgets(|tester| {
            let form_key = GlobalKey::new();
            let field_key = GlobalKey::new();
            pump_ltr(
                tester,
                Form::new(
                    text_field(&field_key)
                        .initial_value("foo".to_string())
                        .validator(|_app, value| required(value)),
                )
                .key(form_key.clone().into())
                .autovalidate_mode(AutovalidateMode::OnUserInteractionIfError)
                .into_widget(),
            );
            let form = form_state(tester, &form_key);

            // No error text is visible yet. (Initial valid state).
            expect(tester, &find::text("Required"), finds_nothing());

            // User types valid input 'bar' → autovalidate is disabled → still no error.
            enter_text(tester, &field_key, "bar");
            tester.pump();
            expect(tester, &find::text("Required"), finds_nothing());

            // Clear the input (invalid).
            enter_text(tester, &field_key, "");
            tester.pump();

            // Manually submit form to show the initial error (AutovalidateMode is now active).
            form.validate(&mut tester.cell.borrow_mut());
            expect(tester, &find::text("Required"), finds_nothing());
            tester.pump();

            // Verify error is shown.
            expect(tester, &find::text("Required"), finds_one_widget());

            // Now user interacts again with valid text ('baz') → validation auto-runs and clears
            // the error.
            enter_text(tester, &field_key, "baz");
            tester.pump();
            expect(tester, &find::text("Required"), finds_nothing());

            // Check the behavior of a manual validate when the text is already valid.
            // This should *confirm* the error is cleared, not re-introduce it.
            form.validate(&mut tester.cell.borrow_mut());
            tester.pump();
            expect(tester, &find::text("Required"), finds_nothing());

            // Resetting should clear form (already cleared, but a safety check).
            enter_text(tester, &field_key, "");
            form.reset(&mut tester.cell.borrow_mut());
            tester.pump();
            expect(tester, &find::text("Required"), finds_nothing());
        });
    }

    #[test]
    fn has_interacted_by_user_is_false_while_the_input_has_not_changed() {
        test_widgets(|tester| {
            let field_key = GlobalKey::new();
            pump_ltr(tester, text_field(&field_key).into_widget());

            let field = field_state::<String>(tester, &field_key);
            assert!(!field.has_interacted_by_user(&tester.cell.borrow_mut()));
        });
    }

    #[test]
    fn has_interacted_by_user_is_true_after_the_input_changed() {
        test_widgets(|tester| {
            let field_key = GlobalKey::new();
            pump_ltr(tester, text_field(&field_key).into_widget());
            let field = field_state::<String>(tester, &field_key);

            // initially, the field has not been interacted with
            assert!(!field.has_interacted_by_user(&tester.cell.borrow_mut()));

            // after entering text, the field has been interacted with
            enter_text(tester, &field_key, "foo");
            assert!(field.has_interacted_by_user(&tester.cell.borrow_mut()));
        });
    }

    #[test]
    fn has_interacted_by_user_is_false_after_the_field_is_reset() {
        test_widgets(|tester| {
            let field_key = GlobalKey::new();
            pump_ltr(tester, text_field(&field_key).into_widget());
            let field = field_state::<String>(tester, &field_key);

            // initially, the field has not been interacted with
            assert!(!field.has_interacted_by_user(&tester.cell.borrow_mut()));

            // after entering text, the field has been interacted with
            enter_text(tester, &field_key, "foo");
            assert!(field.has_interacted_by_user(&tester.cell.borrow_mut()));

            // after resetting the field, it has not been interacted with again
            field.reset(&mut tester.cell.borrow_mut());
            assert!(!field.has_interacted_by_user(&tester.cell.borrow_mut()));
        });
    }

    #[test]
    fn force_error_text_forces_an_error_state_from_the_first_build() {
        test_widgets(|tester| {
            let field_key = GlobalKey::new();
            pump_ltr(
                tester,
                Form::new(text_field(&field_key).force_error_text("Forcing error."))
                    .autovalidate_mode(AutovalidateMode::Disabled)
                    .into_widget(),
            );
            expect(tester, &find::text("Forcing error."), finds_one_widget());
        });
    }

    #[test]
    fn validate_is_false_with_a_force_error_text_even_when_the_validator_finds_no_error() {
        test_widgets(|tester| {
            let form_key = GlobalKey::new();
            let field_key = GlobalKey::new();
            pump_ltr(
                tester,
                Form::new(
                    text_field(&field_key)
                        .force_error_text("Forcing error")
                        .validator(|_app, _value| None),
                )
                .key(form_key.clone().into())
                .into_widget(),
            );

            expect(tester, &find::text("Forcing error"), finds_one_widget());
            let form = form_state(tester, &form_key);
            let is_valid = form.validate(&mut tester.cell.borrow_mut());
            assert!(!is_valid);

            tester.pump();
            expect(tester, &find::text("Forcing error"), finds_one_widget());
        });
    }

    #[test]
    fn force_error_text_forces_an_error_state_only_once_it_is_set() {
        test_widgets(|tester| {
            let form_key = GlobalKey::new();
            let field_key = GlobalKey::new();
            let builder = |force_error_text: Option<&str>| {
                let mut field = text_field(&field_key);
                if let Some(force_error_text) = force_error_text {
                    field = field.force_error_text(force_error_text);
                }
                Form::new(field)
                    .key(form_key.clone().into())
                    .autovalidate_mode(AutovalidateMode::Disabled)
                    .into_widget()
            };

            pump_ltr(tester, builder(None));
            let form = form_state(tester, &form_key);
            let is_valid = form.validate(&mut tester.cell.borrow_mut());
            assert!(is_valid);
            expect(tester, &find::text("Forcing Error Text"), finds_nothing());
            pump_ltr(tester, builder(Some("Forcing Error Text")));
            expect(
                tester,
                &find::text("Forcing Error Text"),
                finds_one_widget(),
            );
        });
    }

    #[test]
    fn the_validator_is_not_called_while_a_force_error_text_is_given() {
        test_widgets(|tester| {
            let form_key = GlobalKey::new();
            let field_key = GlobalKey::new();
            let force_error_text = "Forcing error.";
            let validator_error_text =
                "this error should not appear as we override it with forceErrorText";
            let did_call_validator = Rc::new(Cell::new(false));
            let builder = |autovalidate_mode| {
                let called = Rc::clone(&did_call_validator);
                Form::new(
                    text_field(&field_key)
                        .force_error_text(force_error_text)
                        .validator(move |_app, _value| {
                            called.set(true);
                            Some(validator_error_text.to_string())
                        }),
                )
                .key(form_key.clone().into())
                .autovalidate_mode(autovalidate_mode)
                .into_widget()
            };

            // Start off not autovalidating.
            pump_ltr(tester, builder(AutovalidateMode::Disabled));
            expect(tester, &find::text(force_error_text), finds_one_widget());
            expect(tester, &find::text(validator_error_text), finds_nothing());

            let form = form_state(tester, &form_key);
            form.reset(&mut tester.cell.borrow_mut());
            tester.pump();
            expect(tester, &find::text(force_error_text), finds_nothing());
            expect(tester, &find::text(validator_error_text), finds_nothing());

            // We have to manually validate if we're not autovalidating.
            form.validate(&mut tester.cell.borrow_mut());
            tester.pump();

            assert!(!did_call_validator.get());
            expect(tester, &find::text(force_error_text), finds_one_widget());
            expect(tester, &find::text(validator_error_text), finds_nothing());

            // Try again with autovalidation. Should validate immediately.
            pump_ltr(tester, builder(AutovalidateMode::Always));

            assert!(!did_call_validator.get());
            expect(tester, &find::text(force_error_text), finds_one_widget());
            expect(tester, &find::text(validator_error_text), finds_nothing());
        });
    }

    #[test]
    fn removing_the_validator_takes_its_error_text_away() {
        test_widgets(|tester| {
            let form_key = GlobalKey::new();
            let field_key = GlobalKey::new();
            let use_validator = Rc::new(Cell::new(false));
            let set_state = Rc::new(RefCell::new(None));
            let builder = {
                let (form_key, field_key) = (form_key.clone(), field_key.clone());
                let (use_validator, set_state) = (Rc::clone(&use_validator), Rc::clone(&set_state));
                StatefulBuilder::new(move |_app, _context, setter| {
                    *set_state.borrow_mut() = Some(setter);
                    let mut field = text_field(&field_key);
                    if use_validator.get() {
                        field = field.validator(|_app, value| {
                            value
                                .is_none_or(|value| value.is_empty())
                                .then(|| "test_error".to_string())
                        });
                    }
                    Form::new(field).key(form_key.clone().into()).into_widget()
                })
            };
            pump_ltr(tester, builder.into_widget());
            let form = form_state(tester, &form_key);
            let set_use_validator = |tester: &mut WidgetTester, value: bool| {
                let setter = set_state.borrow().clone().expect("built");
                let use_validator = Rc::clone(&use_validator);
                setter(&mut tester.cell.borrow_mut(), &mut move |_app| {
                    use_validator.set(value)
                });
                tester.pump();
            };

            // Start with no validator.
            enter_text(tester, &field_key, "");
            tester.pump();
            form.validate(&mut tester.cell.borrow_mut());
            tester.pump();
            expect(tester, &find::text("test_error"), finds_nothing());

            // Now use the validator.
            set_use_validator(tester, true);
            form.validate(&mut tester.cell.borrow_mut());
            tester.pump();
            expect(tester, &find::text("test_error"), finds_one_widget());

            // Remove the validator again and expect the error to disappear.
            set_use_validator(tester, false);
            form.validate(&mut tester.cell.borrow_mut());
            tester.pump();
            expect(tester, &find::text("test_error"), finds_nothing());
        });
    }

    /// `tester.tap` on a text field: its subtree takes the primary focus.
    fn focus(tester: &mut WidgetTester, node: AnyFocusNode) {
        node.request_focus(&mut tester.cell.borrow_mut(), None);
        tester.pump();
        tester.pump();
    }

    #[test]
    fn a_form_on_unfocus_validates_a_field_as_it_loses_the_focus() {
        test_widgets(|tester| {
            let (key1, key2) = (GlobalKey::new(), GlobalKey::new());
            let (node1, node2): (FocusNodeRef, FocusNodeRef) = {
                let mut app = tester.cell.borrow_mut();
                (
                    FocusNode::new(&mut app).into_erased(),
                    FocusNode::new(&mut app).into_erased(),
                )
            };
            let field = |key: &GlobalKey, node| {
                focusable_text_field(key, node)
                    .initial_value("bar".to_string())
                    .validator(|_app, value| error_text(value))
                    .into_widget()
            };
            pump_ltr(
                tester,
                Form::new(
                    Column::new()
                        .children([field(&key1, node1.clone()), field(&key2, node2.clone())]),
                )
                .autovalidate_mode(AutovalidateMode::OnUnfocus)
                .into_widget(),
            );

            // No error text is visible yet.
            expect(tester, &find::text("foo/error"), finds_nothing());

            // Enter text in the first TextFormField.
            focus(tester, node1.handle());
            enter_text(tester, &key1, "foo");
            tester.pump();

            // No error text is visible yet.
            expect(tester, &find::text("foo/error"), finds_nothing());

            // Tap on the second TextFormField to trigger validation.
            // This should trigger validation for the first TextFormField as well.
            focus(tester, node2.handle());

            // Verify that the error text is displayed for the first TextFormField.
            expect(tester, &find::text("foo/error"), finds_one_widget());
            expect(tester, &find::text("bar/error"), finds_nothing());

            // Tap on the first TextFormField to trigger validation.
            focus(tester, node1.handle());

            // Verify that the both error texts are displayed.
            expect(tester, &find::text("foo/error"), finds_one_widget());
            expect(tester, &find::text("bar/error"), finds_one_widget());
        });
    }

    #[test]
    fn a_field_mode_of_its_own_wins_over_the_form_on_unfocus() {
        test_widgets(|tester| {
            let (key1, key2) = (GlobalKey::new(), GlobalKey::new());
            let (node1, node2): (FocusNodeRef, FocusNodeRef) = {
                let mut app = tester.cell.borrow_mut();
                (
                    FocusNode::new(&mut app).into_erased(),
                    FocusNode::new(&mut app).into_erased(),
                )
            };
            pump_ltr(
                tester,
                Form::new(
                    Column::new().children([
                        focusable_text_field(&key1, node1.clone())
                            .autovalidate_mode(AutovalidateMode::Always)
                            .initial_value("foo".to_string())
                            .validator(|_app, value| error_text(value))
                            .into_widget(),
                        focusable_text_field(&key2, node2.clone())
                            .autovalidate_mode(AutovalidateMode::Disabled)
                            .initial_value("bar".to_string())
                            .validator(|_app, value| error_text(value))
                            .into_widget(),
                    ]),
                )
                .autovalidate_mode(AutovalidateMode::OnUnfocus)
                .into_widget(),
            );

            // Verify that the error text is displayed for the first TextFormField.
            expect(tester, &find::text("foo/error"), finds_one_widget());

            // Enter text in the TextFormField.
            focus(tester, node1.handle());
            enter_text(tester, &key1, "foo");
            tester.pump();

            // Click in the second TextFormField to trigger validation.
            focus(tester, node2.handle());

            // No error text is visible yet for the second TextFormField.
            expect(tester, &find::text("bar/error"), finds_nothing());

            // Now click in the first TextFormField to trigger validation for the second
            // TextFormField.
            focus(tester, node1.handle());

            // Verify that the error text is displayed for the second TextFormField.
            expect(tester, &find::text("bar/error"), finds_one_widget());
        });
    }

    #[test]
    fn a_form_on_unfocus_validates_every_field_when_validated_by_hand() {
        test_widgets(|tester| {
            let form_key = GlobalKey::new();
            let (key1, key2) = (GlobalKey::new(), GlobalKey::new());
            let (node1, node2): (FocusNodeRef, FocusNodeRef) = {
                let mut app = tester.cell.borrow_mut();
                (
                    FocusNode::new(&mut app).into_erased(),
                    FocusNode::new(&mut app).into_erased(),
                )
            };
            pump_ltr(
                tester,
                Form::new(
                    Column::new().children([
                        focusable_text_field(&key1, node1.clone())
                            .initial_value("foo".to_string())
                            .validator(|_app, value| error_text(value))
                            .into_widget(),
                        focusable_text_field(&key2, node2.clone())
                            .initial_value("bar".to_string())
                            .validator(|_app, value| error_text(value))
                            .into_widget(),
                    ]),
                )
                .key(form_key.clone().into())
                .autovalidate_mode(AutovalidateMode::OnUnfocus)
                .into_widget(),
            );

            // Focus on the first field.
            focus(tester, node1.handle());

            // Check no error messages are displayed initially.
            expect(tester, &find::text("foo/error"), finds_nothing());
            expect(tester, &find::text("bar/error"), finds_nothing());

            // Validate all fields manually using FormState.
            let form = form_state(tester, &form_key);
            assert!(!form.validate(&mut tester.cell.borrow_mut()));
            tester.pump();

            // Check error messages are displayed.
            expect(tester, &find::text("foo/error"), finds_one_widget());
            expect(tester, &find::text("bar/error"), finds_one_widget());
        });
    }

    #[test]
    fn a_form_always_validates_its_fields_at_the_second_frame() {
        test_widgets(|tester| {
            let (key1, key2) = (GlobalKey::new(), GlobalKey::new());
            pump_ltr(
                tester,
                Form::new(
                    Column::new().children([
                        text_field(&key1)
                            .initial_value("foo".to_string())
                            .validator(|_app, value| error_text(value))
                            .into_widget(),
                        text_field(&key2)
                            .initial_value("bar".to_string())
                            .validator(|_app, value| error_text(value))
                            .into_widget(),
                    ]),
                )
                .autovalidate_mode(AutovalidateMode::Always)
                .into_widget(),
            );

            // The validation happens in a post frame callback, so the error
            // doesn't show up until the second frame.
            expect(tester, &find::text("foo/error"), finds_nothing());
            expect(tester, &find::text("bar/error"), finds_nothing());

            tester.pump();

            // The error shows up on the second frame.
            expect(tester, &find::text("foo/error"), finds_one_widget());
            expect(tester, &find::text("bar/error"), finds_one_widget());
        });
    }

    /// `Text('X')`: a box that would be bigger than zero, which zero constraints squeeze.
    fn sized_text() -> WidgetRef {
        Text::new("X").into_widget()
    }

    #[test]
    fn a_form_does_not_crash_at_zero_area() {
        test_widgets(|tester| {
            pump_ltr(
                tester,
                Center::new()
                    .child(SizedBox::shrink().child(Form::new(sized_text())))
                    .into_widget(),
            );
            assert_eq!(tester.get_size(find::by_type::<Form>()), Size::ZERO);
        });
    }

    #[test]
    fn a_form_field_does_not_crash_at_zero_area() {
        test_widgets(|tester| {
            pump_ltr(
                tester,
                Center::new()
                    .child(
                        SizedBox::shrink()
                            .child(FormField::<String>::new(|_app, _field| sized_text())),
                    )
                    .into_widget(),
            );
            assert_eq!(
                tester.get_size(find::by_type::<FormField<String>>()),
                Size::ZERO
            );
        });
    }

    #[test]
    fn clear_error_clears_the_error_and_keeps_the_value() {
        test_widgets(|tester| {
            let field_key = GlobalKey::new();
            pump_ltr(
                tester,
                Form::new(
                    text_field(&field_key)
                        .initial_value("foo".to_string())
                        .validator(|_app, value| error_text(value)),
                )
                .into_widget(),
            );
            let field = field_state::<String>(tester, &field_key);

            field.validate(&mut tester.cell.borrow_mut());
            tester.pump();
            expect(tester, &find::text("foo/error"), finds_one_widget());

            field.clear_error(&mut tester.cell.borrow_mut());
            tester.pump();

            expect(tester, &find::text("foo/error"), finds_nothing());

            // Value is preserved.
            expect(tester, &find::text("foo"), finds_one_widget());
        });
    }

    #[test]
    fn clear_error_on_the_form_clears_every_field_error() {
        test_widgets(|tester| {
            let form_key = GlobalKey::new();
            let (key1, key2) = (GlobalKey::new(), GlobalKey::new());
            pump_ltr(
                tester,
                Form::new(
                    Column::new().children([
                        text_field(&key1)
                            .initial_value("foo".to_string())
                            .validator(|_app, value| error_text(value))
                            .into_widget(),
                        text_field(&key2)
                            .initial_value("bar".to_string())
                            .validator(|_app, value| error_text(value))
                            .into_widget(),
                    ]),
                )
                .key(form_key.clone().into())
                .into_widget(),
            );
            let form = form_state(tester, &form_key);

            form.validate(&mut tester.cell.borrow_mut());
            tester.pump();

            expect(tester, &find::text("foo/error"), finds_one_widget());
            expect(tester, &find::text("bar/error"), finds_one_widget());

            form.clear_error(&mut tester.cell.borrow_mut());
            tester.pump();

            expect(tester, &find::text("foo/error"), finds_nothing());
            expect(tester, &find::text("bar/error"), finds_nothing());
            expect(tester, &find::text("foo"), finds_one_widget());
            expect(tester, &find::text("bar"), finds_one_widget());
        });
    }

    #[test]
    fn fields_exposes_every_registered_field_state_with_its_value() {
        test_widgets(|tester| {
            let form_key = GlobalKey::new();
            let (key1, key2) = (GlobalKey::new(), GlobalKey::new());
            pump_ltr(
                tester,
                Form::new(
                    Column::new().children([
                        text_field(&key1)
                            .initial_value("A".to_string())
                            .into_widget(),
                        text_field(&key2)
                            .initial_value("B".to_string())
                            .into_widget(),
                    ]),
                )
                .key(form_key.clone().into())
                .into_widget(),
            );

            let form = form_state(tester, &form_key);
            let app = tester.cell.borrow_mut();
            let fields = form.fields(&app);
            assert_eq!(fields.len(), 2);
            let values: Vec<&String> = fields
                .iter()
                .map(|field| {
                    field
                        .value(&app)
                        .and_then(|value| value.downcast_ref::<String>())
                        .unwrap()
                })
                .collect();
            assert!(values.contains(&&"A".to_string()));
            assert!(values.contains(&&"B".to_string()));
        });
    }

    #[test]
    fn fields_reports_every_field_invalid_after_validation_errors() {
        test_widgets(|tester| {
            let form_key = GlobalKey::new();
            let (key1, key2) = (GlobalKey::new(), GlobalKey::new());
            pump_ltr(
                tester,
                Form::new(
                    Column::new().children([
                        text_field(&key1)
                            .initial_value("foo".to_string())
                            .validator(|_app, value| error_text(value))
                            .into_widget(),
                        text_field(&key2)
                            .initial_value("bar".to_string())
                            .validator(|_app, value| error_text(value))
                            .into_widget(),
                    ]),
                )
                .key(form_key.clone().into())
                .into_widget(),
            );
            let form = form_state(tester, &form_key);

            form.validate(&mut tester.cell.borrow_mut());
            tester.pump();

            expect(tester, &find::text("foo/error"), finds_one_widget());
            expect(tester, &find::text("bar/error"), finds_one_widget());

            let mut app = tester.cell.borrow_mut();
            let fields = form.fields(&app);

            // Expect all fields to be invalid.
            assert!(fields.into_iter().all(|field| !field.is_valid(&mut app)));
        });
    }

    #[test]
    fn is_valid_evaluates_validity_without_updating_the_error_display() {
        test_widgets(|tester| {
            let form_key = GlobalKey::new();
            let field_key = GlobalKey::new();
            pump_ltr(
                tester,
                Form::new(
                    text_field(&field_key)
                        .initial_value("foo".to_string())
                        .validator(|_app, value| error_text(value)),
                )
                .key(form_key.clone().into())
                .into_widget(),
            );

            let form = form_state(tester, &form_key);
            let fields = form.fields(&tester.cell.borrow_mut());
            assert_eq!(fields.len(), 1);
            let field = fields[0];

            assert!(!field.is_valid(&mut tester.cell.borrow_mut()));

            // No error UI should be shown.
            expect(tester, &find::text("foo/error"), finds_nothing());
            assert!(!field.has_error(&tester.cell.borrow_mut()));
        });
    }

    #[test]
    fn fields_collects_and_updates_the_values_of_fields_of_every_type() {
        test_widgets(|tester| {
            let form_key = GlobalKey::new();
            let keyed = |name: &str| KeyRef::from(ValueKey::new(name.to_string()));
            pump_ltr(
                tester,
                Form::new(
                    Column::new().children([
                        FormField::new(show_field)
                            .key(keyed("name"))
                            .initial_value("Name".to_string())
                            .into_widget(),
                        FormField::new(show_field)
                            .key(keyed("email"))
                            .initial_value("Email".to_string())
                            .into_widget(),
                        FormField::<i64>::new(|_app, _field| SizedBox::shrink().into_widget())
                            .key(keyed("age"))
                            .initial_value(18)
                            .into_widget(),
                    ]),
                )
                .key(form_key.clone().into())
                .into_widget(),
            );
            let form = form_state(tester, &form_key);

            let collect_data = |tester: &WidgetTester| {
                let app = tester.cell.borrow_mut();
                let mut data = Vec::new();
                for field in form.fields(&app) {
                    let key = field.context(&app).widget(&app).key().cloned();
                    let value = field.value(&app).expect("every field holds a value");
                    let value = value
                        .downcast_ref::<String>()
                        .cloned()
                        .or_else(|| value.downcast_ref::<i64>().map(i64::to_string))
                        .expect("a String or an i64");
                    data.push((key.expect("every field is keyed"), value));
                }
                data
            };

            assert_eq!(
                collect_data(tester),
                [
                    (keyed("name"), "Name".to_string()),
                    (keyed("email"), "Email".to_string()),
                    (keyed("age"), "18".to_string()),
                ]
            );

            let field = |tester: &WidgetTester, name: &str| {
                let app = tester.cell.borrow_mut();
                form.fields(&app)
                    .into_iter()
                    .find(|field| field.context(&app).widget(&app).key() == Some(&keyed(name)))
                    .expect("a field keyed so")
            };
            let name = field(tester, "name")
                .typed::<String>()
                .expect("a String field");
            let email = field(tester, "email")
                .typed::<String>()
                .expect("a String field");
            let age = field(tester, "age").typed::<i64>().expect("an i64 field");
            assert!(field(tester, "age").typed::<String>().is_none());

            name.did_change(&mut tester.cell.borrow_mut(), Some("New Name".to_string()));
            email.did_change(
                &mut tester.cell.borrow_mut(),
                Some("new@email.com".to_string()),
            );
            age.did_change(&mut tester.cell.borrow_mut(), Some(30));

            tester.pump();

            assert_eq!(
                collect_data(tester),
                [
                    (keyed("name"), "New Name".to_string()),
                    (keyed("email"), "new@email.com".to_string()),
                    (keyed("age"), "30".to_string()),
                ]
            );
        });
    }

    // ---- restoration, through a field that restores its value as `TextFormField` does ----

    /// A [`FormField`] subclass whose state also restores its value, as `TextFormField`'s
    /// restorable controller does.
    struct RestorableTextField {
        form_field: FormFieldData<String>,
    }

    impl Debug for RestorableTextField {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            self.form_field.fmt(f)
        }
    }

    impl FormFieldLeaf for RestorableTextField {
        type Value = String;
        crate::form_field_accessors!();
    }

    impl StatefulWidget for RestorableTextField {
        type State = RestorableTextFieldState;

        fn key(&self) -> Option<&KeyRef> {
            self.form_field.key.as_ref()
        }

        fn create_state(&self) -> RestorableTextFieldState {
            RestorableTextFieldState {
                state: StateData::new(),
                restoration: RestorationMixinData::new(),
                form_field_state: FormFieldStateData::new(&self.form_field),
                text: None,
            }
        }
    }

    struct RestorableTextFieldState {
        state: StateData<RestorableTextField>,
        restoration: RestorationMixinData,
        form_field_state: FormFieldStateData<String>,
        text: Option<Ref<RestorableStringN>>,
    }

    impl RestorableTextFieldState {
        fn text(self: Handle<Self>, app: &App) -> Handle<RestorableStringN> {
            app.get(self).text.handle().expect("created in init_state")
        }
    }

    impl FormFieldStateLeaf for RestorableTextFieldState {
        crate::form_field_state_accessors!();

        fn did_change(self: Handle<Self>, app: &mut App, value: Option<String>) {
            FormFieldState::did_change(self, app, value.clone());
            self.text(app).set_value(app, value);
        }

        fn reset(self: Handle<Self>, app: &mut App) {
            let initial_value = self.widget(app).form_field.initial_value.clone();
            self.text(app).set_value(app, initial_value);
            FormFieldState::reset(self, app);
        }
    }

    impl RestorationMixin for RestorableTextFieldState {
        crate::restoration_mixin_accessors!();

        fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str> {
            FormFieldState::restoration_id(self, app)
        }

        fn restore_state(
            self: Handle<Self>,
            app: &mut App,
            old_bucket: Option<Handle<RestorationBucket>>,
            initial_restore: bool,
        ) {
            FormFieldState::restore_state(self, app, old_bucket, initial_restore);
            let text = self.text(app);
            self.register_for_restoration(app, text.as_property(), "text");
            let value = RestorableValue::value(text, app).clone();
            self.set_value(app, value);
        }
    }

    impl State for RestorableTextFieldState {
        type Widget = RestorableTextField;
        crate::state_accessors!();

        fn deactivate(self: Handle<Self>, app: &mut App) {
            FormFieldState::deactivate(self, app);
        }

        fn init_state(self: Handle<Self>, app: &mut App) {
            FormFieldState::init_state(self, app);
            let initial_value = self.widget(app).form_field.initial_value.clone();
            let text = RestorableStringN::new(app, initial_value);
            app.get_mut(self).text = Some(text);
        }

        fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &RestorableTextField) {
            FormFieldState::did_update_widget(self, app, old_widget);
        }

        fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
            FormFieldState::did_change_dependencies(self, app);
        }

        fn dispose(self: Handle<Self>, app: &mut App) {
            let text = self.text(app);
            RestorableProperty::dispose(text, app);
            FormFieldState::dispose(self, app);
        }

        fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
            FormFieldState::build(self, app, context)
        }
    }

    #[test]
    fn a_lone_field_restores_its_error_text_on_user_interaction() {
        let field_key = GlobalKey::new();
        let builder = || {
            let mut form_field = FormFieldData::new(Rc::new(show_field));
            form_field.key = Some(field_key.clone().into());
            form_field.autovalidate_mode = AutovalidateMode::OnUserInteraction;
            form_field.restoration_id = Some("text_form_field".to_string());
            form_field.initial_value = Some("foo".to_string());
            form_field.validator = Some(Rc::new(|_app, value| error_text(value)));
            RootRestorationScope::new(Some("app".to_string()), RestorableTextField { form_field })
                .into_widget()
        };
        let restart_and_restore = |data: Option<RestorationMap>| {
            let mut tester = WidgetTester::restoring(data);
            pump_ltr(&mut tester, builder());
            tester
        };

        let mut tester = WidgetTester::restoring(None);
        pump_ltr(&mut tester, builder());

        // No error text is visible yet.
        expect(&tester, &find::text("foo/error"), finds_nothing());

        let field = key_state::<RestorableTextFieldState>(&tester, &field_key);
        field.did_change(&mut tester.cell.borrow_mut(), Some("bar".to_string()));
        tester.pump();
        tester.pump();
        expect(&tester, &find::text("bar/error"), finds_one_widget());

        let data = tester.restoration_data();
        let mut tester = restart_and_restore(data.clone());
        // Error text should be present after restart and restore.
        expect(&tester, &find::text("bar/error"), finds_one_widget());

        // Resetting the form state should remove the error text.
        let field = key_state::<RestorableTextFieldState>(&tester, &field_key);
        field.reset(&mut tester.cell.borrow_mut());
        tester.pump();
        tester.pump();
        expect(&tester, &find::text("bar/error"), finds_nothing());
        let tester = restart_and_restore(tester.restoration_data());
        // Error text should still be removed after restart and restore.
        expect(&tester, &find::text("bar/error"), finds_nothing());

        let tester = restart_and_restore(data);
        expect(&tester, &find::text("bar/error"), finds_one_widget());
    }

    fn key_state<S: State>(tester: &WidgetTester, key: &GlobalKey) -> Handle<S> {
        key.current_state::<S>(&tester.cell.borrow())
            .expect("the field is mounted")
    }

    #[test]
    fn a_form_with_can_pop_wraps_its_fields_in_a_pop_scope() {
        test_widgets(|tester| {
            pump_ltr(
                tester,
                Form::new(SizedBox::shrink()).can_pop(false).into_widget(),
            );
            expect(tester, &find::by_type::<PopScope>(), finds_one_widget());
            tester.widget(find::by_type::<PopScope>(), |scope: &PopScope| {
                assert!(!scope.can_pop);
            });

            pump_ltr(tester, Form::new(SizedBox::shrink()).into_widget());
            expect(tester, &find::by_type::<PopScope>(), finds_nothing());
        });
    }
}