0

I made a Firebase listing system using Flutter I can order it by the thing I want but, can't search through. How can I implement a search system? It list as the love number right now.

EDIT: I added the whole code for explanations.

I tried to do the link this post archived for. Nothing worked at this moment.

Search Code:

          TextField(
            decoration: InputDecoration(
              hintStyle: TextStyle(fontSize: 17),
              hintText: 'Kuş Arama Çubuğu',
              suffixIcon: Icon(Icons.search),
              border: InputBorder.none,
              contentPadding: EdgeInsets.all(20),
            ),
            onChanged: (value) => {
              data.startAt(value) // I don't know what to do here.
            },
          ),

Full Code

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:wallpaper_app/models/config.dart';
import 'package:wallpaper_app/pages/details.dart';
import 'package:wallpaper_app/utils/snacbar.dart';
import 'package:wallpaper_app/widgets/cached_image.dart';

class PopularItems extends StatefulWidget {
  PopularItems({Key? key, required this.scaffoldKey}) : super(key: key);
  final GlobalKey<ScaffoldState> scaffoldKey;

  @override
  _PopularItemsState createState() => _PopularItemsState();
}

class _PopularItemsState extends State<PopularItems>
    with AutomaticKeepAliveClientMixin {
  final FirebaseFirestore firestore = FirebaseFirestore.instance;

  ScrollController? controller;
  DocumentSnapshot? _lastVisible;
  late bool _isLoading;
  List<DocumentSnapshot> _data = [];
  String? searchKey;
  QuerySnapshot? data;
  Stream? streamQuery;

  @override
  void initState() {
    controller = new ScrollController()..addListener(_scrollListener);
    super.initState();
    _isLoading = true;
    _getData();
  }

  Future<Null> _getData() async {
    if (_lastVisible == null)
      data = await firestore
          .collection('contents')
          .orderBy('loves', descending: true)
          .limit(10)
          .get();
    else
      data = await firestore
          .collection('contents')
          .orderBy('loves', descending: true)
          .startAfter([_lastVisible!['loves']])
          .limit(10)
          .get();

    if (data!.docs.length > 0) {
      _lastVisible = data!.docs[data!.docs.length - 1];
      if (mounted) {
        setState(() {
          _isLoading = false;
          _data.addAll(data!.docs);
        });
      }
    } else {
      setState(() => _isLoading = false);
      openSnacbar(widget.scaffoldKey, 'Daha fazla yok :(');
    }
    return null;
  }

  @override
  void dispose() {
    controller!.removeListener(_scrollListener);
    super.dispose();
  }

  void _scrollListener() {
    if (!_isLoading) {
      if (controller!.position.pixels == controller!.position.maxScrollExtent) {
        setState(() => _isLoading = true);
        _getData();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Column(
      children: [
        SizedBox(
          height: 5,
        ),
        Container(
          decoration: BoxDecoration(
            color: Colors.grey[300],
            borderRadius: BorderRadius.circular(32),
          ),
          child: TextField(
              decoration: InputDecoration(
                hintStyle: TextStyle(fontSize: 17),
                hintText: 'Kuş Arama Çubuğu',
                suffixIcon: Icon(Icons.search),
                border: InputBorder.none,
                contentPadding: EdgeInsets.all(20),
              ),
              onChanged: (value) async {
                data = await firestore
                    .collection('contents')
                    .orderBy('sira')
                    .startAt([value])
                    .limit(10)
                    .get();
                setState(() {
                  _isLoading = false;
                  _data.addAll(data!.docs);
                });
              }),
        ),
        SizedBox(
          height: 5,
        ),
        Expanded(
          child: StaggeredGridView.countBuilder(
            controller: controller,
            crossAxisCount: 4,
            itemCount: _data.length + 1,
            itemBuilder: (BuildContext context, int index) {
              if (index < _data.length) {
                final DocumentSnapshot d = _data[index];
                return InkWell(
                  child: Stack(
                    children: <Widget>[
                      Hero(
                          tag: 'popular$index',
                          child: cachedImage(d['image url'])),
                      Positioned(
                        bottom: 30,
                        left: 10,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                              Config().hashTag,
                              style:
                                  TextStyle(color: Colors.white, fontSize: 14),
                            ),
                            Text(
                              d['name'],
                              style:
                                  TextStyle(color: Colors.white, fontSize: 18),
                            )
                          ],
                        ),
                      ),
                      Positioned(
                        right: 10,
                        top: 20,
                        child: Row(
                          children: [
                            Icon(Icons.favorite,
                                color: Colors.white.withOpacity(0.5), size: 25),
                            Text(
                              d['loves'].toString(),
                              style: TextStyle(
                                  color: Colors.white.withOpacity(0.7),
                                  fontSize: 16,
                                  fontWeight: FontWeight.w600),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                  onTap: () {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => DetailsPage(
                                tag: 'popular$index',
                                imageUrl: d['image url'],
                                catagory: d['name'],
                                timestamp: d['timestamp'],
                                detay: d['hakkinda'],
                                habitat: d['habitat'],
                                yayilis: d['yayilis'],
                                beslenme: d['beslenme'],
                                biyoloji: d['biyoloji'],
                                biyoname: d['biyoname'],
                                ses: d['ses'])));
                  },
                );
              }

              return Center(
                child: new Opacity(
                  opacity: _isLoading ? 1.0 : 0.0,
                  child: new SizedBox(
                      width: 32.0,
                      height: 32.0,
                      child: CupertinoActivityIndicator()),
                ),
              );
            },
            staggeredTileBuilder: (int index) =>
                new StaggeredTile.count(2, index.isEven ? 4 : 3),
            mainAxisSpacing: 10,
            crossAxisSpacing: 10,
            padding: EdgeInsets.all(15),
          ),
        ),
      ],
    );
  }

  @override
  bool get wantKeepAlive => true;
}

CidQu
  • 412
  • 6
  • 13
  • Does this answer your question? [Flutter: Firebase basic Query or Basic Search code](https://stackoverflow.com/questions/50870652/flutter-firebase-basic-query-or-basic-search-code) – Lluís Muñoz Jan 24 '22 at 09:58
  • @LluísMuñoz Nope, It doesn't. I can't add this into my firebase code. – CidQu Jan 24 '22 at 11:21
  • I understood that you are trying to create a form, which uses Firebase to query for similar results on each TextField change. Please correct me if I'm wrong. If my understanding was correct, could you please provide more details to why the answers to that question didn't help you? – Lluís Muñoz Jan 24 '22 at 12:29
  • Not really. I'm sharing the whole code in the original title. Can you check it, please? I tried the link you sent me but nothing works. – CidQu Jan 24 '22 at 21:05
  • Could you please provide a detailed explanation on what you are trying to achieve? Do you want the search to be done in Flutter after the queries or are you trying to [filter the queries](https://firebase.flutter.dev/docs/firestore/usage/#filtering)? Additionally, please note that sharing your entire code is considered [a bad practice](https://stackoverflow.com/help/how-to-ask#:~:text=don%27t%20just%20copy%20in%20your%20entire%20program!). – Lluís Muñoz Feb 03 '22 at 08:41

0 Answers0