Я делаю обычный поиск по названию из JSON. Проблема в том, что вроде все работает (по крайне мере, у меня нет ошибок в стэктрэйсе), но я просто не могу понять, почему не работает поиск (принтом вывожу, отрабатывает весь виджет _serachBar, но поиск по названию не начинается). Я сначала решил, что нужно использовать Future внутри виджета поиска, но это тоже не дало результатов. Может ли кто-нибудь указать мне, что именно происходит не так? Может, мне тоже нужно создать массив для добавления результатов поиска? Так как поиск элемента у меня завязан на алгоритме сортировки, то я не могу просто взять одну модель классам Routes и по ней проводить поиск:
Сейчас вся страница выглядит вот так:
class MarshrutesPage extends StatefulWidget {
final int ttId;
MarshrutesPage({this.ttId});
@override
_MarshrutesPageState createState() => _MarshrutesPageState();
}
class _MarshrutesPageState extends State<MarshrutesPage> {
Box<RouteWithStops> favoriteRoutesBox;
TransportService service = getIt<TransportService>();
@override
void initState() {
super.initState();
favoriteRoutesBox = Hive.box(favoritesBox);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: [
IconButton(
icon: Icon(
Icons.favorite,
color: Colors.white,
),
onPressed: () {
Navigator.pushNamed(context, 'favorite');
},
),
],
elevation: 0.0,
backgroundColor: Colors.green,
title: Text(
'Название',
style: GoogleFonts.montserrat(
color: Colors.white, fontWeight: FontWeight.w400),
),
),
body: FutureBuilder(
future: service.getMarshrutWithStops(widget.ttId),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
List<RouteWithStops> routes = snapshot.data;
print(routes?.toString());
return (routes == null)
? Center(child: CircularProgressIndicator())
: ValueListenableBuilder(
valueListenable: favoriteRoutesBox.listenable(),
builder: (BuildContext context, value, Widget child) {
return ListView.builder(
itemCount: routes.length + 1,
itemBuilder: (context, index) {
return index == 0
? _searchBar(routes)
: _listItem(index - 1, routes);
},
);
},
);
}),
bottomNavigationBar: BottomAppBar(
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
IconButton(
icon: Icon(
Icons.message,
color: Colors.grey,
),
onPressed: () async {
await launch("mailto: @gmail.com");
}),
IconButton(
icon: Icon(Icons.home, color: Colors.grey), onPressed: () {}),
IconButton(
icon: Icon(Icons.notifications, color: Colors.grey),
onPressed: () {}),
IconButton(
icon: Icon(Icons.map, color: Colors.grey), onPressed: () {}),
]),
),
);
}
Widget getIcon(int index) {
if (favoriteRoutesBox.containsKey(index)) {
return Icon(Icons.favorite, color: Colors.red);
}
return Icon(Icons.favorite_border);
}
void onFavoritePress(int index, List<RouteWithStops> routes) {
if (favoriteRoutesBox.containsKey(index)) {
favoriteRoutesBox.delete(index);
return;
}
favoriteRoutesBox.put(index, routes[index]);
}
_listItem(index, List<RouteWithStops> routes) {
return ListTile(
title: Text(routes[index].route.mrTitle),
leading: Text(
routes[index].route.mrNum,
style: TextStyle(color: Colors.green, fontSize: 20),
),
trailing: IconButton(
icon: getIcon(index),
onPressed: () => onFavoritePress(index, routes),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StopsPage(
routeWithStops: routes[index],
)));
},
);
}
_searchBar(List<RouteWithStops> routes) {
return Padding(
padding: const EdgeInsets.all(8),
child: TextField(
decoration: InputDecoration(
hintText: 'Search',
hoverColor: Colors.green,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
prefixIcon: Icon(Icons.search),
),
onChanged: (text) {
text = text.toLowerCase();
setState(() {
routes = routes.where((element) {
var routesTitle = element.route.mrTitle.toLowerCase();
return routesTitle.contains(text);
}).toList();
print('test2');
});
},
),
);
}
}
Все прекрасно отрисовывается: то есть все виджеты отрабатывают (_listItem и _serachBar), http-запросы срабатывают и алгоритм тоже срабатывает, но поиск почему-то не работает.
Сам алгоритм:
Future<List<RouteWithStops>> getMarshrutWithStops(int ttId) async {
if (routesbyTransportType.isEmpty) {
await fetchTransportWithRoutes();
}
List<Routes> routes = routesbyTransportType[ttId].routes;
List<ScheduleVariants> variants = [];
variants.addAll(await api.fetchSchedule());
List<RouteWithStops> routesWithStops = [];
for (Routes route in routes) {
final routeWithStops = RouteWithStops();
routesWithStops.add(routeWithStops);
routeWithStops.route = route;
routeWithStops.variant =
variants.where((variant) => variant.mrId == route.mrId).first;
}
return routesWithStops;
}
Я также видел решение, где в initState помещают запрос и получается примерно вот такой код:
List<Post> posts = [];
initState(){
setState(){
getPosts.then(value)){
posts.addAll(value);
}
}
}
И дальше уже не нужно прописывать FutureBuilder в основном виджете, а просто использовать posts по всему древу виджетов, просто объявив его в самом верху, но у меня все приложение завязано на алгоритме и я пробовал такой способ, но ничего не отрабатывало.
Я идиот, я понял, в чем ошибка: я в _searchBar передаю List<RouteWithStops> routes
, то есть когда я пытаюсь искать по названиям, мне просто выгружает полностью весь список, какой есть внутри этого массива данных, а самого поиска по названию не происходит. Но как это исправить? По сути я не должен передавать в этот виджет никаких массивов, но если я объявляю новый массив вверху всего древа виджетов, то либо приложение полностью крашнеться, либо опять не работает поиск. Проблема в том, что я жестко завязан на этом алгоритме.