Flutter 将搜索数据传递给 SearchDelegate

Wai*_*aly 3 api parameters search list flutter

我创建了带有标签的产品,因此当用户按下标签按钮时,它将打开 SearchDelegate 并搜索该标签,

那么如何将标签名称传递给 Search Delegate查询呢?

我的代码:

class DataSearch extends SearchDelegate<Product> {
  final suggestions = new ProductsRepository().fetchAllProducts();
  final lastOnes = ['suggest'];

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(icon: Icon(Icons.clear), onPressed: () {
        query = '';
        showSuggestions(context);
      }),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
        icon: AnimatedIcon(
          icon: AnimatedIcons.menu_arrow,
          progress: transitionAnimation,
        ),
        onPressed: () {
          close(context, null);
        });
  }

  @override
  Widget buildResults(BuildContext context) {
    final suggestionList = query.isEmpty
        ? []
        : suggestions.where((p) => p.title.contains(query)).toList();
    double _gridSize =
        MediaQuery.of(context).size.height * 0.58; //88% of screen
    double childAspectRatio = MediaQuery.of(context).size.width /
        (MediaQuery.of(context).size.height / 1.0);

    return Column(children: <Widget>[
      new Container(
          height: _gridSize + 100,
          decoration: BoxDecoration(
            color: const Color(0xFFeeeeee),),
          padding: EdgeInsets.only(left: 10, right: 10),
          child: new Column(children: <Widget>[
            new Container(
                margin: EdgeInsets.only(top: 40),
                child: new Column(children: <Widget>[
                  new Container(
                      height: _gridSize - 60,
                      margin: EdgeInsets.only(top: 0),
                      child: new PhysicalModel(
                          color: Colors.transparent,
                          borderRadius: BorderRadius.only(
                              bottomLeft: Radius.circular(_gridSize / 10 - 10),
                              bottomRight:
                              Radius.circular(_gridSize / 10 - 10)),
                          clipBehavior: Clip.antiAlias,
                          child: GridView.builder(
                              itemCount: suggestionList.length,
                              gridDelegate:
                              new SliverGridDelegateWithFixedCrossAxisCount(
                                  crossAxisCount: 2,
                                  childAspectRatio: childAspectRatio),
                              itemBuilder: (BuildContext context, int index) {
                                return new Padding(
                                    padding: EdgeInsets.only(
                                        top: index % 2 == 0 ? 20 : 0,
                                        right: index % 2 == 0 ? 5 : 0,
                                        left: index % 2 == 1 ? 5 : 0,
                                        bottom: index % 2 == 1 ? 20 : 0),
                                    child:
                                    ProductWidget(
                                        product: suggestionList[index]));
                              })

                      )),

                ]))
          ])),
//      new MinimalCart(_gridSize)
    ]);
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    final suggestionList = query.isEmpty
        ? []
        : suggestions.where((p) => p.title.contains(query)).toList();
    return ListView.builder(
      itemBuilder: (context, index) =>
          ListTile(
            leading: Icon(Icons.add),
            onTap: () => showResults(context),
            title: RichText(
                text: TextSpan(
                    text: suggestionList[index].title.substring(
                        0, query.length),
                    style: TextStyle(
                        color: Colors.black, fontWeight: FontWeight.bold),
                    children: [
                      TextSpan(
                          text: suggestionList[index].title.substring(
                              query.length),
                          style: TextStyle(
                              color: Colors.grey))
                    ])),
          ),
      itemCount: suggestionList.length,
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我的标签按钮:

 child: FlatButton(
     child: Text(widget.product.tags[index]),
     onPressed: () {
            showSearch(
              context: context,
              delegate: DataSearch(),
         );

       })
Run Code Online (Sandbox Code Playgroud)

我试图传递查询变量但它不起作用,因为查询在小部件内,还有其他方法可以做到吗?

Sha*_*hra 6

您可以DataSearch使用参数q作为字符串和最终的构造函数。然后设置this.q为您想要的查询。在按钮中,DataSearch使用产品标签作为参数进行初始化。

试试这个代码并告诉我它是否有效。

class DataSearch extends SearchDelegate<Product> {
  final suggestions = new ProductsRepository().fetchAllProducts();
  final lastOnes = ['suggest'];

  final String q;

  DataSearch(this.q) {
       query = this.q;
  }

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(icon: Icon(Icons.clear), onPressed: () {
        query = '';
        showSuggestions(context);
      }),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
        icon: AnimatedIcon(
          icon: AnimatedIcons.menu_arrow,
          progress: transitionAnimation,
        ),
        onPressed: () {
          close(context, null);
        });
  }

  @override
  Widget buildResults(BuildContext context) {
    final suggestionList = query.isEmpty
        ? []
        : suggestions.where((p) => p.title.contains(query)).toList();
    double _gridSize =
        MediaQuery.of(context).size.height * 0.58; //88% of screen
    double childAspectRatio = MediaQuery.of(context).size.width /
        (MediaQuery.of(context).size.height / 1.0);

    return Column(children: <Widget>[
      new Container(
          height: _gridSize + 100,
          decoration: BoxDecoration(
            color: const Color(0xFFeeeeee),),
          padding: EdgeInsets.only(left: 10, right: 10),
          child: new Column(children: <Widget>[
            new Container(
                margin: EdgeInsets.only(top: 40),
                child: new Column(children: <Widget>[
                  new Container(
                      height: _gridSize - 60,
                      margin: EdgeInsets.only(top: 0),
                      child: new PhysicalModel(
                          color: Colors.transparent,
                          borderRadius: BorderRadius.only(
                              bottomLeft: Radius.circular(_gridSize / 10 - 10),
                              bottomRight:
                              Radius.circular(_gridSize / 10 - 10)),
                          clipBehavior: Clip.antiAlias,
                          child: GridView.builder(
                              itemCount: suggestionList.length,
                              gridDelegate:
                              new SliverGridDelegateWithFixedCrossAxisCount(
                                  crossAxisCount: 2,
                                  childAspectRatio: childAspectRatio),
                              itemBuilder: (BuildContext context, int index) {
                                return new Padding(
                                    padding: EdgeInsets.only(
                                        top: index % 2 == 0 ? 20 : 0,
                                        right: index % 2 == 0 ? 5 : 0,
                                        left: index % 2 == 1 ? 5 : 0,
                                        bottom: index % 2 == 1 ? 20 : 0),
                                    child:
                                    ProductWidget(
                                        product: suggestionList[index]));
                              })

                      )),

                ]))
          ])),
//      new MinimalCart(_gridSize)
    ]);
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    final suggestionList = query.isEmpty
        ? []
        : suggestions.where((p) => p.title.contains(query)).toList();
    return ListView.builder(
      itemBuilder: (context, index) =>
          ListTile(
            leading: Icon(Icons.add),
            onTap: () => showResults(context),
            title: RichText(
                text: TextSpan(
                    text: suggestionList[index].title.substring(
                        0, query.length),
                    style: TextStyle(
                        color: Colors.black, fontWeight: FontWeight.bold),
                    children: [
                      TextSpan(
                          text: suggestionList[index].title.substring(
                              query.length),
                          style: TextStyle(
                              color: Colors.grey))
                    ])),
          ),
      itemCount: suggestionList.length,
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

还有你的按钮

child: FlatButton(
     child: Text(widget.product.tags[index]),
     onPressed: () {
            showSearch(
              context: context,
              delegate: DataSearch(widget.product.tags[index]),
         );

       })
Run Code Online (Sandbox Code Playgroud)