Autocomplete suggestion and search using json data

2019-07-29 12:43发布

问题:

I want to display data from local json in list as suggestions when user types in a textfield. The suggestions displayed should be based on id that is associated with text to be displayed. Somehow I am not able to achieve to display the data in UI and how to build the hierarchy of widgets that will display suggestions in list. Not sure what am I missing here. Looking for guidance. End result I am looking to achieve is:

Json snippet:

{
    "data": [{
        "serviceCategory": "ELECTRICAL",
        "serviceCategoryDesc": "Electrical",
        "serviceCategoryId": 3,
        "autocompleteTerm": "Accent Lighting Installation",
        "category": "IMPROVEMENT",

Ex : If user types electrical, then autocompleteterm value should be displayed in the list.

For this, I created model class and fetching it's data which is displayed in console properly.

class Categories {
  String serviceCategory;
  String servCategoryDesc;
  int id;
  String autocompleteterm;
  String category;
  String desc;

  Categories({
    this.serviceCategory,
    this.servCategoryDesc,
    this.id,
    this.autocompleteterm,
    this.category,
    this.desc
  });

  factory Categories.fromJson(Map<String, dynamic> parsedJson) {
    return Categories(
        serviceCategory: parsedJson['serviceCategory'] as String,
        servCategoryDesc: parsedJson['serviceCategoryDesc'] as String,
        id: parsedJson['serviceCategoryId'],
        autocompleteterm: parsedJson['autocompleteTerm'] as String,
        category: parsedJson['category'] as String,
        desc: parsedJson['description'] as String
    );
  }
}

Code :

    // Get json result and convert it to model. Then add
      Future<String> getUserDetails() async {

        String jsonData = await DefaultAssetBundle.of(context).loadString('assets/services.json');
        Map data = json.decode(jsonData);
        print(data);

        setState(() {
          final List<Categories> items = (data['data'] as List).map((i) => new Categories.fromJson(i)).toList();
          for (final item in items) {
            print(item.autocompleteterm);
          }
        });
      }

GlobalKey<AutoCompleteTextFieldState<Categories>> key = new GlobalKey();

   get categories => List<Categories>();

  AutoCompleteTextField textField;

  String currentText = "";

  List<Categories> added = [];

@override
  void initState() {
    textField = AutoCompleteTextField<Categories>
      (style: new TextStyle(
      color: Colors.white,
      fontSize: 16.0),
      decoration: new InputDecoration(
        suffixIcon: Container(
          width: 85.0,
          height: 60.0,
          color:Colors.green,
          child: new IconButton(
            icon: new Image.asset('assets/search_icon_ivory.png',color: Colors.white,
            height: 18.0,),
            onPressed: (){},
          ),
        ),
        fillColor: Colors.black,
        contentPadding: EdgeInsets.fromLTRB(10.0, 30.0, 10.0, 20.0),
        filled: true,
        hintText: 'Search',
        hintStyle: TextStyle(
          color: Colors.white
        )
      ),
        itemSubmitted: null,
        submitOnSuggestionTap: true,
        clearOnSubmit: true,
        textChanged: (item) {
        currentText = item;
        },
        textSubmitted: (item) {
        setState(() {
          currentText = item;
          added.add(widget.categories.firstWhere((i) => i.autocompleteterm.toLowerCase().contains(currentText)));
        });
        },
        key: key,
        suggestions: widget.categories,
        itemBuilder: (context, item) {
        return new Padding(
          padding: EdgeInsets.all(8.0), child: new Text(item.autocompleteterm),
        );
        },
        itemSorter: (a,b) {
        return a.autocompleteterm.compareTo(b.autocompleteterm);
        },
        itemFilter: (item, query){
        return item.autocompleteterm.toLowerCase().startsWith(query.toLowerCase());
        });
    super.initState();
    _getUser();
    getUserDetails();
  }

  @override
  Widget build(BuildContext context) {
    Column body = new Column(
      children: <Widget>[
        ListTile(
          title: textField,
        )
      ],
    );
    body.children.addAll(added.map((item) {
      return ListTile(title: Text(item.autocompleteterm),
      );
    }
    )
    );

    return Scaffold(
        resizeToAvoidBottomPadding: false,
        backgroundColor: Color(0xFF13212C),
        appBar: AppBar(
          title: Text('Demo'),
        ),
        drawer: appDrawer(),
        body: new Center(
        child: new Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          new Column(
            children: <Widget>[
              textField,
        ]
    ),

回答1:

The autocomplete_field package has been updated since this question was asked and now allows the use of objects other than Strings to work:

HomePage:

import 'package:flutter/material.dart';
import 'package:hello_world/category.dart';
import 'package:autocomplete_textfield/autocomplete_textfield.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => new _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<Category> added = [];
  String currentText = "";
  GlobalKey<AutoCompleteTextFieldState<Category>> key = new GlobalKey();
  AutoCompleteTextField textField;

  @override void initState() {
      textField = new AutoCompleteTextField<Category>(
        decoration: new InputDecoration(
          hintText: "Search Item",
        ),
        key: key,
        submitOnSuggestionTap: true,
        clearOnSubmit: true,
        suggestions: CategoryViewModel.categories,
        textInputAction: TextInputAction.go,
        textChanged: (item) {
          currentText = item;
        },
        itemSubmitted: (item) {
          setState(() {
            currentText = item.autocompleteterm;
            added.add(item);
            currentText = "";
          });
        },
        itemBuilder: (context, item) {
          return new Padding(
              padding: EdgeInsets.all(8.0), child: new Text(item.autocompleteterm));
        },
        itemSorter: (a, b) {
          return a.autocompleteterm.compareTo(b.autocompleteterm);
        },
        itemFilter: (item, query) {
          return item.autocompleteterm.toLowerCase().startsWith(query.toLowerCase());
        }
      );
      super.initState();
    }

  @override
  Widget build(BuildContext context) {
    Column body = new Column(children: [
      new ListTile(
          title: textField,
          trailing: new IconButton(
              icon: new Icon(Icons.add),
              onPressed: () {
                setState(() {
                  if (currentText != "") {
                    added.add(CategoryViewModel.categories.firstWhere((i) => i.autocompleteterm.toLowerCase().contains(currentText)));
                    textField.clear();
                    currentText = "";
                  }
                });
              }))
    ]);

    body.children.addAll(added.map((item) {
      return ListTile(title: Text(item.autocompleteterm), subtitle: Text(item.serviceCategory));
    }));

    return body;
  }
}

Category classes:

import 'dart:convert';

import 'package:flutter/services.dart' show rootBundle;

class Category {
  String serviceCategory;
  String servCategoryDesc;
  int id;
  String autocompleteterm;

  Category(
      {this.serviceCategory,
      this.servCategoryDesc,
      this.id,
      this.autocompleteterm});

  factory Category.fromJson(Map<String, dynamic> parsedJson) {
    return new Category(
        serviceCategory: parsedJson['serviceCategory'],
        servCategoryDesc: parsedJson['serviceCategoryDesc'],
        id: parsedJson['serviceCategoryId'],
        autocompleteterm: parsedJson['autocompleteTerm']);
  }
}

class CategoryViewModel {
  static List<Category> categories;

  static Future loadCategories() async {
    try {
      categories = new List<Category>();
      String jsonString = await rootBundle.loadString('assets/categories.json');
      Map parsedJson = json.decode(jsonString);
      var categoryJson = parsedJson['data'] as List;
      for (int i = 0; i < categoryJson.length; i++) {
        categories.add(new Category.fromJson(categoryJson[i]));
      }
    } catch (e) {
      print(e);
    }
  }
}

Main with loading data:

void main() async {
  await CategoryViewModel.loadCategories();
  runApp(App());
}

Note, there are a few ways to load the data from the JSON but I find this way is easiest to do for a simple demo.