opt: search page

This commit is contained in:
guozhigq
2024-10-19 13:29:18 +08:00
parent fa79b92f82
commit c755e8a60f
6 changed files with 138 additions and 95 deletions

View File

@ -1,10 +1,13 @@
import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:get/get_rx/src/rx_workers/utils/debouncer.dart'; import 'package:get/get_rx/src/rx_workers/utils/debouncer.dart';
import 'package:hive/hive.dart'; import 'package:hive/hive.dart';
import 'package:pilipala/http/search.dart'; import 'package:pilipala/http/search.dart';
import 'package:pilipala/models/search/hot.dart'; import 'package:pilipala/models/search/hot.dart';
import 'package:pilipala/models/search/suggest.dart'; import 'package:pilipala/models/search/suggest.dart';
import 'package:pilipala/utils/global_data_cache.dart';
import 'package:pilipala/utils/storage.dart'; import 'package:pilipala/utils/storage.dart';
class SSearchController extends GetxController { class SSearchController extends GetxController {
@ -12,7 +15,7 @@ class SSearchController extends GetxController {
RxString searchKeyWord = ''.obs; RxString searchKeyWord = ''.obs;
Rx<TextEditingController> controller = TextEditingController().obs; Rx<TextEditingController> controller = TextEditingController().obs;
RxList<HotSearchItem> hotSearchList = <HotSearchItem>[].obs; RxList<HotSearchItem> hotSearchList = <HotSearchItem>[].obs;
Box histiryWord = GStrorage.historyword; Box localCache = GStrorage.localCache;
List historyCacheList = []; List historyCacheList = [];
RxList historyList = [].obs; RxList historyList = [].obs;
RxList<SearchSuggestItem> searchSuggestList = <SearchSuggestItem>[].obs; RxList<SearchSuggestItem> searchSuggestList = <SearchSuggestItem>[].obs;
@ -22,21 +25,26 @@ class SSearchController extends GetxController {
RxString defaultSearch = ''.obs; RxString defaultSearch = ''.obs;
Box setting = GStrorage.setting; Box setting = GStrorage.setting;
bool enableHotKey = true; bool enableHotKey = true;
late StreamController<bool> clearStream = StreamController<bool>.broadcast();
@override @override
void onInit() { void onInit() {
super.onInit(); super.onInit();
// 其他页面跳转过来 // 其他页面跳转过来
if (Get.parameters.keys.isNotEmpty) { final parameters = Get.parameters;
if (Get.parameters['keyword'] != null) { if (parameters.keys.isNotEmpty) {
onClickKeyword(Get.parameters['keyword']!); final keyword = parameters['keyword'];
if (keyword != null) {
onClickKeyword(keyword);
} }
if (Get.parameters['hintText'] != null) {
hintText = Get.parameters['hintText']!; final hint = parameters['hintText'];
if (hint != null) {
hintText = hint;
searchKeyWord.value = hintText; searchKeyWord.value = hintText;
} }
} }
historyCacheList = histiryWord.get('cacheList') ?? []; historyCacheList = GlobalDataCache().historyCacheList;
historyList.value = historyCacheList; historyList.value = historyCacheList;
enableHotKey = setting.get(SettingBoxKey.enableHotKey, defaultValue: true); enableHotKey = setting.get(SettingBoxKey.enableHotKey, defaultValue: true);
} }
@ -45,8 +53,10 @@ class SSearchController extends GetxController {
searchKeyWord.value = value; searchKeyWord.value = value;
if (value == '') { if (value == '') {
searchSuggestList.value = []; searchSuggestList.value = [];
clearStream.add(false);
return; return;
} }
clearStream.add(true);
_debouncer.call(() => querySearchSuggest(value)); _debouncer.call(() => querySearchSuggest(value));
} }
@ -55,6 +65,7 @@ class SSearchController extends GetxController {
controller.value.clear(); controller.value.clear();
searchKeyWord.value = ''; searchKeyWord.value = '';
searchSuggestList.value = []; searchSuggestList.value = [];
clearStream.add(false);
} else { } else {
Get.back(); Get.back();
} }
@ -62,8 +73,7 @@ class SSearchController extends GetxController {
// 搜索 // 搜索
void submit() { void submit() {
// ignore: unrelated_type_equality_checks if (searchKeyWord.value == '') {
if (searchKeyWord == '') {
return; return;
} }
List arr = historyCacheList.where((e) => e != searchKeyWord.value).toList(); List arr = historyCacheList.where((e) => e != searchKeyWord.value).toList();
@ -73,7 +83,7 @@ class SSearchController extends GetxController {
historyList.value = historyCacheList; historyList.value = historyCacheList;
// 手动刷新 // 手动刷新
historyList.refresh(); historyList.refresh();
histiryWord.put('cacheList', historyCacheList); localCache.put('cacheList', historyCacheList);
searchFocusNode.unfocus(); searchFocusNode.unfocus();
Get.toNamed('/searchResult', parameters: {'keyword': searchKeyWord.value}); Get.toNamed('/searchResult', parameters: {'keyword': searchKeyWord.value});
} }
@ -117,13 +127,14 @@ class SSearchController extends GetxController {
int index = historyList.indexOf(word); int index = historyList.indexOf(word);
historyList.removeAt(index); historyList.removeAt(index);
historyList.refresh(); historyList.refresh();
histiryWord.put('cacheList', historyList); localCache.put('cacheList', historyList);
} }
onClearHis() { onClearHis() {
historyList.value = []; historyList.value = [];
historyCacheList = []; historyCacheList = [];
historyList.refresh(); historyList.refresh();
histiryWord.put('cacheList', []); localCache.put('cacheList', []);
SmartDialog.showToast('搜索历史已清空');
} }
} }

View File

@ -1,4 +1,3 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:pilipala/common/widgets/http_error.dart'; import 'package:pilipala/common/widgets/http_error.dart';
@ -54,7 +53,7 @@ class _SearchPageState extends State<SearchPage> with RouteAware {
actions: [ actions: [
IconButton( IconButton(
onPressed: () => _searchController.submit(), onPressed: () => _searchController.submit(),
icon: const Icon(CupertinoIcons.search, size: 22), icon: const Icon(Icons.search),
), ),
const SizedBox(width: 10) const SizedBox(width: 10)
], ],
@ -68,13 +67,19 @@ class _SearchPageState extends State<SearchPage> with RouteAware {
decoration: InputDecoration( decoration: InputDecoration(
hintText: _searchController.hintText, hintText: _searchController.hintText,
border: InputBorder.none, border: InputBorder.none,
suffixIcon: IconButton( suffixIcon: StreamBuilder(
icon: Icon( initialData: false,
Icons.clear, stream: _searchController.clearStream.stream,
size: 22, builder: (_, snapshot) {
color: Theme.of(context).colorScheme.outline, if (snapshot.data == true) {
), return IconButton(
onPressed: () => _searchController.onClear(), icon: const Icon(Icons.clear, size: 22),
onPressed: () => _searchController.onClear(),
);
} else {
return const SizedBox();
}
},
), ),
), ),
onSubmitted: (String value) => _searchController.submit(), onSubmitted: (String value) => _searchController.submit(),
@ -84,7 +89,7 @@ class _SearchPageState extends State<SearchPage> with RouteAware {
body: SingleChildScrollView( body: SingleChildScrollView(
child: Column( child: Column(
children: [ children: [
const SizedBox(height: 12), const SizedBox(height: 6),
// 搜索建议 // 搜索建议
_searchSuggest(), _searchSuggest(),
// 热搜 // 热搜
@ -135,7 +140,7 @@ class _SearchPageState extends State<SearchPage> with RouteAware {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Padding( Padding(
padding: const EdgeInsets.fromLTRB(6, 0, 6, 6), padding: const EdgeInsets.fromLTRB(6, 0, 6, 4),
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
@ -153,7 +158,7 @@ class _SearchPageState extends State<SearchPage> with RouteAware {
padding: MaterialStateProperty.all(const EdgeInsets.only( padding: MaterialStateProperty.all(const EdgeInsets.only(
left: 10, top: 6, bottom: 6, right: 10)), left: 10, top: 6, bottom: 6, right: 10)),
), ),
onPressed: () => ctr.queryHotSearchList(), onPressed: ctr.queryHotSearchList,
icon: const Icon(Icons.refresh_outlined, size: 18), icon: const Icon(Icons.refresh_outlined, size: 18),
label: const Text('刷新'), label: const Text('刷新'),
), ),
@ -199,6 +204,7 @@ class _SearchPageState extends State<SearchPage> with RouteAware {
return HotKeyword( return HotKeyword(
width: width, width: width,
hotSearchList: _searchController.hotSearchList, hotSearchList: _searchController.hotSearchList,
onClick: () {},
); );
} else { } else {
return const SizedBox(); return const SizedBox();
@ -217,13 +223,13 @@ class _SearchPageState extends State<SearchPage> with RouteAware {
return Obx( return Obx(
() => Container( () => Container(
width: double.infinity, width: double.infinity,
padding: const EdgeInsets.fromLTRB(10, 25, 6, 0), padding: const EdgeInsets.fromLTRB(10, 20, 4, 0),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
if (_searchController.historyList.isNotEmpty) if (_searchController.historyList.isNotEmpty)
Padding( Padding(
padding: const EdgeInsets.fromLTRB(6, 0, 0, 2), padding: const EdgeInsets.fromLTRB(6, 0, 6, 8),
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
@ -234,10 +240,19 @@ class _SearchPageState extends State<SearchPage> with RouteAware {
.titleMedium! .titleMedium!
.copyWith(fontWeight: FontWeight.bold), .copyWith(fontWeight: FontWeight.bold),
), ),
TextButton( SizedBox(
onPressed: () => _searchController.onClearHis(), height: 34,
child: const Text('清空'), child: TextButton.icon(
) style: ButtonStyle(
padding: MaterialStateProperty.all(
const EdgeInsets.only(
left: 10, top: 6, bottom: 6, right: 10)),
),
onPressed: _searchController.onClearHis,
icon: const Icon(Icons.clear_all_outlined, size: 18),
label: const Text('清空'),
),
),
], ],
), ),
), ),

View File

@ -1,15 +1,15 @@
// ignore: file_names
import 'package:cached_network_image/cached_network_image.dart'; import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
class HotKeyword extends StatelessWidget { class HotKeyword extends StatelessWidget {
final double? width; final double width;
final List? hotSearchList; final List hotSearchList;
final Function? onClick; final Function onClick;
const HotKeyword({ const HotKeyword({
this.width, required this.width,
this.hotSearchList, required this.hotSearchList,
this.onClick, required this.onClick,
super.key, super.key,
}); });
@ -18,45 +18,67 @@ class HotKeyword extends StatelessWidget {
return Wrap( return Wrap(
runSpacing: 0.4, runSpacing: 0.4,
spacing: 5.0, spacing: 5.0,
children: [ children: hotSearchList.map((item) {
for (var i in hotSearchList!) return HotKeywordItem(
SizedBox( width: width,
width: width! / 2 - 4, item: item,
child: Material( onClick: onClick,
borderRadius: BorderRadius.circular(3), isRightPadding: hotSearchList.indexOf(item) % 2 == 1,
clipBehavior: Clip.hardEdge, );
child: InkWell( }).toList(),
onTap: () => onClick!(i.keyword), );
child: Padding( }
padding: EdgeInsets.only( }
left: 2,
right: hotSearchList!.indexOf(i) % 2 == 1 ? 10 : 0), class HotKeywordItem extends StatelessWidget {
child: Row( final double width;
children: [ final dynamic item;
Flexible( final Function onClick;
child: Padding( final bool isRightPadding;
padding: const EdgeInsets.fromLTRB(6, 5, 4, 5),
child: Text( const HotKeywordItem({
i.keyword!, required this.width,
overflow: TextOverflow.ellipsis, required this.item,
maxLines: 1, required this.onClick,
style: const TextStyle(fontSize: 14), required this.isRightPadding,
), super.key,
), });
),
if (i.icon != null && i.icon != '') @override
SizedBox( Widget build(BuildContext context) {
height: 15, return SizedBox(
child: CachedNetworkImage( width: width / 2 - 4,
imageUrl: i.icon!, height: 15.0), child: Material(
), borderRadius: BorderRadius.circular(4),
], clipBehavior: Clip.hardEdge,
), child: InkWell(
), onTap: () => onClick.call(item.keyword),
), child: Padding(
), padding: EdgeInsets.only(left: 2, right: isRightPadding ? 10 : 0),
), child: Row(
], children: [
Flexible(
child: Padding(
padding: const EdgeInsets.fromLTRB(6, 5, 4, 5),
child: Text(
item.keyword,
overflow: TextOverflow.ellipsis,
maxLines: 1,
style: const TextStyle(fontSize: 14),
),
),
),
if (item.icon != null && item.icon != '')
SizedBox(
height: 15,
child:
CachedNetworkImage(imageUrl: item.icon!, height: 15.0),
),
],
),
),
),
),
); );
} }
} }

View File

@ -1,4 +1,5 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:pilipala/utils/feed_back.dart';
class SearchText extends StatelessWidget { class SearchText extends StatelessWidget {
final String? searchText; final String? searchText;
@ -17,30 +18,31 @@ class SearchText extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
return Material( return Material(
color: isSelect color: isSelect
? Theme.of(context).colorScheme.primaryContainer ? colorScheme.primaryContainer
: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.5), : colorScheme.surfaceVariant.withOpacity(0.5),
borderRadius: BorderRadius.circular(6), borderRadius: BorderRadius.circular(6),
child: Padding( child: Padding(
padding: EdgeInsets.zero, padding: EdgeInsets.zero,
child: InkWell( child: InkWell(
onTap: () { onTap: () {
onSelect!(searchText); onSelect?.call(searchText);
}, },
onLongPress: () { onLongPress: () {
onLongSelect!(searchText); feedBack();
onLongSelect?.call(searchText);
}, },
borderRadius: BorderRadius.circular(6), borderRadius: BorderRadius.circular(6),
child: Padding( child: Padding(
padding: padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 11),
const EdgeInsets.only(top: 5, bottom: 5, left: 11, right: 11),
child: Text( child: Text(
searchText!, searchText!,
style: TextStyle( style: TextStyle(
color: isSelect color: isSelect
? Theme.of(context).colorScheme.primary ? colorScheme.primary
: Theme.of(context).colorScheme.onSurfaceVariant, : colorScheme.onSurfaceVariant,
), ),
), ),
), ),

View File

@ -45,6 +45,8 @@ class GlobalDataCache {
late List<double> speedsList; late List<double> speedsList;
// 用户信息 // 用户信息
UserInfoData? userInfo; UserInfoData? userInfo;
// 搜索历史
late List historyCacheList;
// 私有构造函数 // 私有构造函数
GlobalDataCache._(); GlobalDataCache._();
@ -105,5 +107,6 @@ class GlobalDataCache {
userInfo = userInfoCache.get('userInfoCache'); userInfo = userInfoCache.get('userInfoCache');
sheetHeight = localCache.get('sheetHeight'); sheetHeight = localCache.get('sheetHeight');
historyCacheList = localCache.get('cacheList', defaultValue: []);
} }
} }

View File

@ -5,7 +5,6 @@ import 'package:pilipala/models/user/info.dart';
class GStrorage { class GStrorage {
static late final Box<dynamic> userInfo; static late final Box<dynamic> userInfo;
static late final Box<dynamic> historyword;
static late final Box<dynamic> localCache; static late final Box<dynamic> localCache;
static late final Box<dynamic> setting; static late final Box<dynamic> setting;
static late final Box<dynamic> video; static late final Box<dynamic> video;
@ -26,18 +25,11 @@ class GStrorage {
localCache = await Hive.openBox( localCache = await Hive.openBox(
'localCache', 'localCache',
compactionStrategy: (int entries, int deletedEntries) { compactionStrategy: (int entries, int deletedEntries) {
return deletedEntries > 4; return deletedEntries > 10;
}, },
); );
// 设置 // 设置
setting = await Hive.openBox('setting'); setting = await Hive.openBox('setting');
// 搜索历史
historyword = await Hive.openBox(
'historyWord',
compactionStrategy: (int entries, int deletedEntries) {
return deletedEntries > 10;
},
);
// 视频设置 // 视频设置
video = await Hive.openBox('video'); video = await Hive.openBox('video');
} }
@ -52,8 +44,6 @@ class GStrorage {
// user.close(); // user.close();
userInfo.compact(); userInfo.compact();
userInfo.close(); userInfo.close();
historyword.compact();
historyword.close();
localCache.compact(); localCache.compact();
localCache.close(); localCache.close();
setting.compact(); setting.compact();