|
| 1 | +// Copyright 2014 The Flutter Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style license that can be |
| 3 | +// found in the LICENSE file. |
| 4 | + |
| 5 | +import 'dart:async'; |
| 6 | + |
| 7 | +import 'package:flutter/material.dart'; |
| 8 | + |
| 9 | +/// Flutter code sample for [Autocomplete] that demonstrates fetching the |
| 10 | +/// options asynchronously and debouncing the network calls. |
| 11 | +
|
| 12 | +const Duration fakeAPIDuration = Duration(seconds: 1); |
| 13 | +const Duration debounceDuration = Duration(milliseconds: 500); |
| 14 | + |
| 15 | +void main() => runApp(const AutocompleteExampleApp()); |
| 16 | + |
| 17 | +class AutocompleteExampleApp extends StatelessWidget { |
| 18 | + const AutocompleteExampleApp({super.key}); |
| 19 | + |
| 20 | + @override |
| 21 | + Widget build(BuildContext context) { |
| 22 | + return MaterialApp( |
| 23 | + home: Scaffold( |
| 24 | + appBar: AppBar( |
| 25 | + title: const Text('Autocomplete - async and debouncing'), |
| 26 | + ), |
| 27 | + body: const Center( |
| 28 | + child: _AsyncAutocomplete(), |
| 29 | + ), |
| 30 | + ), |
| 31 | + ); |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +class _AsyncAutocomplete extends StatefulWidget { |
| 36 | + const _AsyncAutocomplete(); |
| 37 | + |
| 38 | + @override |
| 39 | + State<_AsyncAutocomplete > createState() => _AsyncAutocompleteState(); |
| 40 | +} |
| 41 | + |
| 42 | +class _AsyncAutocompleteState extends State<_AsyncAutocomplete > { |
| 43 | + // The query currently being searched for. If null, there is no pending |
| 44 | + // request. |
| 45 | + String? _currentQuery; |
| 46 | + |
| 47 | + // The most recent options received from the API. |
| 48 | + late Iterable<String> _lastOptions = <String>[]; |
| 49 | + |
| 50 | + late final _Debounceable<Iterable<String>?, String> _debouncedSearch; |
| 51 | + |
| 52 | + // Calls the "remote" API to search with the given query. Returns null when |
| 53 | + // the call has been made obsolete. |
| 54 | + Future<Iterable<String>?> _search(String query) async { |
| 55 | + _currentQuery = query; |
| 56 | + |
| 57 | + // In a real application, there should be some error handling here. |
| 58 | + final Iterable<String> options = await _FakeAPI.search(_currentQuery!); |
| 59 | + |
| 60 | + // If another search happened after this one, throw away these options. |
| 61 | + if (_currentQuery != query) { |
| 62 | + _currentQuery = null; |
| 63 | + return null; |
| 64 | + } |
| 65 | + _currentQuery = null; |
| 66 | + |
| 67 | + return options; |
| 68 | + } |
| 69 | + |
| 70 | + @override |
| 71 | + void initState() { |
| 72 | + super.initState(); |
| 73 | + _debouncedSearch = _debounce<Iterable<String>?, String>(_search); |
| 74 | + } |
| 75 | + |
| 76 | + @override |
| 77 | + Widget build(BuildContext context) { |
| 78 | + return Autocomplete<String>( |
| 79 | + optionsBuilder: (TextEditingValue textEditingValue) async { |
| 80 | + final Iterable<String>? options = await _debouncedSearch(textEditingValue.text); |
| 81 | + if (options == null) { |
| 82 | + return _lastOptions; |
| 83 | + } |
| 84 | + _lastOptions = options; |
| 85 | + return options; |
| 86 | + }, |
| 87 | + onSelected: (String selection) { |
| 88 | + debugPrint('You just selected $selection'); |
| 89 | + }, |
| 90 | + ); |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +// Mimics a remote API. |
| 95 | +class _FakeAPI { |
| 96 | + static const List<String> _kOptions = <String>[ |
| 97 | + 'aardvark', |
| 98 | + 'bobcat', |
| 99 | + 'chameleon', |
| 100 | + ]; |
| 101 | + |
| 102 | + // Searches the options, but injects a fake "network" delay. |
| 103 | + static Future<Iterable<String>> search(String query) async { |
| 104 | + await Future<void>.delayed(fakeAPIDuration); // Fake 1 second delay. |
| 105 | + if (query == '') { |
| 106 | + return const Iterable<String>.empty(); |
| 107 | + } |
| 108 | + return _kOptions.where((String option) { |
| 109 | + return option.contains(query.toLowerCase()); |
| 110 | + }); |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +typedef _Debounceable<S, T> = Future<S?> Function(T parameter); |
| 115 | + |
| 116 | +/// Returns a new function that is a debounced version of the given function. |
| 117 | +/// |
| 118 | +/// This means that the original function will be called only after no calls |
| 119 | +/// have been made for the given Duration. |
| 120 | +_Debounceable<S, T> _debounce<S, T>(_Debounceable<S?, T> function) { |
| 121 | + _DebounceTimer? debounceTimer; |
| 122 | + |
| 123 | + return (T parameter) async { |
| 124 | + if (debounceTimer != null && !debounceTimer!.isCompleted) { |
| 125 | + debounceTimer!.cancel(); |
| 126 | + } |
| 127 | + debounceTimer = _DebounceTimer(); |
| 128 | + try { |
| 129 | + await debounceTimer!.future; |
| 130 | + } catch (error) { |
| 131 | + if (error is _CancelException) { |
| 132 | + return null; |
| 133 | + } |
| 134 | + rethrow; |
| 135 | + } |
| 136 | + return function(parameter); |
| 137 | + }; |
| 138 | +} |
| 139 | + |
| 140 | +// A wrapper around Timer used for debouncing. |
| 141 | +class _DebounceTimer { |
| 142 | + _DebounceTimer( |
| 143 | + ) { |
| 144 | + _timer = Timer(debounceDuration, _onComplete); |
| 145 | + } |
| 146 | + |
| 147 | + late final Timer _timer; |
| 148 | + final Completer<void> _completer = Completer<void>(); |
| 149 | + |
| 150 | + void _onComplete() { |
| 151 | + _completer.complete(); |
| 152 | + } |
| 153 | + |
| 154 | + Future<void> get future => _completer.future; |
| 155 | + |
| 156 | + bool get isCompleted => _completer.isCompleted; |
| 157 | + |
| 158 | + void cancel() { |
| 159 | + _timer.cancel(); |
| 160 | + _completer.completeError(const _CancelException()); |
| 161 | + } |
| 162 | +} |
| 163 | + |
| 164 | +// An exception indicating that the timer was canceled. |
| 165 | +class _CancelException implements Exception { |
| 166 | + const _CancelException(); |
| 167 | +} |
0 commit comments