From 255454721586f17e65d5c359e15b5c54976ea60c Mon Sep 17 00:00:00 2001 From: Julian Mutter Date: Wed, 30 Apr 2025 13:05:15 +0200 Subject: [PATCH] search: add timer to search only after 0.5s inactivity --- lib/sheet.dart | 44 ++++++++++++++++++++++++++++++-------------- 1 file changed, 30 insertions(+), 14 deletions(-) diff --git a/lib/sheet.dart b/lib/sheet.dart index 4448d3d..b0a9711 100644 --- a/lib/sheet.dart +++ b/lib/sheet.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; class Sheet { @@ -37,33 +39,46 @@ class SheetsWidget extends StatefulWidget { class _SheetsWidgetState extends State { late List filteredSheets; final TextEditingController _searchController = TextEditingController(); + Timer? _debounce; @override void initState() { super.initState(); filteredSheets = widget.sheets; - _searchController.addListener(_filterSheets); + _searchController.addListener(_onSearchChanged); } @override void dispose() { + _searchController.removeListener(_onSearchChanged); _searchController.dispose(); + _debounce?.cancel(); super.dispose(); } + void _onSearchChanged() { + if (_debounce?.isActive ?? false) _debounce!.cancel(); + + _debounce = Timer(const Duration(milliseconds: 500), () { + _filterSheets(); + }); + } + void _filterSheets() { setState(() { String query = _searchController.text.toLowerCase().trim(); List terms = query.split(RegExp(r'\s+')); // Split by whitespace - filteredSheets = widget.sheets.where((sheet) { - String name = sheet.name.toLowerCase(); - String composer = sheet.composerName.toLowerCase(); + filteredSheets = + widget.sheets.where((sheet) { + String name = sheet.name.toLowerCase(); + String composer = sheet.composerName.toLowerCase(); - // Each term must be found in either the name or composer - return terms - .every((term) => name.contains(term) || composer.contains(term)); - }).toList(); + // Each term must be found in either the name or composer + return terms.every( + (term) => name.contains(term) || composer.contains(term), + ); + }).toList(); }); } @@ -82,12 +97,13 @@ class _SheetsWidgetState extends State { decoration: InputDecoration( hintText: 'Search...', prefixIcon: const Icon(Icons.search), - suffixIcon: _searchController.text.isNotEmpty - ? IconButton( - icon: const Icon(Icons.clear), - onPressed: _clearSearch, - ) - : null, + suffixIcon: + _searchController.text.isNotEmpty + ? IconButton( + icon: const Icon(Icons.clear), + onPressed: _clearSearch, + ) + : null, border: OutlineInputBorder( borderRadius: BorderRadius.circular(8.0), ),