refactor: search page

Signed-off-by: bggRGjQaUbCoE <githubaccount56556@proton.me>
This commit is contained in:
bggRGjQaUbCoE
2024-11-23 22:05:06 +08:00
parent d8d6cf4d26
commit 44bd5afb70
8 changed files with 157 additions and 219 deletions

View File

@@ -86,7 +86,7 @@ class DynamicSliverAppBar extends StatefulWidget {
final CustomClipper<Path>? appBarClipper; final CustomClipper<Path>? appBarClipper;
@override @override
_DynamicSliverAppBarState createState() => _DynamicSliverAppBarState(); State<DynamicSliverAppBar> createState() => _DynamicSliverAppBarState();
} }
class _DynamicSliverAppBarState extends State<DynamicSliverAppBar> { class _DynamicSliverAppBarState extends State<DynamicSliverAppBar> {

View File

@@ -67,8 +67,7 @@ class NetworkImgLayer extends StatelessWidget {
child: Builder( child: Builder(
builder: (context) => CachedNetworkImage( builder: (context) => CachedNetworkImage(
imageUrl: imageUrl:
'${src?.startsWith('//') == true ? 'https:$src' : src}${thumbnail ? '@${quality ?? defaultImgQuality}q.webp' : ''}' '${src?.startsWith('//') == true ? 'https:$src' : src?.http2https}${thumbnail ? '@${quality ?? defaultImgQuality}q.webp' : ''}',
.http2https,
width: width, width: width,
height: ignoreHeight == null || ignoreHeight == false height: ignoreHeight == null || ignoreHeight == false
? height ? height

View File

@@ -33,7 +33,7 @@ class SearchHttp {
return { return {
'status': false, 'status': false,
'data': [], 'data': [],
'msg': '请求错误 🙅', 'msg': '请求错误',
}; };
} }

View File

@@ -12,7 +12,6 @@ import 'package:hive/hive.dart';
import 'package:PiliPalaX/common/widgets/custom_toast.dart'; import 'package:PiliPalaX/common/widgets/custom_toast.dart';
import 'package:PiliPalaX/http/init.dart'; import 'package:PiliPalaX/http/init.dart';
import 'package:PiliPalaX/models/common/color_type.dart'; import 'package:PiliPalaX/models/common/color_type.dart';
import 'package:PiliPalaX/pages/search/index.dart';
import 'package:PiliPalaX/pages/video/detail/index.dart'; import 'package:PiliPalaX/pages/video/detail/index.dart';
import 'package:PiliPalaX/router/app_pages.dart'; import 'package:PiliPalaX/router/app_pages.dart';
import 'package:PiliPalaX/pages/main/view.dart'; import 'package:PiliPalaX/pages/main/view.dart';
@@ -190,7 +189,6 @@ class MyApp extends StatelessWidget {
}, },
navigatorObservers: [ navigatorObservers: [
VideoDetailPage.routeObserver, VideoDetailPage.routeObserver,
SearchPage.routeObserver,
MainApp.routeObserver, MainApp.routeObserver,
], ],
); );

View File

@@ -214,6 +214,7 @@ class _EditProfilePageState extends State<EditProfilePage> {
'https://account.bilibili.com/official/mobile/home'), 'https://account.bilibili.com/official/mobile/home'),
), ),
_divider, _divider,
SizedBox(height: 25 + MediaQuery.paddingOf(context).bottom),
], ],
), ),
), ),

View File

@@ -1,27 +1,23 @@
import 'package:PiliPalaX/http/loading_state.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:get/get_rx/src/rx_workers/utils/debouncer.dart';
import 'package:hive/hive.dart';
import 'package:PiliPalaX/http/search.dart'; import 'package:PiliPalaX/http/search.dart';
import 'package:PiliPalaX/models/search/hot.dart';
import 'package:PiliPalaX/models/search/suggest.dart'; import 'package:PiliPalaX/models/search/suggest.dart';
import 'package:PiliPalaX/utils/storage.dart'; import 'package:PiliPalaX/utils/storage.dart';
class SSearchController extends GetxController { class SSearchController extends GetxController {
final FocusNode searchFocusNode = FocusNode(); final searchFocusNode = FocusNode();
RxString searchKeyWord = ''.obs; final controller = TextEditingController();
Rx<TextEditingController> controller = TextEditingController().obs;
RxList<HotSearchItem> hotSearchList = <HotSearchItem>[].obs;
Box historyWord = GStorage.historyWord;
List<String> historyCacheList = [];
RxList<String> historyList = <String>[].obs; RxList<String> historyList = <String>[].obs;
RxList<SearchSuggestItem> searchSuggestList = <SearchSuggestItem>[].obs; RxList<SearchSuggestItem> searchSuggestList = <SearchSuggestItem>[].obs;
final _debouncer =
Debouncer(delay: const Duration(milliseconds: 200)); // 设置延迟时间
String hintText = '搜索'; String hintText = '搜索';
RxString defaultSearch = ''.obs;
Box setting = GStorage.setting; late bool enableHotKey;
bool enableHotKey = true;
Rx<LoadingState> loadingState = LoadingState.loading().obs;
@override @override
void onInit() { void onInit() {
@@ -33,28 +29,31 @@ class SSearchController extends GetxController {
} }
if (Get.parameters['hintText'] != null) { if (Get.parameters['hintText'] != null) {
hintText = Get.parameters['hintText']!; hintText = Get.parameters['hintText']!;
searchKeyWord.value = hintText;
} }
} }
historyCacheList = List<String>.from(historyWord.get('cacheList') ?? []);
historyList.value = historyCacheList; historyList.value = List.from(GStorage.historyWord.get('cacheList') ?? []);
enableHotKey = setting.get(SettingBoxKey.enableHotKey, defaultValue: true);
enableHotKey =
GStorage.setting.get(SettingBoxKey.enableHotKey, defaultValue: true);
if (enableHotKey) {
queryHotSearchList();
}
} }
void onChange(value) { void onChange(String value) {
searchKeyWord.value = value; if (value.isEmpty) {
if (value == '') { searchSuggestList.clear();
searchSuggestList.value = []; } else {
return; querySearchSuggest(value);
} }
_debouncer.call(() => querySearchSuggest(value));
} }
void onClear() { void onClear() {
if (searchKeyWord.value.isNotEmpty && controller.value.text != '') { if (controller.value.text != '') {
controller.value.clear(); controller.clear();
searchKeyWord.value = ''; searchSuggestList.clear();
searchSuggestList.value = [];
searchFocusNode.requestFocus(); searchFocusNode.requestFocus();
} else { } else {
Get.back(); Get.back();
@@ -62,44 +61,38 @@ class SSearchController extends GetxController {
} }
// 搜索 // 搜索
void submit() { void submit() async {
// ignore: unrelated_type_equality_checks if (controller.text.isEmpty) {
if (searchKeyWord == '') { if (hintText.isEmpty) {
if (hintText == '') {
return; return;
} }
searchKeyWord.value = hintText; controller.text = hintText;
} }
List<String> arr =
historyCacheList.where((e) => e != searchKeyWord.value).toList();
arr.insert(0, searchKeyWord.value);
historyCacheList = arr;
historyList.value = historyCacheList; historyList.remove(controller.text);
// 手动刷新 historyList.insert(0, controller.text);
historyList.refresh(); GStorage.historyWord.put('cacheList', historyList);
historyWord.put('cacheList', historyCacheList);
searchFocusNode.unfocus(); searchFocusNode.unfocus();
Get.toNamed('/searchResult', parameters: {'keyword': searchKeyWord.value});
await Get.toNamed('/searchResult', parameters: {
'keyword': controller.text,
});
searchFocusNode.requestFocus();
} }
// 获取热搜关键词 // 获取热搜关键词
Future queryHotSearchList() async { Future queryHotSearchList() async {
var result = await SearchHttp.hotSearchList(); dynamic result = await SearchHttp.hotSearchList();
if (result['status']) { if (result['status']) {
hotSearchList.value = result['data'].list; loadingState.value = LoadingState.success(result['data'].list);
} else {
loadingState.value = LoadingState.error(result['msg']);
} }
return result;
} }
// 点击热搜关键词
void onClickKeyword(String keyword) { void onClickKeyword(String keyword) {
searchKeyWord.value = keyword; controller.text = keyword;
controller.value.text = keyword; searchSuggestList.clear();
// 移动光标
controller.value.selection = TextSelection.fromPosition(
TextPosition(offset: controller.value.text.length),
);
submit(); submit();
} }
@@ -112,28 +105,20 @@ class SSearchController extends GetxController {
} }
} }
onSelect(word) {
searchKeyWord.value = word;
controller.value.text = word;
submit();
}
onLongSelect(word) { onLongSelect(word) {
int index = historyList.indexOf(word); historyList.remove(word);
historyList.removeAt(index); GStorage.historyWord.put('cacheList', historyList);
historyWord.put('cacheList', historyList);
} }
onClearHis() { onClearHistory() {
historyList.value = []; historyList.clear();
historyCacheList = []; GStorage.historyWord.put('cacheList', []);
historyList.refresh();
historyWord.put('cacheList', []);
} }
@override @override
void onClose() { void onClose() {
searchFocusNode.dispose(); searchFocusNode.dispose();
controller.dispose();
super.onClose(); super.onClose();
} }
} }

View File

@@ -1,6 +1,7 @@
import 'package:PiliPalaX/common/widgets/loading_widget.dart';
import 'package:PiliPalaX/http/loading_state.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:PiliPalaX/common/widgets/http_error.dart';
import 'controller.dart'; import 'controller.dart';
import 'widgets/hot_keyword.dart'; import 'widgets/hot_keyword.dart';
import 'widgets/search_text.dart'; import 'widgets/search_text.dart';
@@ -10,39 +11,10 @@ class SearchPage extends StatefulWidget {
@override @override
State<SearchPage> createState() => _SearchPageState(); State<SearchPage> createState() => _SearchPageState();
static final RouteObserver<PageRoute> routeObserver =
RouteObserver<PageRoute>();
} }
class _SearchPageState extends State<SearchPage> with RouteAware { class _SearchPageState extends State<SearchPage> with RouteAware {
final SSearchController _searchController = Get.put(SSearchController()); final SSearchController _searchController = Get.put(SSearchController());
late Future? _futureBuilderFuture;
@override
void initState() {
super.initState();
_futureBuilderFuture = _searchController.queryHotSearchList();
}
@override
void dispose() {
SearchPage.routeObserver.unsubscribe(this);
super.dispose();
}
@override
// 返回当前页面时
void didPopNext() async {
_searchController.searchFocusNode.requestFocus();
super.didPopNext();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
SearchPage.routeObserver
.subscribe(this, ModalRoute.of(context) as PageRoute);
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -63,38 +35,33 @@ class _SearchPageState extends State<SearchPage> with RouteAware {
), ),
const SizedBox(width: 10) const SizedBox(width: 10)
], ],
title: Obx( title: TextField(
() => TextField( autofocus: true,
autofocus: true, focusNode: _searchController.searchFocusNode,
focusNode: _searchController.searchFocusNode, controller: _searchController.controller,
controller: _searchController.controller.value, textInputAction: TextInputAction.search,
textInputAction: TextInputAction.search, onChanged: _searchController.onChange,
onChanged: (value) => _searchController.onChange(value), textAlignVertical: TextAlignVertical.center,
textAlignVertical: TextAlignVertical.center, decoration: InputDecoration(
decoration: InputDecoration( hintText: _searchController.hintText,
hintText: _searchController.hintText, border: InputBorder.none,
border: InputBorder.none, suffixIcon: IconButton(
suffixIcon: IconButton( tooltip: '清空',
tooltip: '清空', icon: const Icon(Icons.clear, size: 22),
icon: const Icon(Icons.clear, size: 22), onPressed: _searchController.onClear,
onPressed: () => _searchController.onClear(),
),
), ),
onSubmitted: (String value) => _searchController.submit(),
), ),
onSubmitted: (value) => _searchController.submit(),
), ),
), ),
body: SingleChildScrollView( body: SingleChildScrollView(
child: Column( child: Column(
children: [ children: [
const SizedBox(height: 12),
// 搜索建议 // 搜索建议
_searchSuggest(), _searchSuggest(),
// 热搜 if (_searchController.enableHotKey)
Visibility( // 热搜
visible: _searchController.enableHotKey, hotSearch(),
child: hotSearch(_searchController),
),
// 搜索历史 // 搜索历史
_history() _history()
], ],
@@ -107,32 +74,37 @@ class _SearchPageState extends State<SearchPage> with RouteAware {
return Obx( return Obx(
() => _searchController.searchSuggestList.isNotEmpty && () => _searchController.searchSuggestList.isNotEmpty &&
_searchController.searchSuggestList.first.term != null && _searchController.searchSuggestList.first.term != null &&
_searchController.controller.value.text != '' _searchController.controller.text != ''
? ListView.builder( ? Column(
physics: const NeverScrollableScrollPhysics(), mainAxisSize: MainAxisSize.min,
shrinkWrap: true, crossAxisAlignment: CrossAxisAlignment.start,
itemCount: _searchController.searchSuggestList.length, children: _searchController.searchSuggestList
itemBuilder: (context, index) { .map(
return InkWell( (item) => InkWell(
customBorder: RoundedRectangleBorder( customBorder: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4), borderRadius: BorderRadius.circular(4),
), ),
onTap: () => _searchController.onClickKeyword( onTap: () => _searchController.onClickKeyword(item.term!),
_searchController.searchSuggestList[index].term!), child: Container(
child: Padding( width: double.infinity,
padding: const EdgeInsets.only(left: 20, top: 9, bottom: 9), padding: const EdgeInsets.only(
child: _searchController.searchSuggestList[index].textRich, left: 20,
), top: 9,
); bottom: 9,
}, ),
child: item.textRich,
),
),
)
.toList(),
) )
: const SizedBox(), : const SizedBox.shrink(),
); );
} }
Widget hotSearch(ctr) { Widget hotSearch() {
return Padding( return Padding(
padding: const EdgeInsets.fromLTRB(10, 14, 4, 0), padding: const EdgeInsets.fromLTRB(10, 25, 4, 25),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
@@ -152,10 +124,12 @@ class _SearchPageState extends State<SearchPage> with RouteAware {
height: 34, height: 34,
child: TextButton.icon( child: TextButton.icon(
style: ButtonStyle( style: ButtonStyle(
padding: WidgetStateProperty.all(const EdgeInsets.only( padding: WidgetStateProperty.all(
left: 10, top: 6, bottom: 6, right: 10)), const EdgeInsets.only(
left: 10, top: 6, bottom: 6, right: 10),
),
), ),
onPressed: () => ctr.queryHotSearchList(), onPressed: _searchController.queryHotSearchList,
icon: const Icon(Icons.refresh_outlined, size: 18), icon: const Icon(Icons.refresh_outlined, size: 18),
label: const Text('刷新'), label: const Text('刷新'),
), ),
@@ -163,60 +137,7 @@ class _SearchPageState extends State<SearchPage> with RouteAware {
], ],
), ),
), ),
LayoutBuilder( Obx(() => _buildHotKey(_searchController.loadingState.value)),
builder: (context, boxConstraints) {
final double width = boxConstraints.maxWidth;
return FutureBuilder(
future: _futureBuilderFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.data == null) {
return const SizedBox();
}
Map data = snapshot.data as Map;
if (data['status']) {
return Obx(
() => HotKeyword(
width: width,
// ignore: invalid_use_of_protected_member
hotSearchList: _searchController.hotSearchList.value,
onClick: (keyword) async {
_searchController.searchFocusNode.unfocus();
await Future.delayed(
const Duration(milliseconds: 150));
_searchController.onClickKeyword(keyword);
},
),
);
} else {
return CustomScrollView(
shrinkWrap: true,
slivers: [
HttpError(
errMsg: data['msg'],
callback: () => setState(() {
_futureBuilderFuture =
_searchController.queryHotSearchList();
}),
),
],
);
}
} else {
// 缓存数据
if (_searchController.hotSearchList.isNotEmpty) {
return HotKeyword(
width: width,
hotSearchList: _searchController.hotSearchList,
);
} else {
return const SizedBox();
}
}
},
);
},
),
], ],
), ),
); );
@@ -227,13 +148,17 @@ class _SearchPageState extends State<SearchPage> with RouteAware {
() => Container( () => Container(
width: double.infinity, width: double.infinity,
padding: EdgeInsets.fromLTRB( padding: EdgeInsets.fromLTRB(
10, 25, 6, MediaQuery.of(context).padding.bottom + 50), 10,
_searchController.enableHotKey ? 0 : 6,
6,
MediaQuery.of(context).padding.bottom + 50,
),
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, 6),
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
@@ -244,9 +169,23 @@ 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: WidgetStateProperty.all(
const EdgeInsets.only(
left: 10,
top: 6,
bottom: 6,
right: 10,
),
),
),
onPressed: _searchController.onClearHistory,
icon: const Icon(Icons.clear_all_outlined, size: 18),
label: const Text('清空'),
),
) )
], ],
), ),
@@ -257,16 +196,15 @@ class _SearchPageState extends State<SearchPage> with RouteAware {
runSpacing: 8, runSpacing: 8,
direction: Axis.horizontal, direction: Axis.horizontal,
textDirection: TextDirection.ltr, textDirection: TextDirection.ltr,
children: [ children: _searchController.historyList
for (int i = 0; i < _searchController.historyList.length; i++) .map(
SearchText( (item) => SearchText(
searchText: _searchController.historyList[i], searchText: item,
searchTextIdx: i, onSelect: _searchController.onClickKeyword,
onSelect: (value) => _searchController.onSelect(value), onLongSelect: _searchController.onLongSelect,
onLongSelect: (value) => ),
_searchController.onLongSelect(value),
) )
], .toList(),
), ),
), ),
], ],
@@ -274,4 +212,23 @@ class _SearchPageState extends State<SearchPage> with RouteAware {
), ),
); );
} }
Widget _buildHotKey(LoadingState loadingState) {
return switch (loadingState) {
Success() => (loadingState.response as List?)?.isNotEmpty == true
? LayoutBuilder(
builder: (_, constraints) => HotKeyword(
width: constraints.maxWidth,
hotSearchList: loadingState.response,
onClick: _searchController.onClickKeyword,
),
)
: const SizedBox.shrink(),
Error() => errorWidget(
errMsg: loadingState.errMsg,
callback: _searchController.queryHotSearchList,
),
_ => const SizedBox.shrink(),
};
}
} }

View File

@@ -3,7 +3,6 @@ import 'package:flutter/material.dart';
class SearchText extends StatelessWidget { class SearchText extends StatelessWidget {
final String? searchText; final String? searchText;
final Function? onSelect; final Function? onSelect;
final int? searchTextIdx;
final Function? onLongSelect; final Function? onLongSelect;
final double? fontSize; final double? fontSize;
final Color? bgColor; final Color? bgColor;
@@ -13,7 +12,6 @@ class SearchText extends StatelessWidget {
super.key, super.key,
this.searchText, this.searchText,
this.onSelect, this.onSelect,
this.searchTextIdx,
this.onLongSelect, this.onLongSelect,
this.fontSize, this.fontSize,
this.bgColor, this.bgColor,