如何修改Flutter SearchDelegate中的光标颜色?
解决Flutter SearchDelegate光标颜色修改问题
直接在SearchDelegate的appBarTheme方法里修改TextSelectionThemeData就能搞定,你之前没生效是因为光标颜色不在appBarTheme的直接属性里,而是归textSelectionTheme管。
具体实现代码:
class CustomSearchDelegate extends SearchDelegate { @override ThemeData appBarTheme(BuildContext context) { // 获取当前主题,避免完全替换导致其他样式丢失 final originalTheme = super.appBarTheme(context); return originalTheme.copyWith( // 设置光标颜色为黑色 textSelectionTheme: const TextSelectionThemeData( cursorColor: Colors.black, ), // 顺便确认搜索栏背景(如果需要) appBarTheme: originalTheme.appBarTheme.copyWith( backgroundColor: Colors.white, ), ); } @override Widget buildResults(BuildContext context) { // 这里返回你的搜索结果UI return const Center(child: Text("搜索结果")); } @override Widget buildSuggestions(BuildContext context) { // 这里返回搜索建议UI return const Center(child: Text("搜索建议")); } }
调用的时候正常用showSearch就行:
showSearch(context: context, delegate: CustomSearchDelegate());
原理是SearchDelegate的搜索输入框会继承appBarTheme方法返回的主题配置,其中textSelectionTheme专门控制光标、选中文本的样式,所以修改这里的cursorColor就能直接生效。
内容的提问来源于stack exchange,提问作者Bala_proglint
相关产品推荐
相关产品推荐

