Skip to content

Unhandled Exception when pop Dialog into Autocomplete onSelected method #170403

Closed

Description

@rogeriomq

Steps to reproduce

Just create a Dialog, which contains as a child an autocomplete component, which, in the onSelected method, executes the Navigation POP

Flutter throws Unhandler Exception when, into onSelected method in AutoComplete Widget, execute Navigator.of(context).pop(); If the autocomplete widget is inside a Dialog.

Expected results

Close dialog without unhandled exception throws.

Actual results

Bellow is the error thrown:

[ERROR:flutter/runtime/dart_vm_initializer.cc(40)] Unhandled Exception: 'package:flutter/src/widgets/overlay.dart': Failed assertion: line 1682 pos 14: '_zOrderIndex != null': is not true.
#0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:67:4)
errors_patch.dart:67
#1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:49:5)
errors_patch.dart:49
#2      OverlayPortalController.hide (package:flutter/src/widgets/overlay.dart:1682:14)
overlay.dart:1682
#3      _RawAutocompleteState._updateOptionsViewVisibility (package:flutter/src/widgets/autocomplete.dart:403:30)
autocomplete.dart:403
#4      _RawAutocompleteState._onChangedField (package:flutter/src/widgets/autocomplete.dart:436:5)
autocomplete.dart:436
<asynchronous suspension>

Code sample

Here is the darpad link to the code I used to replicate the error.

DartPad

Screenshots or Video

Logs

Logs
[ERROR:flutter/runtime/dart_vm_initializer.cc(40)] Unhandled Exception: 'package:flutter/src/widgets/overlay.dart': Failed assertion: line 1682 pos 14: '_zOrderIndex != null': is not true.
#0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:67:4)
errors_patch.dart:67
#1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:49:5)
errors_patch.dart:49
#2      OverlayPortalController.hide (package:flutter/src/widgets/overlay.dart:1682:14)
overlay.dart:1682
#3      _RawAutocompleteState._updateOptionsViewVisibility (package:flutter/src/widgets/autocomplete.dart:403:30)
autocomplete.dart:403
#4      _RawAutocompleteState._onChangedField (package:flutter/src/widgets/autocomplete.dart:436:5)
autocomplete.dart:436
<asynchronous suspension>

Flutter Doctor output

Doctor output
flutter doctor -v
[✓] Flutter (Channel stable, 3.32.2, on macOS 15.5 24F74 darwin-arm64, locale
    en-BR) [346ms]
    • Flutter version 3.32.2 on channel stable at
      /Users/destroyer/.puro/envs/stable/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 8defaa71a7 (6 days ago), 2025-06-04 11:02:51 -0700
    • Engine revision 1091508939
    • Dart version 3.8.1
    • DevTools version 2.45.1

[✓] Android toolchain - develop for Android devices (Android SDK version
    32.1.0-rc1) [1,286ms]
    • Android SDK at /Users/destroyer/Library/Android/sdk
    • Platform android-33, build-tools 32.1.0-rc1
    • ANDROID_HOME = /Users/destroyer/Library/Android/sdk
    • Java binary at: /Applications/Android
      Studio.app/Contents/jbr/Contents/Home/bin/java
      This is the JDK bundled with the latest Android Studio installation on
      this machine.
      To manually set the JDK path, use: `flutter config
      --jdk-dir="path/to/jdk"`.
    • Java version OpenJDK Runtime Environment (build 21.0.5+-12932927-b750.29)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 16.4) [781ms]
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 16F6
    • CocoaPods version 1.16.2

[✓] Chrome - develop for the web [12ms]
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2024.2) [11ms]
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 21.0.5+-12932927-b750.29)

[✓] VS Code (version 1.100.3) [10ms]
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.113.20250603

[✓] Connected device (2 available) [6.0s]
    • macOS (desktop) • macos  • darwin-arm64   • macOS 15.5 24F74 darwin-arm64
    • Chrome (web)    • chrome • web-javascript • Google Chrome 137.0.7151.69

[✓] Network resources [882ms]
    • All expected network resources are available.

• No issues found!

Activity

  1. tirth-patel-nc commented on Jun 11, 2025

    @tirth-patel-nc
    Member

    Triage Report

    I was able to reproduce the issue using the provided code sample on the stable (3.29.3), stable (3.32.2) and master (3.33.0-1.0.pre.444) channels.

    Code Sample (Same as OP)
    import 'dart:async';
    
    import 'package:flutter/material.dart';
    
    void main() => runApp(const DialogExampleApp());
    
    class DialogExampleApp extends StatelessWidget {
      const DialogExampleApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(title: const Text('Dialog Sample')),
            body: const Center(child: DialogExample()),
          ),
        );
      }
    }
    
    class DialogExample extends StatelessWidget {
      const DialogExample({super.key});
    
      @override
      Widget build(BuildContext context) {
        return Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextButton(
              onPressed: () => showDialog<String>(
                context: context,
                builder: (BuildContext context) => Dialog(
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        const Text('This is a typical dialog.'),
                        const SizedBox(height: 15),
                        AsyncAutocomplete(),
                      ],
                    ),
                  ),
                ),
              ),
              child: const Text('Show Dialog'),
            ),
            const SizedBox(height: 10),
            TextButton(
              onPressed: () => showDialog<String>(
                context: context,
                builder: (BuildContext context) => Dialog.fullscreen(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      const Text('This is a fullscreen dialog.'),
                      const SizedBox(height: 15),
                      TextButton(
                        onPressed: () {
                          Navigator.pop(context);
                        },
                        child: const Text('Close'),
                      ),
                    ],
                  ),
                ),
              ),
              child: const Text('Show Fullscreen Dialog'),
            ),
          ],
        );
      }
    }
    
    const Duration fakeAPIDuration = Duration(seconds: 1);
    const Duration debounceDuration = Duration(milliseconds: 500);
    
    class AsyncAutocomplete extends StatefulWidget {
      const AsyncAutocomplete({super.key});
    
      @override
      State<AsyncAutocomplete> createState() => _AsyncAutocompleteState();
    }
    
    class _AsyncAutocompleteState extends State<AsyncAutocomplete> {
      // The query currently being searched for. If null, there is no pending
      // request.
      String? _currentQuery;
    
      // The most recent options received from the API.
      late Iterable<String> _lastOptions = <String>[];
    
      late final _Debounceable<Iterable<String>?, String> _debouncedSearch;
    
      // Calls the "remote" API to search with the given query. Returns null when
      // the call has been made obsolete.
      Future<Iterable<String>?> _search(String query) async {
        _currentQuery = query;
    
        // In a real application, there should be some error handling here.
        final Iterable<String> options = await _FakeAPI.search(_currentQuery!);
    
        // If another search happened after this one, throw away these options.
        if (_currentQuery != query) {
          return null;
        }
        _currentQuery = null;
    
        return options;
      }
    
      @override
      void initState() {
        super.initState();
        _debouncedSearch = _debounce<Iterable<String>?, String>(_search);
      }
    
      @override
      Widget build(BuildContext context) {
        return Column(
          spacing: 20,
          children: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(); // Close the dialog
              },
              child: Text('Close modal without autocomplete'),
            ),
            Autocomplete<String>(
              optionsBuilder: (TextEditingValue textEditingValue) async {
                final Iterable<String>? options = await _debouncedSearch(
                  textEditingValue.text,
                );
                if (options == null) {
                  return _lastOptions;
                }
                _lastOptions = options;
                return options;
              },
              onSelected: (String selection) {
                debugPrint('You just selected $selection');
                // When POP into autocomplete, generate unhandled error.
                Navigator.of(context).pop(); // Close the dialog after selection
              },
            ),
          ],
        );
      }
    }
    
    // Mimics a remote API.
    class _FakeAPI {
      static const List<String> _kOptions = <String>[
        'aardvark',
        'bobcat',
        'chameleon',
      ];
    
      // Searches the options, but injects a fake "network" delay.
      static Future<Iterable<String>> search(String query) async {
        await Future<void>.delayed(fakeAPIDuration); // Fake 1 second delay.
        if (query == '') {
          return const Iterable<String>.empty();
        }
        return _kOptions.where((String option) {
          return option.contains(query.toLowerCase());
        });
      }
    }
    
    typedef _Debounceable<S, T> = Future<S?> Function(T parameter);
    
    /// Returns a new function that is a debounced version of the given function.
    ///
    /// This means that the original function will be called only after no calls
    /// have been made for the given Duration.
    _Debounceable<S, T> _debounce<S, T>(_Debounceable<S?, T> function) {
      _DebounceTimer? debounceTimer;
    
      return (T parameter) async {
        if (debounceTimer != null && !debounceTimer!.isCompleted) {
          debounceTimer!.cancel();
        }
        debounceTimer = _DebounceTimer();
        try {
          await debounceTimer!.future;
        } on _CancelException {
          return null;
        }
        return function(parameter);
      };
    }
    
    // A wrapper around Timer used for debouncing.
    class _DebounceTimer {
      _DebounceTimer() {
        _timer = Timer(debounceDuration, _onComplete);
      }
    
      late final Timer _timer;
      final Completer<void> _completer = Completer<void>();
    
      void _onComplete() {
        _completer.complete();
      }
    
      Future<void> get future => _completer.future;
    
      bool get isCompleted => _completer.isCompleted;
    
      void cancel() {
        _timer.cancel();
        _completer.completeError(const _CancelException());
      }
    }
    
    // An exception indicating that the timer was canceled.
    class _CancelException implements Exception {
      const _CancelException();
    }
    Log
    E/flutter ( 6991): [ERROR:flutter/runtime/dart_vm_initializer.cc(40)] Unhandled Exception: 'package:flutter/src/widgets/overlay.dart': Failed assertion: line 1682 pos 14: '_zOrderIndex != null': is not true.
    E/flutter ( 6991): #0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:67:4)
    errors_patch.dart:67
    E/flutter ( 6991): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:49:5)
    errors_patch.dart:49
    E/flutter ( 6991): #2      OverlayPortalController.hide (package:flutter/src/widgets/overlay.dart:1682:14)
    overlay.dart:1682
    E/flutter ( 6991): #3      _RawAutocompleteState._updateOptionsViewVisibility (package:flutter/src/widgets/autocomplete.dart:403:30)
    autocomplete.dart:403
    E/flutter ( 6991): #4      _RawAutocompleteState._onChangedField (package:flutter/src/widgets/autocomplete.dart:436:5)
    autocomplete.dart:436
    E/flutter ( 6991): <asynchronous suspension>
    E/flutter ( 6991): 
    Screen.Recording.2025-06-11.at.3.30.57.PM.mov
  2. added
    frameworkflutter/packages/flutter repository. See also f: labels.
    has reproducible stepsThe issue has been confirmed reproducible and is ready to work on
    team-designOwned by Design Languages team
    p: material_uimaterial_ui package in flutter/packages
    a: error messageError messages from the Flutter framework
    and removed
    in triagePresently being triaged by the triage team
    team-designOwned by Design Languages team
    on Jun 11, 2025
  3. added
    P2Important issues not at the top of the work list
    on Jun 24, 2025
  4. added a commit that references this issue on Jan 12, 2026
    404221c
  5. added a commit that references this issue on Jan 15, 2026
    6c8dcc8
  6. github-actions commented on Jan 27, 2026

    @github-actions

    This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

  7. locked as resolved and limited conversation to collaborators on Jan 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2Important issues not at the top of the work lista: error messageError messages from the Flutter frameworkfound in release: 3.32Found to occur in 3.32found in release: 3.33Found to occur in 3.33frameworkflutter/packages/flutter repository. See also f: labels.has reproducible stepsThe issue has been confirmed reproducible and is ready to work onp: material_uimaterial_ui package in flutter/packagesr: fixedIssue is closed as already fixed in a newer versionteam-frameworkOwned by Framework teamtriaged-frameworkTriaged by Framework team

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions