首页 > 解决方案 > 如何在搜索委托上添加提示文本?

问题描述

如何在 Flutter showSearch() 上更改提示文本和提示文本颜色

 AppBar(
        backgroundColor: Colors.blue,
        centerTitle: true,
        title: appBarIcon(context),
        actions: <Widget>[
          IconButton(
              icon: Icon(Icons.search),
              onPressed: () {
                showSearch(
                    context: context,
                    delegate: CustomSearchDelegateAssets(_searchdata, widget.regId));
              })
        ],
      ),

标签: dartflutterflutter-layout

解决方案


根据方法的来源showSearch它只是推了一条新的路线—— _SearchPageRoute.

这个内部定义的路由提供了一个有状态的小部件 ( _SearchPage),它由一个新建的AppBar带有一个文本字段的小部件组成。

您需要做的是基于_SearchPageRoute返回 custom创建一个自定义路由_SearchPage。路由需要根据showSearch逻辑通过自己的方法推送。

在你的自定义中实现自定义hintText& hintStyle-修改。InputDecoration_SearchPageState


例如MySearchPageRoute

class MySearchPageRoute<T> extends PageRoute<T> {
  // ...
  @override
  Widget buildPage(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
  ) {
    return MySearchPage<T>( // KEY PROP: Custom stateful widget based on `_SearchPage`
      delegate: delegate,
      animation: animation,
    );
  }
  // ...
}

我的搜索页面:

class MySearchPage<T> extends StatefulWidget {
  // ...
  @override
  State<StatefulWidget> createState() => MySearchPageState<T>();
}
class MySearchPageState<T> extends State<MySearchPage<T>> {
  // ...
  @override
  Widget build(BuildContext context) {
    // ...
    return Semantics(
      // ...
      child: Scaffold(
        appBar: AppBar(
          // ...
          title: TextField(
            // ...
            decoration: InputDecoration(
              border: InputBorder.none,
              hintText: "My Custom Search Label", // KEY PROP
              hintStyle: TextStyle(color: Colors.red), // KEY PROP
            ),
          ),
          // ...
        ),
        // ...
      )
    );
  }
  // ...
}

推送路线:

Future<T> showMySearch<T>({
  @required BuildContext context,
  @required SearchDelegate<T> delegate,
  String query = '',
}) {
  // ...
  return Navigator.of(context).push(MySearchPageRoute<T>( // KEY PROP
    delegate: delegate,
  ));
}

换句话说 - 简单地从_SearchPageRoute文件中复制、、_SearchPage和。然后在我用 标记的行中进行更改。_SearchPageStateshowSearch // KEY PROP


推荐阅读