felixmccuaig / flutter-autocomplete-textfield

An autocomplete Textfield for flutter
MIT License
181 stars 131 forks source link

Get id of value #55

Open HosseinBabriani opened 5 years ago

HosseinBabriani commented 5 years ago

How can iget selected id from autocomplete_textfield ?

HosseinBabriani commented 5 years ago

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 { AutoCompleteTextField searchTextField; GlobalKey<AutoCompleteTextFieldState> key = new GlobalKey(); static List users = new List(); 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 loadUser(String jsonString) { final parsed = json.decode(jsonString).cast<Map<String, dynamic>>(); return parsed.map((json) => User.fromJson(json)).toList(); }

@override void initState() { getUser(); // TODO: implement initState super.initState(); }

Widget row(User user) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ 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: [ loading ? CircularProgressIndicator() : searchTextField = AutoCompleteTextField( 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) ], ), ); } }