flutter-autocomplete-textfield
flutter-autocomplete-textfield copied to clipboard
Get id of value
How can iget selected id from autocomplete_textfield ?
This id my code : import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'User.dart'; import 'dart:convert'; import 'package:autocomplete_textfield/autocomplete_textfield.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } }
class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title;
@override _MyHomePageState createState() => _MyHomePageState(); }
class _MyHomePageState extends State<MyHomePage> { AutoCompleteTextField searchTextField; GlobalKey<AutoCompleteTextFieldState<User>> key = new GlobalKey(); static List<User> users = new List<User>(); bool loading = true;
//https://jsonplaceholder.typicode.com/users void getUser() async { try { final response = await http.get("https://jsonplaceholder.typicode.com/users"); if (response.statusCode == 200) { users = loadUser(response.body); setState(() { loading = false; }); } else { print("Error!"); } } catch (e) { print("Error!"); } }
static List<User> loadUser(String jsonString) { final parsed = json.decode(jsonString).cast<Map<String, dynamic>>(); return parsed.map<User>((json) => User.fromJson(json)).toList(); }
@override void initState() { getUser(); // TODO: implement initState super.initState(); }
Widget row(User user) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( user.name, style: TextStyle(fontSize: 16.0), ), SizedBox( width: 10.0, ), Text( user.email, style: TextStyle(fontSize: 16.0), ), ], ); }
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Column( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ loading ? CircularProgressIndicator() : searchTextField = AutoCompleteTextField<User>( key: key, clearOnSubmit: false, suggestions: users, style: TextStyle(color: Colors.black, fontSize: 16.0), decoration: InputDecoration( contentPadding: EdgeInsets.all(8.0), hintText: "Search box", hintStyle: TextStyle(color: Colors.blueAccent), ), itemFilter: (item, query) { return item.name .toLowerCase() .startsWith(query.toLowerCase()); }, itemSorter: (a, b) { return a.name.compareTo(b.name); }, itemSubmitted: (item) { setState(() { searchTextField.textField.controller.text = item.name; }); }, itemBuilder: (context, item) { return row(item); }, ), Text(searchTextField.textField.controller.text) ], ), ); } }