Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Explore Autocomplete Widget In Flutter

Flutter came out a couple of days prior and presents to us an extremely valuable widget called Autocomplete. With this new companion, we presently can rapidly carry out autocomplete text fields without utilizing any outsider party plugins. Making a pursuit field with ideas that show up as the client types something is currently perfect and simple.

In this article, we will Explore Autocomplete Widget In Flutter. We will execute a demo program of the autocomplete and tell you the best way to utilize the widget, including how to set the options, customize the TextField, and handle the choice chose events in your flutter applications.

Autocomplete class – material library – Dart API
A widget for helping the user make a selection by entering some text and choosing from among a list of options. The…api.flutter.dev

Table Of Contents::

Introduction

Constructor

Properties

Code Implement

Code File

Conclusion



Introduction:

On the off chance that you have a text field in your Flutter application, for certain cases, it would be pleasant if you can give a list of choices that clients can choose from. Subsequently, the clients don’t have to type the total text and henceforth can further develop the client experience. In Flutter, that should be possible by utilizing Autocomplete widget. It’s a widget that permits the client to type on text enter and choose over a list of choices.

Demo Module :

This demo video shows how to use autocomplete in a flutter. It shows how to autocomplete will work in your flutter applications. It shows when users tap on textfield then will show down some suggestions and yow will also pick up those suggestions. It will be shown on your device.

Constructor:

To utilize Autocomplete, you need to call the constructor underneath:

const Autocomplete({
Key? key,
required AutocompleteOptionsBuilder<T> optionsBuilder,
AutocompleteOptionToString<T> displayStringForOption = RawAutocomplete.defaultStringForOption,
AutocompleteFieldViewBuilder fieldViewBuilder =
_defaultFieldViewBuilder,
AutocompleteOnSelected<T>? onSelected,
AutocompleteOptionsBuilder<T>? optionsViewBuilder,
})

The Autocomplete class itself has a generic kind T expands Object. That implies the choice item can be any kind of object, not a string.

Properties:

There are some properties of Autocompleteare:

  • > key: The widget’s key, used to control how a widget is replaced with another widget.
  • > optionsBuilder: Returns the selectable options objects given the current TextEditingValue.
  • > displayStringForOption: Returns the string to be shown for choice.
  • > fieldViewBuilder: Used to construct the field whose info is utilized to get the alternatives. If not given, will construct a standard Material-style text field by default.
  • > onSelected: A function that will be considered when a choice is chosen by the user.
  • > optionsViewBuilder: Used to assemble the selectable options widgets from a list of choices objects.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called country_page.dart inside the lib folder.

To start with, we will make a class name Country to be utilized as the choice item.

class Country {

const Country({
required this.name,
required this.size,
});

final String name;
final int size;

@override
String toString() {
return '$name ($size)';
}
}

Create a new dart file called main.dart inside the lib folder.

const List<Country> countryOptions = <Country>[
Country(name: 'Africa', size: 30370000),
Country(name: 'Asia', size: 44579000),
Country(name: 'Australia', size: 8600000),
Country(name: 'Bulgaria', size: 110879),
Country(name: 'Canada', size: 9984670),
Country(name: 'Denmark', size: 42916),
Country(name: 'Europe', size: 10180000),
Country(name: 'India', size: 3287263),
Country(name: 'North America', size: 24709000),
Country(name: 'South America', size: 17840000),
];

When calling the constructor, you need to pass Country as the generic type.

Autocomplete<Country>(
// Put the arguments here
)

There is a necessarily named contention optionsBuilder. For that contention, you need to pass a function that returns the list of options that can be chosen by the user. The following are instances of how to make the options builder and pass different contentions upheld by Flutter’s Autocomplete widget.

  • > Set Options Builder:

You can handle the list of choices accessible to browse by making your own AutocompleteOptionsBuilder and pass it as optionsBuilder. The AutocompleteOptionsBuilder is a function that acknowledges a boundary of type TextEditingValue and returns an Iterable of T. By using the passed TextEditingValue, you can filter the list of options to be shown depending on the current text.

optionsBuilder: (TextEditingValue textEditingValue) {
return countryOptions
.where((Country county) => county.name.toLowerCase()
.startsWith(textEditingValue.text.toLowerCase())
)
.toList();
},
  • > Set Displayed String Options:

Of course, Flutter will utilize the toString method for the generic kind as the shown string for every choice, as you can see from the past output. Be that as it may, it’s feasible to set the string to be shown by passing displayStringForOption contention. You need to pass a function that acknowledges a boundary of type T and returns the string that you need to show in the options.

In the code beneath, the function passed as displayStringForOption returns the name property of the Country class.

displayStringForOption: (Country option) => option.name,
  • > Set Field View Builder:

For the text field, Flutter will construct a standard Material-style text field of default. Assuming you need to utilize an altered TextView, you can pass fieldViewBuilder contention. The value for the contention is a function with four boundaries whose types all together are BuildContext, TextEditingController, FocusNode, and VoidCallback. The return kind of the function is a Widget.

The underneath model passes the fieldViewBuilder contention with the passed work returns a TextField with a custom text style.:

fieldViewBuilder: (
BuildContext context,
TextEditingController fieldTextEditingController,
FocusNode fieldFocusNode,
VoidCallback onFieldSubmitted
) {
return TextField(
controller: fieldTextEditingController,
focusNode: fieldFocusNode,
style: const TextStyle(fontWeight: FontWeight.bold),
);
},
  • > Set Options View Builder:

The function should have three boundaries whose types all together are BuildContextAutocompleteOnSelected<T>, and Iterable<T>. The subsequent boundary is the function to be considered when a thing is chosen, while the third boundary is the list of options. The return kind of the function is a Widget.

Generally, you need to utilize the passed options to assemble a list of widgets. Likewise, the Autocomplete widget should be advised when the client chooses an option. To tell the Autocomplete widget, call the AutocompleteOnSelected function and pass the selected item as the contention.

The beneath model makes a custom view for the options by making a ListView wrapped as the child of a Container. Each list item is wrapped as the child of a GestureDetector widget, settling on it conceivable to decision the AutocompleteOnSelected function when a tap gesture happens.

optionsViewBuilder: (
BuildContext context,
AutocompleteOnSelected<Country> onSelected,
Iterable<Country> options
) {
return Align(
alignment: Alignment.topLeft,
child: Material(
child: Container(
width: 300,
color: Colors.cyan,
child: ListView.builder(
padding: EdgeInsets.all(10.0),
itemCount: options.length,
itemBuilder: (BuildContext context, int index) {
final Country option = options.elementAt(index);

return GestureDetector(
onTap: () {
onSelected(option);
},
child: ListTile(
title: Text(option.name, style: const TextStyle(color: Colors.white)),
),
);
},
),
),
),
);
},
  • > Set On Selected Callback:

At the point when the client chooses an item from the options, you can get the event by passing a callback function as onSelected contention. The callback function acknowledges a boundary of type T and returns void.

onSelected: (Country selection) {
print('Selected: ${selection.name}');
},

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Final Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_autocomplete_demo/country_page.dart';
import 'package:flutter_autocomplete_demo/splash_screen.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

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


const List<Country> countryOptions = <Country>[
Country(name: 'Africa', size: 30370000),
Country(name: 'Asia', size: 44579000),
Country(name: 'Australia', size: 8600000),
Country(name: 'Bulgaria', size: 110879),
Country(name: 'Canada', size: 9984670),
Country(name: 'Denmark', size: 42916),
Country(name: 'Europe', size: 10180000),
Country(name: 'India', size: 3287263),
Country(name: 'North America', size: 24709000),
Country(name: 'South America', size: 17840000),
];

class AutoCompleteDemo extends StatefulWidget {

@override
State<StatefulWidget> createState() => _AutoCompleteDemoState();
}

class _AutoCompleteDemoState extends State<AutoCompleteDemo> {

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title:Text('Flutter AutoComplete Demo'),
backgroundColor: Colors.cyan,
),
body: Padding(
padding: EdgeInsets.all(15.0),
child: Autocomplete<Country>(
optionsBuilder: (TextEditingValue textEditingValue) {
return countryOptions
.where((Country county) => county.name.toLowerCase()
.startsWith(textEditingValue.text.toLowerCase())
)
.toList();
},
displayStringForOption: (Country option) => option.name,
fieldViewBuilder: (
BuildContext context,
TextEditingController fieldTextEditingController,
FocusNode fieldFocusNode,
VoidCallback onFieldSubmitted
) {
return TextField(
controller: fieldTextEditingController,
focusNode: fieldFocusNode,
style: const TextStyle(fontWeight: FontWeight.bold),
);
},
onSelected: (Country selection) {
print('Selected: ${selection.name}');
},
optionsViewBuilder: (
BuildContext context,
AutocompleteOnSelected<Country> onSelected,
Iterable<Country> options
) {
return Align(
alignment: Alignment.topLeft,
child: Material(
child: Container(
width: 300,
color: Colors.cyan,
child: ListView.builder(
padding: EdgeInsets.all(10.0),
itemCount: options.length,
itemBuilder: (BuildContext context, int index) {
final Country option = options.elementAt(index);

return GestureDetector(
onTap: () {
onSelected(option);
},
child: ListTile(
title: Text(option.name, style: const TextStyle(color: Colors.white)),
),
);
},
),
),
),
);
},
),
),
);
}
}

Conclusion:

In the article, I have explained the basic structure of the Autocomplete Widget in a flutter; you can modify this code according to your choice. This was a small introduction to Autocomplete Widget On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying up the Autocomplete Widget in your flutter projects. We will show you what the Introduction is?. Show a constructor and properties of the Autocomplete Widget. The AutoComplete widget can be utilized to give a superior user experience to the users by permitting them to choose from a list of qualities. On the off chance that is essential, you can likewise generate the choices dynamically (for example from API response) rather than utilizing static choices like in this article. You can likewise consider utilizing RawAutocomplete which permits you to pass FocusNode and TextEditingController as contentions when utilizing an external field. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.

find the source code of the Flutter Autocomplete Widget Demo:

GitHub – flutter-devs/flutter_autocomplete_widget_demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Leave comment

Your email address will not be published. Required fields are marked with *.