0

Я делаю обычный поиск по названию из 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, то есть когда я пытаюсь искать по названиям, мне просто выгружает полностью весь список, какой есть внутри этого массива данных, а самого поиска по названию не происходит. Но как это исправить? По сути я не должен передавать в этот виджет никаких массивов, но если я объявляю новый массив вверху всего древа виджетов, то либо приложение полностью крашнеться, либо опять не работает поиск. Проблема в том, что я жестко завязан на этом алгоритме.

1
  • Не могли бы вы минимальный пример на DartPad выложить?
    – nazarpunk
    21 сен 2021 в 19:13

1 ответ 1

1

Проблема решалась довольно просто, нужно было просто быть чуть внимательнее: в общем, нужно объявить наверху в самом древе виджетов два массива:

 List<RouteWithStops> _routes = [];
 List<RouteWithStops> _routesToDisplay = [];

Первый массив отвечает за все элементы списка, которые необходимо вывести под строкой поиска. Второй массив нужен, чтобы когда вы настроили поиск и ввели туда определенное название/значение, то оно не провисало в воздухе, а подгружало новое. Например, вы ищете название по автору: Толстой Л.Н. "Война и мир". Если вы оставите как есть, не добавляя второй массив, то у вас так и повиснет Толстой Л.Н. "Война и мир" до следующей перезагрузки. Так быть не должно.

Чтобы избежать этого надо сделать следующее:

 @override
  void initState() {
    service.getMarshrutWithStops(widget.ttId).then((value) {
      setState(() {
        _routes.addAll(value);
        _routesToDisplay = _routes;
      });
    });
    super.initState();
  }

В пустой второй массив записываются данные из первого массива, таким образом поиск становится, так скажем, динамическим и теперь отображаются все книги автора и при стирании фамилии автора из поиска загружается остальной массив, а не висит только то, что было набрано в поиске.

В древе виджетов делаем все то же самое, что и у меня в вопросе, только с той разницей, что в _listItem мы передаем только index и ничего более, а чтобы загрузка происходила корректно нужно просто в главном виджете перед ListView.builder добавить загрузку, используя тернарные операторы:

 body:  (_routes == null) ? CircularProgressIndicator() : ValueListenableBuilder(
        builder: (BuildContext context, value, Widget child) {  
        return ListView.builder(
                          itemCount: _routesToDisplay.length + 1,
                          itemBuilder: (context, index) {
                            return index == 0
                                ? _searchBar()
                                : _listItem(index-1);
                          },
                        );

P.S Тут не нужен ValueListenableBuilder, это я начал делать сохранение в БД выбранных элементов, для загрузки нужна только эта строчка: (_routes == null) ? CircularProgressIndicator() : ListView.builder

Также в виджетах для отображения списка и поиска вместо _routes добавляем _routesToDisplay и получается вот так:

 _listItem(index) {
    return ListTile(
      title: Text(_routesToDisplay[index].route.mrTitle),
      leading: Text(
        _routesToDisplay[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() {
    print('test1');
    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(() {
            print('object');
            _routesToDisplay = _routes.where((element) {
              var routesTitle = element.route.mrTitle.toLowerCase();
              print(routesTitle);
              return routesTitle.contains(text);
            }).toList();
          });
        },
      ),
    );
  }
1
  • Думаю полезно было бы использовать понятный паттерн MVP или Redux; Чтобы была возможность провести изолированный от UI тест
    – santavital
    22 сен 2021 в 8:14

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.