Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
8.1 kB
3
Indexable
// ignore_for_file: curly_braces_in_flow_control_structures

import 'dart:collection';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_typeahead/flutter_typeahead.dart';
import 'package:tvs/members.dart';
import 'package:tvs/screens/details.dart';
import 'package:tvs/services/DBService.dart';

import 'categoryScreen.dart';
import 'loading.dart';

class Search extends StatefulWidget {
  const Search({Key? key}) : super(key: key);
  static String id = "/search";
  @override
  State<Search> createState() => _SearchState();
}

class _SearchState extends State<Search> {
  String searchBy = "Name";
  DBService dbService = DBService();
  @override
  void initState() {
    //  implement initState
    super.initState();
  }

  SplayTreeMap items = SplayTreeMap();
  late double devWidth, devHeight;
  @override
  Widget build(BuildContext context) {
    devWidth = MediaQuery.of(context).size.width;
    devHeight = MediaQuery.of(context).size.height;

    return Scaffold(
      body: SingleChildScrollView(
        child: StreamBuilder(
            stream: dbService.streamAllMember(),
            builder: (context, snapshot) {
              return Column(
                children: [
                  const SizedBox(height: 50),
                  ListTile(
                    title: ClipRRect(
                      borderRadius: BorderRadius.circular(10.0),
                      child: Container(
                        color: Colors.black12,
                        child: Row(
                          children: [
                            _buildDropDownButton(searchBy),
                            Expanded(
                              child: TypeAheadFormField(
                                  textFieldConfiguration:
                                      const TextFieldConfiguration(
                                          decoration: InputDecoration(
                                              border: InputBorder.none,
                                              hintText: " Search")),
                                  onSuggestionSelected: (val) {},
                                  itemBuilder: (context, result) {
                                    Map map = result;
                                    return ListTile(
                                      onTap: () {
                                        print("selected = $map");
                                        Navigator.push(
                                            context,
                                            MaterialPageRoute(
                                                builder: (context) =>
                                                    Details(id: map['uid'])));
                                        // Helper().contactPerson(
                                        //     member: map, context: context);
                                      },
                                      title: Text("${map['name']}"),
                                      subtitle: Text(
                                          "category:${map['category']} \ncompany:${map['company']}"),
                                    );
                                  },
                                  suggestionsCallback: (keyword) {
                                    List<Map> result = [];
                                    keyword = keyword.toLowerCase();
                                    for (Map map in members) {
                                      if (searchBy == 'Name') {
                                        String temp = map['name']
                                            .toString()
                                            .toLowerCase();
                                        if (temp.contains(keyword))
                                          result.add(map);
                                      }
                                      if (searchBy == 'Category') {
                                        String temp = map['category']
                                            .toString()
                                            .toLowerCase();
                                        if (temp.contains(keyword))
                                          result.add(map);
                                      }
                                      if (searchBy == 'Company') {
                                        String temp = map['company']
                                            .toString()
                                            .toLowerCase();
                                        if (temp.contains(keyword))
                                          result.add(map);
                                      }
                                    }
                                    return result;
                                  }),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  SizedBox(height: devHeight * 0.05),
                  StreamBuilder(
                    stream: dbService.quoteStream,
                    builder: (context, snapshot) {
                      if (!snapshot.hasData) return const Loading();
                      DocumentSnapshot ds = snapshot.data;
                      Map data = ds.data() as Map;
                      Map categories = data['categories'];
                      items.addAll(categories);

                      return Wrap(
                        spacing: devWidth * 0.07,
                        runSpacing: devHeight * 0.04,
                        children: buildItems(0, categories.length),
                      );
                    },
                  )
                ],
              );
            }),
      ),
    );
  }

  List<Widget> buildItems(int start, int end) {
    List<Widget> temp = [];
    for (int i = start; i < end; i++) {
      var key = items.keys.elementAt(i);
      var value = items.values.elementAt(i);

      temp.add(myCard(value, key));
    }
    return temp;
  }

  Widget myCard(String img, String title) {
    String temp = title;
    if (title.contains('-')) temp = temp.replaceAll('-', '\n');
    return GestureDetector(
      onTap: () {
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => CategoryScreen(category: title)));
      },
      child: Column(
        children: [
          CircleAvatar(
            backgroundImage: CachedNetworkImageProvider(img),
            radius: 30,
            backgroundColor: Colors.grey[300],
          ),
          Text(temp, style: TextStyle(fontWeight: FontWeight.w500))
        ],
      ),
    );
  }

  Widget _buildDropDownButton(String currencyCategory) {
    return Container(
      color: Colors.green,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
        child: DropdownButtonHideUnderline(
          child: DropdownButton(
            iconEnabledColor: Colors.white,
            style: const TextStyle(
              color: Colors.white,
            ),
            dropdownColor: Colors.deepPurple,
            value: searchBy,
            items: ['Name', 'Category', 'Company']
                .map((String value) => DropdownMenuItem(
                      value: value,
                      child: Row(
                        children: <Widget>[
                          Text(value),
                        ],
                      ),
                    ))
                .toList(),
            onChanged: (value) {
              setState(() {
                searchBy = value as String;
              });
            },
          ),
        ),
      ),
    );
  }
}