Skip to content

RawAutocomplete dropdown shows previous keyword results if the optionsBuilder resolves previous keyword Futures slower than the latest ones #150774

@mohsinraza-fdev

Description

@mohsinraza-fdev

Steps to reproduce

  1. Add "http" package in pubspec
  2. Run the sample code

Expected results

When you type a keyword into the RawAutocomplete field, the dropdown results should represent the api output from the latest text inside the search field.

Actual results

When you start typing into the RawAutocomplete field the dropdown results show the output of the slowest call resolved by the options builder amongst all the calls in progress instead of the last call made to the optionsBuilder.

For Instance in the sample code i am using the google books api, i have added delay in the function which resolves the http call (As the google books api responds a bit too fast), that reduces with the keyword length.

You can see in the video attached that when i type keywords into the field, the results of the dropdown represent the slowest call resolved amongst all the active calls at the time when i stopped typing, instead of showing the the results from the last call made to the optionsBuilder.

Code sample

Code sample
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: RawAutoCompleteExample(),
    );
  }
}

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

  @override
  State<RawAutoCompleteExample> createState() => _RawAutoCompleteExampleState();
}

class _RawAutoCompleteExampleState extends State<RawAutoCompleteExample> {
  final _controller = TextEditingController();
  final _focusNode = FocusNode();

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SizedBox(
          width: 350,
          child: RawAutocomplete<String>(
            textEditingController: _controller,
            focusNode: _focusNode,
            fieldViewBuilder: _fieldViewBuilder,
            optionsViewBuilder: _optionsViewBuilder,
            optionsBuilder: _searchLocation,
          ),
        ),
      ),
    );
  }

  Widget _fieldViewBuilder(
      BuildContext context, controller, focusNode, onSubmit) {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 150),
      height: 40,
      alignment: Alignment.center,
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
      constraints: const BoxConstraints(minHeight: 40),
      decoration: BoxDecoration(
        color: Colors.transparent,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          width: 1,
          color: Colors.grey,
        ),
      ),
      child: TextField(
        controller: controller,
        focusNode: focusNode,
        maxLines: 1,
        decoration: const InputDecoration(
          isCollapsed: true,
          floatingLabelBehavior: FloatingLabelBehavior.never,
          alignLabelWithHint: true,
          border: InputBorder.none,
        ),
      ),
    );
  }

  Widget _optionsViewBuilder(BuildContext context,
      void Function(String) onSelect, Iterable<String> options) {
    return Align(
      alignment: Alignment.topLeft,
      child: Material(
        child: Container(
          margin: const EdgeInsets.only(top: 7),
          height: (40.0 * (options.length > 4 ? 4 : options.length)) + 16,
          width: 350,
          padding: const EdgeInsets.all(8),
          clipBehavior: Clip.antiAlias,
          decoration: ShapeDecoration(
            color: Colors.white,
            shape: RoundedRectangleBorder(
              side: const BorderSide(
                width: 1,
                color: Colors.grey,
              ),
              borderRadius: BorderRadius.circular(12),
            ),
            shadows: const [
              BoxShadow(
                color: Color(0x19000000),
                blurRadius: 8,
                offset: Offset(0, 4),
                spreadRadius: 0,
              )
            ],
          ),
          child: ListView(
            children: options
                .map((option) => GestureDetector(
                      onTap: () => onSelect(option),
                      child: AnimatedContainer(
                        height: 40,
                        alignment: Alignment.centerLeft,
                        decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0),
                            borderRadius: BorderRadius.circular(24)),
                        duration: const Duration(milliseconds: 150),
                        padding: const EdgeInsets.symmetric(horizontal: 16),
                        child: Text(
                          option.toString(),
                        ),
                      ),
                    ))
                .toList(),
          ),
        ),
      ),
    );
  }

  Future<List<String>> _searchLocation(TextEditingValue keyword) async {
    final response = await http.get(Uri.parse(
        'https://dev-gateway.digitalhire.com/v1/recruitment/static-listing/locations?search=${keyword.text}&page=1&pageSize=5000'));

    if (response.statusCode == 200) {
      List<dynamic> data = json.decode(response.body);
      return [
        keyword.text,
        ...data
            .map((e) => '${e["city"] as String?}, ${e["state"] as String?}')
            .toList()
      ];
    } else {
      throw Exception('Failed to load data');
    }
  }
}

Screenshots or Video

Screenshots / Video demonstration
Screen.Recording.2024-06-25.at.4.33.27.PM.mov

Logs

Logs
[Paste your logs here]

Flutter Doctor output

Doctor output
[✓] Flutter (Channel stable, 3.22.2, on macOS 14.0 23A344 darwin-arm64, locale
    en-PK)
    • Flutter version 3.22.2 on channel stable at
      /Users/mohsinraza/Documents/Core/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 761747bfc5 (3 weeks ago), 2024-06-05 22:15:13 +0200
    • Engine revision edd8546116
    • Dart version 3.4.3
    • DevTools version 2.34.3

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
    • Android SDK at /Users/mohsinraza/Library/Android/sdk
    • Platform android-34, build-tools 33.0.1
    • Java binary at: /Applications/Android
      Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build
      17.0.6+0-17.0.6b802.4-9586694)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 15.4)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 15F31d
    • CocoaPods version 1.15.2

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

[✓] Android Studio (version 2022.2)
    • 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
      17.0.6+0-17.0.6b802.4-9586694)

[✓] IntelliJ IDEA Ultimate Edition (version 2023.1.2)
    • IntelliJ at /Applications/IntelliJ IDEA.app
    • 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

[✓] VS Code (version 1.90.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.90.0

[✓] Connected device (3 available)
    • macOS (desktop)                 • macos                 • darwin-arm64   •
      macOS 14.0 23A344 darwin-arm64
    • Mac Designed for iPad (desktop) • mac-designed-for-ipad • darwin         •
      macOS 14.0 23A344 darwin-arm64
    • Chrome (web)                    • chrome                • web-javascript •
      Google Chrome 126.0.6478.63

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

• No issues found!

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2Important issues not at the top of the work listfound in release: 3.22Found to occur in 3.22found in release: 3.23Found to occur in 3.23frameworkflutter/packages/flutter repository. See also f: labels.has reproducible stepsThe issue has been confirmed reproducible and is ready to work onr: fixedIssue is closed as already fixed in a newer versionteam-text-inputOwned by Text Input teamtriaged-text-inputTriaged by Text Input team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions