blob: d4da62e74d85feaad068008ee74d95e301d94277 [file] [log] [blame]
Greg Spencer33403bd2021-08-25 09:45:12 -07001// 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
Greg Spencer33403bd2021-08-25 09:45:12 -07005// Flutter code sample for Autocomplete
Greg Spencer33403bd2021-08-25 09:45:12 -07006
7import 'package:flutter/material.dart';
8
9void main() => runApp(const AutocompleteExampleApp());
10
11class AutocompleteExampleApp extends StatelessWidget {
12 const AutocompleteExampleApp({Key? key}) : super(key: key);
13
14 @override
15 Widget build(BuildContext context) {
16 return MaterialApp(
17 home: Scaffold(
18 appBar: AppBar(
19 title: const Text('Autocomplete Basic User'),
20 ),
21 body: const Center(
22 child: AutocompleteBasicUserExample(),
23 ),
24 ),
25 );
26 }
27}
28
29@immutable
30class User {
31 const User({
32 required this.email,
33 required this.name,
34 });
35
36 final String email;
37 final String name;
38
39 @override
40 String toString() {
41 return '$name, $email';
42 }
43
44 @override
45 bool operator ==(Object other) {
46 if (other.runtimeType != runtimeType) {
47 return false;
48 }
49 return other is User && other.name == name && other.email == email;
50 }
51
52 @override
53 int get hashCode => hashValues(email, name);
54}
55
56class AutocompleteBasicUserExample extends StatelessWidget {
57 const AutocompleteBasicUserExample({Key? key}) : super(key: key);
58
59 static const List<User> _userOptions = <User>[
60 User(name: 'Alice', email: 'alice@example.com'),
61 User(name: 'Bob', email: 'bob@example.com'),
62 User(name: 'Charlie', email: 'charlie123@gmail.com'),
63 ];
64
65 static String _displayStringForOption(User option) => option.name;
66
67 @override
68 Widget build(BuildContext context) {
69 return Autocomplete<User>(
70 displayStringForOption: _displayStringForOption,
71 optionsBuilder: (TextEditingValue textEditingValue) {
72 if (textEditingValue.text == '') {
73 return const Iterable<User>.empty();
74 }
75 return _userOptions.where((User option) {
76 return option
77 .toString()
78 .contains(textEditingValue.text.toLowerCase());
79 });
80 },
81 onSelected: (User selection) {
Ian Hicksonf25b8332021-10-07 16:48:04 -070082 debugPrint('You just selected ${_displayStringForOption(selection)}');
Greg Spencer33403bd2021-08-25 09:45:12 -070083 },
84 );
85 }
86}