Home > OS >  Autocomplete Textfield with an List title input
Autocomplete Textfield with an List title input

Time:09-13


import 'dart:convert';

import 'package:condomini/condominio.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(const MyHomePage());
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

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

class _MyHomePageState extends State<MyHomePage> {
  List<Condominio> condomini = [];

  @override
  void initState() {
    var url = Uri.parse('http://www.ixee.it/index.php/flutter/getcondomini');
    http.get(url).then((response) => setState(() {
          condomini = List<Condominio>.from(
            jsonDecode(response.body)['condomini']?.map(
              (mappa) => Condominio.fromMap(mappa),
            ),
          );
        }));

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("STEB"),
      ),
      body: Column(
        children: <Widget>[
          Container(
            margin: EdgeInsets.symmetric(
              horizontal: 10,
            ),
            child: Row(
              children: <Widget>[
                Flexible(
                  child: TextField(
                    
                    decoration: InputDecoration(
                      contentPadding:
                          EdgeInsets.symmetric(vertical: 20, horizontal: 10),
                      hintText: "Inserisci via",
                      hintStyle: TextStyle(color: Colors.blue, fontSize: 20),
                      
                      isDense: true, // Added this
                    ),
                  ),
                ),
                SizedBox(
                  width: 10,
                ),
                ElevatedButton(
                  onPressed: () {},
                  child: Text("CERCA"),
                ),
              ],
            ),
          ),
          Expanded(
            child: ListView.builder(
                shrinkWrap: true,
                itemCount: condomini.length,
                
                itemBuilder: (BuildContext context, int index) {
                  
                  return ListTile(
                    title: Text(condomini[index].nome),
                    subtitle: Text(condomini[index].indirizzo),
                    trailing: Icon(Icons.arrow_drop_up_rounded),
                    
                  );
                }),
          )
        ],
      ),
    );
  }
}

I have this code where I need to create an android app where I will have a fixed Textfield where I can write the street of a building. The list of buildings complete with street and name, are taken from a request to a server with a response to a json file. What I need to be able to do is to be able to select a street in the building and automatically enter it in the fixed text field at the top of the page.

CodePudding user response:

Check this Example : Hope this will help you .

dependencies:
  auto_complete_search: ^0.0.4

Example:

import 'package:flutter/material.dart';
import 'package:auto_complete_search/auto_complete_search.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final List areaList = [
    {"name": "Block 1", "id": "124612615"},
    {"name": "Block 2", "id": "124612615"},
    {"name": "Block 3", "id": "124612615"},
    {"name": "PECHS block 1", "id": "124612615"},
    {"name": "PECHS block 2", "id": "124612615"},
    {"name": "PECHS block 3", "id": "124612615"},
    {"name": "PECHS block 4", "id": "124612615"},
    {"name": "PECHS block 5", "id": "124612615"},
    {"name": "PECHS block 6", "id": "124612615"},
    {"name": "PECHS block 7", "id": "12461265"},
    {"name": "PECHS block 8", "id": "12461215"},
    {"name": "PECHS block 9", "id": "12461615"},
    {"name": "PECHS block 0", "id": "12462615"},
    {"name": "PECHS block 89", "id": "12612615"},
    {"name": "PECHS block 88", "id": "1261265"},
    {"name": "PECHS block 87", "id": "14612615"},
  ];
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Auto Complete Search Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Auto Complete Search Demo', areaList: areaList),
    );
  }
}

class Area {
  final String name;
  final String id;
  static List<Area> areas;

  Area({this.name, this.id});
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title, this.areaList}) : super(key: key);
  final String title;
  final List areaList;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final TextEditingController areaCtrl = TextEditingController();
  GlobalKey key = new GlobalKey<AutoCompleteSearchFieldState<Area>>();
  List<Area> areas = [];

  @override
  void initState() {
    List<Area> areas = widget.areaList
        .map((area) => Area(name: area["name"], id: area["id"]))
        .toList();
    Area.areas = areas;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Align(
          alignment: Alignment.center,
          child: AutoCompleteSearchField(
            key: key,
            controller: areaCtrl,
            submitOnSuggestionTap: true,
            itemSorter: (Area a, Area b) =>
                a.name.toLowerCase().compareTo(b.name.toLowerCase()),
            suggestions: Area.areas,
            itemSubmitted: (Area area) {
              setState(() {
                this.areaCtrl.text = area.name;
              });
            },
            suggestionsDirection: SuggestionsDirection.down,
            suggestionWidgetSize: 50.0,
            itemBuilder: (context, suggestion) => new Padding(
                child: new ListTile(
                  title: new Text(suggestion.name),
                ),
                padding: const EdgeInsets.all(4.0)),
            itemFilter: (suggestion, input) =>
                suggestion.name.toLowerCase().contains(input.toLowerCase()),
            clearOnSubmit: false,
          )),
    );
  }
}

CodePudding user response:

// ignore_for_file: prefer_const_constructors

import 'dart:convert';
import 'package:condomini/condominio.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(const MyHomePage());
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

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

class _MyHomePageState extends State<MyHomePage> {
  List<Condominio> condomini = [];
  // ignore: prefer_final_fields
  TextEditingController _controller = TextEditingController();

  @override
  void initState() {
    var url = Uri.parse('MYURL');
    http.get(url).then((response) => setState(() {
          condomini = List<Condominio>.from(
            jsonDecode(response.body)['condomini']?.map(
              (mappa) => Condominio.fromMap(mappa),
            ),
          );
        }));

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("STEB"),
      ),
      body: Column(
        children: <Widget>[
          Container(
            margin: EdgeInsets.symmetric(
              horizontal: 10,
            ),
            child: Row(
              children: <Widget>[
                Flexible(
                  child: TextField(
                    //usa una funzione che permette di accedere all'inserimento automatico del testo
                    controller: _controller,
                    decoration: InputDecoration(
                      contentPadding:
                          EdgeInsets.symmetric(vertical: 20, horizontal: 10),
                      hintText: "Inserisci via",
                      hintStyle: TextStyle(color: Colors.blue, fontSize: 20),

                      isDense: true, // Added this
                    ),
                  ),
                ),
                SizedBox(
                  width: 10,
                ),
                ElevatedButton(
                  onPressed: () {
                    // ignore: todo
                    // TODO crea collegamento con pagina /seriali
                    Navigator.pushNamed(context, '/seriali');
                  },
                  child: Text("CERCA"),
                ),
              ],
            ),
          ),
          Expanded(
            child: ListView.builder(
                shrinkWrap: true,
                itemCount: condomini.length,
                itemBuilder: (BuildContext context, int index) {
                  // rendi disponibile la selezione "onclick" di una voce, reindirizzandola all'autocompilazione del campo di testo
                  return ListTile(
                    onTap: () => _controller.text = condomini[index].nome,
                    title: Text(condomini[index].nome),
                    subtitle: Text(condomini[index].indirizzo),
                    trailing: Icon(Icons.arrow_drop_up_rounded),
                  );
                }),
          )
        ],
      ),
    );
  }
}

Very simply the body became Column and then I created two lines: one for the Textfield and for the Button while the second line was used to have the scrollable list keeping the first line (Textfield and Button) fixed at the top.

  • Related