如何从本地json连接数据以实现列表中自动完成文本的搜索?

时间:2018-11-22 10:59:44

标签: json flutter flutter-layout

我正在尝试实现输入搜索功能,其中键入搜索文本将显示建议的文本,并且用户可以从列表中选择相关文本,然后单击搜索按钮以进入相应的屏幕。建议的文本位于local json中,我将其添加到assets/文件夹下的pubspec.yaml下。 搜索文本字段为:

enter image description here

上面的代码是:

new TextField(
            style: new TextStyle(
            color: Colors.white,
          fontSize: 16.0),
          cursorColor: Colors.green,
          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: new EdgeInsets.fromLTRB(10.0, 30.0, 10.0, 20.0),
            filled: true,
            hintText: 'What Do You Need Help With?',
            hintStyle: new TextStyle(
              color: Colors.white
            )
        )
        )

本地json数据示例为: enter image description here

我想使用已安装并导入的autocomplete_textfield软件包并参考this示例来实现以上目的。

我想知道如何开始并集成来自本地json的解析,使用autocomplete_textfield包将数据挂钩以实现我的目标。我还没有在flutter中解析json,所以正在寻找如何做到这一点的指导。 我正在寻找的最终结果是这样的:

enter image description here enter image description here

*****************编辑**************

我现在可以使用演示应用程序从local json解析数据并将其显示在listView中。为此,我创建了一个新的模型类`services.dart',如下所示:

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
    );
  }
}

使用builder函数来检索和显示listview中的值,如下所示:

@override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text("Load local JSON file"),
        ),
        body: new Container(
            child: new Center(
              // Use future builder and DefaultAssetBundle to load the local JSON file
                child: new FutureBuilder(
                  future: DefaultAssetBundle
                      .of(context)
                      .loadString('assets/services.json'),
                  builder: (context, snapshot) {
                    // Decode the JSON
                    Map data = json.decode(snapshot.data
                        .toString());
                    print(data);
                    final List<Categories> items = (data['data'] as List).map((i) => new Categories.fromJson(i)).toList();
                    for (final item in items) {
                      print(item.category);

                      return new ListView.builder(
                        itemBuilder: (BuildContext context, int index) {
                          return new Card(
                            child: new Column(
                              crossAxisAlignment: CrossAxisAlignment.stretch,
                              children: <Widget>[
                                new Text('Service Category: ' + items[index].category),
                                new Text('Category' + items[index].categoryDesc),
                                new Text('Auto complete term' + items[index].autocompleteterm),
                                new Text('Desc' + items[index].desc)
                              ],
                            ),
                          );
                        },
                      );
                    }
                  }

    )
    )
    )
    );
  }
}

在我的目标应用程序中,添加了使用autocomplete_textfield程序包的必需代码,该程序包显示了到目前为止的静态建议列表:

@override
  Widget build(BuildContext context) {

    textField = new AutoCompleteTextField<String>
      (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: new EdgeInsets.fromLTRB(10.0, 30.0, 10.0, 20.0),
            filled: true,
            hintText: 'What Do You Need Help With ?',
            hintStyle: new TextStyle(
                color: Colors.white
            )
        ),
        submitOnSuggestionTap: true,
        clearOnSubmit: true,
        textChanged: (item){
          currentText = item;
        },
        textSubmitted: (item) {
          setState(() {
            currentText = item;
          });
        },
        key: key,
        suggestions: suggestions,
        itemBuilder: (context, item) {
          return new Padding(
              padding: EdgeInsets.all(8.0), child: new Text(item));
        },
        itemSorter: (a, b) {
          return a.compareTo(b);
        },
        itemFilter: (item, query) {
          return item.toLowerCase().startsWith(query.toLowerCase());
        });

    Column body = new Column(children: [
      new GestureDetector(
        child: new ListTile(
          title: textField,
              onTap: () {
                setState(() {
                  if (currentText != "") {
                    added.add(currentText);
                    textField.clear();
                    currentText = "";
                  }
                });
              }
              )
      )
    ]
    );

    body.children.addAll(added.map((item) {
      return new ListTile(
          title: new Text(item)
      );
    }));

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

上面的代码在UI中显示如下:

enter image description here

我现在想知道如何在目标应用程序中钩住builder函数以获取json数据,以便该下拉列表将显示json的建议,而不是静态的字符串列表(如我原始问题的屏幕截图)。

1 个答案:

答案 0 :(得分:0)

如果发现手动执行此操作过多,则实际上是颤抖的package。打包站点上也有两个示例。

请注意,这是当前程序包中的错误(我提出了一个PR来对其进行修复,但程序包所有者最近正忙于审查任何PR)。根据您的使用方式,该错误可能不会影响您。