在Flutter中实现Algolia搜索

w8ntj3qf  于 2022-12-30  发布在  Flutter
关注(0)|答案(1)|浏览(110)

我试图实现algolia搜索flutter与过滤器。我发现了一篇文章上的algolia网站,我遵循到一个发球台,以达到这一阶段的实现,但我得到这个错误,并不知道该怎么办:

lib/services/search.dart:194:52: Error: Member not found: 'fromResponse'.
      _assetsSearcher.responses.map(SearchMetadata.fromResponse);
                                                   ^^^^^^^^^^^^
lib/services/search.dart:200:46: Error: Member not found: 'fromResponse'.
      _assetsSearcher.responses.map(HitsPage.fromResponse);
                                             ^^^^^^^^^^^^

这是我的代码:

class SearchMetadata {
  final int nbHits;

  const SearchMetadata(this.nbHits);

  factory SearchMetadata.fromResponse(SearchResponse response) =>
      SearchMetadata(response.nbHits);
}

class Asset {
  final String code;
  final String name;
  final String desc;
  final String loc;
  final String img;

  Asset(this.code, this.name, this.desc, this.loc, this.img);

  static Asset fromJson(Map<String, dynamic> json) {
    return Asset(
        json['name'], json['desc'], json['desc'], json['loc'], json['img']);
  }
}

class HitsPage {
  const HitsPage(this.assets, this.pageKey, this.nextPageKey);

  final List<Asset> assets;
  final int pageKey;
  final int? nextPageKey;

  factory HitsPage.fromResponse(SearchResponse response) {
    final assets = response.hits.map(Asset.fromJson).toList();
    final isLastPage = response.page >= response.nbPages;
    final nextPageKey = isLastPage ? null : response.page + 1;
    return HitsPage(assets, response.page, nextPageKey);
  }
}

class AlgoliaSearchFilters extends StatefulWidget {
  const AlgoliaSearchFilters({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<AlgoliaSearchFilters> createState() => _AlgoliaSearchFiltersState();
}

class _AlgoliaSearchFiltersState extends State<AlgoliaSearchFilters> {
  final _searchTextController = TextEditingController();

  final _assetsSearcher = HitsSearcher(
      applicationID: 'OPN6AROJK6',
      apiKey: '0ba458475d25b7e2069d700c32e42f29',
      indexName: 'asset');

  Stream<SearchMetadata> get _searchMetadata =>
      _assetsSearcher.responses.map(SearchMetadata.fromResponse);

  final PagingController<int, Asset> _pagingController =
      PagingController(firstPageKey: 0);

  Stream<HitsPage> get _searchPage =>
      _assetsSearcher.responses.map(HitsPage.fromResponse);

  final GlobalKey<ScaffoldState> _mainScaffoldKey = GlobalKey();

  final _filterState = FilterState();

  late final _facetList = FacetList(
      searcher: _assetsSearcher, filterState: _filterState, attribute: 'loc');

  @override
  void initState() {
    super.initState();
    _searchTextController
        .addListener(() => _assetsSearcher.query(_searchTextController.text));
    _searchPage.listen((page) {
      if (page.pageKey == 0) {
        _pagingController.refresh();
      }
      _pagingController.appendPage(page.assets, page.nextPageKey);
    }).onError((error) => _pagingController.error = error);
    _pagingController.addPageRequestListener((pageKey) =>
        _assetsSearcher.applyState((state) => state.copyWith(page: pageKey)));
    _assetsSearcher.connectFilterState(_filterState);
    _filterState.filters.listen((_) => _pagingController.refresh());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _mainScaffoldKey,
      appBar: AppBar(
        backgroundColor: Colors.blue[900],
        title: const Text("Algolia Flutter Search"),
        actions: [
          IconButton(
              onPressed: () => _mainScaffoldKey.currentState?.openEndDrawer(),
              icon: const Icon(Icons.filter_list_sharp))
        ],
      ),
      endDrawer: Drawer(
        child: _filters(context),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            SizedBox(
                height: 44,
                child: TextField(
                  controller: _searchTextController,
                  decoration: const InputDecoration(
                    border: InputBorder.none,
                    hintText: 'Enter a search term',
                    prefixIcon: Icon(Icons.search),
                  ),
                )),
            StreamBuilder<SearchMetadata>(
              stream: _searchMetadata,
              builder: (context, snapshot) {
                if (!snapshot.hasData) {
                  return const SizedBox.shrink();
                }
                return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Text('${snapshot.data!.nbHits} hits'),
                );
              },
            ),
            Expanded(
              child: _hits(context),
            )
          ],
        ),
      ),
    );
  }

  Widget _hits(BuildContext context) => PagedListView<int, Asset>(
      pagingController: _pagingController,
      builderDelegate: PagedChildBuilderDelegate<Asset>(
          noItemsFoundIndicatorBuilder: (_) => const Center(
                child: Text('No results found'),
              ),
          itemBuilder: (_, item, __) => Container(
                color: Colors.white,
                height: 80,
                padding: const EdgeInsets.all(8.0),
                child: Row(
                  children: [
                    SizedBox(width: 50, child: Image.network(item.img)),
                    const SizedBox(width: 20),
                    Expanded(child: Text(item.name))
                  ],
                ),
              )));

  Widget _filters(BuildContext context) => Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.blue[900],
          title: const Text('Filters'),
        ),
        body: StreamBuilder<List<SelectableItem<Facet>>>(
            stream: _facetList.facets,
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                return const SizedBox.shrink();
              }
              final selectableFacets = snapshot.data!;
              return ListView.builder(
                  padding: const EdgeInsets.all(8.0),
                  itemCount: selectableFacets.length,
                  itemBuilder: (_, index) {
                    final selectableFacet = selectableFacets[index];
                    return CheckboxListTile(
                      value: selectableFacet.isSelected,
                      title: Text(
                          '${selectableFacet.item.value} (${selectableFacet.item.count})'),
                      onChanged: (_) {
                        _facetList.toggle(selectableFacet.item.value);
                      },
                    );
                  });
            }),
      );

  @override
  void dispose() {
    _searchTextController.dispose();
    _assetsSearcher.dispose();
    _pagingController.dispose();
    _filterState.dispose();
    _facetList.dispose();
    super.dispose();
  }
}

它显示为一个错误,只有当我运行我的程序,请让我知道任何修复,谢谢!

gab6jxml

gab6jxml1#

我在更新flutter后遇到了同样的问题。尝试运行

flutter pub upgrade

升级所有依赖项,因为这是由可传递依赖项引起的。

相关问题