Skip to content

SearchAnchor.bar lacks a focusNode parameter #177454

Closed
flutter/packages
#12863

Description

@lucavenir

Steps to reproduce

Use SearchAnchor.bar.

Notice how barFocusNode is not a parameter.

Expected results

Let this constructor accept a barFocusNode

Actual results

I can't pipe a FocusNode to this constructor.

Because of this, even tho I submit anything by pressing Enter on my keyboard after seeing some results on the search view, the focus is kept on the search bar. This leads to poor UX if not bugs, directly.

Code sample

Code sample
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

void main() {
  runApp(const ProviderScope(child: MyWidget()));
}

class MyWidget extends ConsumerWidget {
  const MyWidget({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return const MaterialApp(
      home: Scaffold(
        body: Center(child: MySearchAnchorBar()),
      ),
    );
  }
}

class MySearchAnchorBar extends StatefulWidget {
  const MySearchAnchorBar({super.key});

  @override
  State<MySearchAnchorBar> createState() => _MySearchAnchorBarState();
}

class _MySearchAnchorBarState extends State<MySearchAnchorBar> {
  late final SearchController _controller;

  @override
  void initState() {
    super.initState();
    _controller = SearchController();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SearchAnchor.bar(
      searchController: _controller,
      barElevation: WidgetStateProperty.all(2),
      barPadding: const WidgetStatePropertyAll(
        EdgeInsets.symmetric(horizontal: 12),
      ),

      viewHeaderTextStyle: const TextStyle(fontSize: 14),
      barTextStyle: WidgetStateProperty.all(
        const TextStyle(fontSize: 14),
      ),
      viewLeading: const Icon(Icons.search),
      viewBarPadding: const EdgeInsets.symmetric(horizontal: 12),
      scrollPadding: EdgeInsets.zero,
      viewPadding: EdgeInsets.zero,
      onSubmitted: (value) {
        _controller.closeView(value);
        // focus is kept on the bar.
      },
      suggestionsBuilder: (context, controller) async {
        final results = await Future.value(<String>['Example1', 'Example2']);

        return [
          for (final element in results)
            ListTile(
              title: Text(
                element,
              ),
              onTap: () {
                print('Selected: $element');
                controller.closeView(element);
              },
            ),
        ];
      },
    );
  }
}

Screenshots or Video

N.A.

Logs

N.A.

Flutter Doctor output

Doctor output
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.35.5, on macOS 15.6.1 24G90 darwin-arm64, locale en-IT)
[✓] Android toolchain - develop for Android devices (Android SDK version 36.0.0-rc1)
[✓] Xcode - develop for iOS and macOS (Xcode 26.0.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2024.2)
[✓] VS Code (version 1.105.1)
[✓] Connected device (2 available)
[✓] Network resources

• No issues found!

Activity

  1. lucavenir commented on Oct 23, 2025

    @lucavenir
    Author

    I'm more than willing to open a PR for this, it should be trivial.

  2. added
    in triagePresently being triaged by the triage team
    on Oct 24, 2025
  3. huycozy commented on Oct 24, 2025

    @huycozy
    Member

    Hello @lucavenir
    When using your sample code, I see another issue (assertion is thrown after pressing Enter key). Also, the focus is lost. Is this intentional or a separate issue?

    Demo screenshot/video
    Screen.Recording.2025-10-24.at.17.58.01.mov
    Output log
    ════════ Exception caught by widgets ═══════════════════════════════════════════
    The following assertion was thrown while calling onSubmitted for TextInputAction.done:
    'package:flutter/src/material/search_anchor.dart': Failed assertion: line 1344 pos 12: 'isAttached': is not true.
    
    When the exception was thrown, this was the stack:
    #2      SearchController.closeView (package:flutter/src/material/search_anchor.dart:1344:12)
    search_anchor.dart:1344
    #3      _MySearchAnchorBarState.build.<anonymous closure> (package:repro_issues/177454.dart:54:21)
    177454.dart:54
    #4      EditableTextState._finalizeEditing (package:flutter/src/widgets/editable_text.dart:3771:18)
    editable_text.dart:3771
    #5      EditableTextState.performAction (package:flutter/src/widgets/editable_text.dart:3561:9)
    editable_text.dart:3561
    #6      TextInput._handleTextInputInvocation (package:flutter/src/services/text_input.dart:2110:39)
    text_input.dart:2110
    #7      TextInput._loudlyHandleTextInputInvocation (package:flutter/src/services/text_input.dart:1973:20)
    text_input.dart:1973
    #8      MethodChannel._handleAsMethodCall (package:flutter/src/services/platform_channel.dart:608:55)
    platform_channel.dart:608
    #9      MethodChannel.setMethodCallHandler.<anonymous closure> (package:flutter/src/services/platform_channel.dart:598:55)
    platform_channel.dart:598
    #10     _DefaultBinaryMessenger.setMessageHandler.<anonymous closure> (package:flutter/src/services/binding.dart:665:35)
    binding.dart:665
    #11     _invoke2 (dart:ui/hooks.dart:388:13)
    hooks.dart:388
    #12     _ChannelCallbackRecord.invoke (dart:ui/channel_buffers.dart:45:5)
    channel_buffers.dart:45
    #13     _Channel.push (dart:ui/channel_buffers.dart:136:31)
    channel_buffers.dart:136
    #14     ChannelBuffers.push (dart:ui/channel_buffers.dart:344:17)
    channel_buffers.dart:344
    #15     PlatformDispatcher._dispatchPlatformMessage (dart:ui/platform_dispatcher.dart:819:22)
    platform_dispatcher.dart:819
    #16     _dispatchPlatformMessage (dart:ui/hooks.dart:302:31)
    hooks.dart:302
    (elided 2 frames from class _AssertionError)

    About adding a focusNode parameter to SearchAnchor.bar, I think we can consider this as a feature request.

  4. added
    waiting for responseThe Flutter team cannot make further progress on this issue until the original reporter responds
    on Oct 24, 2025
  5. lucavenir commented on Oct 24, 2025

    @lucavenir
    Author

    About adding a focusNode parameter to SearchAnchor.bar, I think we can consider this as a feature request.

    Yes, thank you, that was the point of this issue. Sorry for the confusion.

    Nonetheless, I've updated the above example to make sure no exceptions are thrown.

    The above example is to show that:

    1. by default, closing the search anchor view does not clear the focus away from the search bar
    2. there's no way to work around this because we can't inject a FocusNode in there

    About point 1: that is pretty common functionality. You perform some search, you press Enter halfway there, and you're happy with the first results. You'd expect the focus not to be on the search bar anymore.

  6. removed
    waiting for responseThe Flutter team cannot make further progress on this issue until the original reporter responds
    on Oct 24, 2025
  7. lucavenir commented on Oct 24, 2025

    @lucavenir
    Author

    About that - should I make a different issue about the default behavior of the search anchor?

  8. huycozy commented on Oct 27, 2025

    @huycozy
    Member

    You perform some search, you press Enter halfway there, and you're happy with the first results. You'd expect the focus not to be on the search bar anymore.

    It appears that the default behavior is to lose focus after pressing Enter, as shown in the demo I shared. This issue may become an applicable proposal if you expect it's able to manage focus on SearchAnchor.bar, by adding a focusNode parameter to the constructor. Please let me know if that is the case.

  9. added
    waiting for responseThe Flutter team cannot make further progress on this issue until the original reporter responds
    on Oct 27, 2025
  10. github-actions commented on Nov 17, 2025

    @github-actions
  11. lucavenir commented on Nov 17, 2025

    @lucavenir
    Author

    dang it, I forgot about this issue.

    can we reopen it? there are problems in here.


    I took some time to address this, and indeed...

    It appears that the default behavior is to lose focus after pressing Enter, as shown in the demo I shared.

    ...the behavior I see is completely different.

    Again, just to be 110% sure, the code is the following:

    code
    import "package:flutter/material.dart";
    import "package:flutter_riverpod/flutter_riverpod.dart";
    
    void main() {
      runApp(const ProviderScope(child: MySearchBarPage()));
    }
    
    class MySearchBarPage extends ConsumerWidget {
      const MySearchBarPage({super.key});
    
      @override
      Widget build(BuildContext context, WidgetRef ref) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: const Text("My Search Bar Page"),
            ),
            body: const Center(
              child: MySearchAnchorBar(),
            ),
          ),
        );
      }
    }
    
    class MySearchAnchorBar extends StatefulWidget {
      const MySearchAnchorBar({super.key});
    
      @override
      State<MySearchAnchorBar> createState() => _MySearchAnchorBarState();
    }
    
    class _MySearchAnchorBarState extends State<MySearchAnchorBar> {
      late final SearchController _controller;
    
      @override
      void initState() {
        super.initState();
        _controller = SearchController();
      }
    
      @override
      void dispose() {
        _controller.dispose();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return SearchAnchor.bar(
          searchController: _controller,
          barElevation: WidgetStateProperty.all(2),
          barPadding: const WidgetStatePropertyAll(
            EdgeInsets.symmetric(horizontal: 12),
          ),
    
          viewHeaderTextStyle: const TextStyle(fontSize: 14),
          barTextStyle: WidgetStateProperty.all(
            const TextStyle(fontSize: 14),
          ),
          viewLeading: const Icon(Icons.search),
          viewBarPadding: const EdgeInsets.symmetric(horizontal: 12),
          scrollPadding: EdgeInsets.zero,
          viewPadding: EdgeInsets.zero,
          onSubmitted: (value) {
            _controller.closeView(value);
            // focus is kept on the bar.
          },
          suggestionsBuilder: (context, controller) async {
            final results = await Future.value(<String>["Example1", "Example2"]);
    
            return [
              for (final element in results)
                ListTile(
                  title: Text(
                    element,
                  ),
                  onTap: () {
                    print("Selected: $element");
                    controller.closeView(element);
                  },
                ),
            ];
          },
        );
      }
    }

    And to be 220% sure we're on the same page, here's the repro steps:

    1. Click the search bar (by tapping it, you focus it)
    2. See the suggestions appear: Example 1 and Example 2 appear
    3. Type exa in the search bar
    4. Press Enter (submit)
    5. You'll see focus is not lost, and indeed
    6. Press Enter again
    7. The app becomes black (the current page is popped, meaning that _controller.closeView(value) is evaluated again, and that such evaluation leads to a context.pop)
    video
    Screen.Recording.2025-11-17.at.09.24.54.mov

    So, from this issue, I see two different bugs and an enhancement:

    1. bug 1: after a onSubmitted event, focus is not lost
    2. bug 2: triggering .closeView twice leads to a .pop (but I'd expect this to trigger an AssertionError instead, or a StateError, or anything else really)
    3. feature request: let SearchAnchor.bar accept a focusNode parameter (that I can tackle in a PR)

    Thank you for your patience, @huycozy, if you could confirm or deny any of the above, that'd be great.

  12. removed
    waiting for responseThe Flutter team cannot make further progress on this issue until the original reporter responds
    on Nov 17, 2025
  13. huycozy commented on Nov 17, 2025

    @huycozy
    Member

    welcome back @lucavenir ,

    The app becomes black (the current page is popped, meaning that _controller.closeView(value) is evaluated again, and that such evaluation leads to a context.pop)

    I'm able to reproduce this too. However, per triage pov, I consider it as a bug report type, could you please help to file another issue in bug type, because this issue (based on the title and what is discussed above) seems to a feature request?

    feature request: let SearchAnchor.bar accept a focusNode parameter

    Marking this as a feature request.

  14. 11 remaining items

  15. added
    ⏳Bot is counting down the days until it unassigns the issue
    on Mar 25, 2026
  16. flutter-triage-bot commented on Mar 25, 2026

    @flutter-triage-bot

    This issue is assigned to @lucavenir but has had no recent status updates. Please consider unassigning this issue if it is not going to be addressed in the near future. This allows people to have a clearer picture of what work is actually planned. Thanks!

  17. flutter-triage-bot commented on Jun 10, 2026

    @flutter-triage-bot

    This issue was assigned to @lucavenir but has had no status updates in a long time. To remove any ambiguity about whether the issue is being worked on, the assignee was removed.

  18. removed
    ⏳Bot is counting down the days until it unassigns the issue
    on Jun 10, 2026
  19. dkwingsmt commented on Jun 17, 2026

    @dkwingsmt
    Contributor

    @lucavenir Let's keep it this way to keep the bot happy. We have the PR ready for the new package and that's what matters. :)

  20. lucavenir commented on Jun 17, 2026

    @lucavenir
    Author

    yay! happy bot, happy team! hear you soon!

  21. added
    packageflutter/packages repository. See also p: labels.
    and removed
    frameworkflutter/packages/flutter repository. See also f: labels.
    on Aug 17, 2026
  22. added a commit that references this issue on Oct 20, 2026
    497b0b1
  23. github-actions commented on Nov 3, 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.

  24. locked as resolved and limited conversation to collaborators on Nov 3, 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

    P3Issues that are less important to the Flutter projectc: new featureNothing broken; request for a new capabilityp: material_uimaterial_ui package in flutter/packagespackageflutter/packages repository. See also p: labels.team-designOwned by Design Languages teamtriaged-designTriaged by Design Languages team

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions