Usama Bin Tahir
Usama Bin Tahir

Reputation: 153

How to compare two values from two different collections from firebase?

Below is the vehicle uploading details file code that uploads details on the firebase. It uploads city, vehicle type, and phone number. I wanted to search for vehicle in the specified city. So basically it matches the details of user. For example a person wants to book vehicle in city Lahore and vehicle type Car so this should search in database if anyone uploaded details matching the description and show it to the user.

    import 'dart:io';
    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'package:flash_chat/constants.dart';
    import 'package:flash_chat/constraints/rounded_button.dart';
    import 'package:flash_chat/screens/Home.dart';
    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    import 'package:modal_progress_hud/modal_progress_hud.dart';
    import 'package:image_picker/image_picker.dart';
    
    
    class UploadingVehicle extends StatefulWidget {
      static const id = 'uploading_vehicle';
    
      @override
      _UploadingVehicleState createState() => _UploadingVehicleState();
    }
    
    class _UploadingVehicleState extends State<UploadingVehicle> {
      FirebaseFirestore _firestore = FirebaseFirestore.instance;
      bool showSpinner = false;
      static String uCity;
      String description;
      String phoneNumber;
      String uDropdownvalue = 'Hiace';
      var vehicles = ['Car','Suzuki Bolan','Hiace'];
      File _image1,_image2,_image3;
      String id;
      final Picker = ImagePicker();
    
      _UploadingVehicleState();
      _imgFromCamera() async {
    
        final image = await Picker.pickImage(
            source: ImageSource.camera, imageQuality: 50
        );
    
        setState(() {
          _image1 = File(image.path);
        });
      }
    
      _imgFromGallery(String id) async {
         final image = await  Picker.pickImage(
            source: ImageSource.gallery, imageQuality: 50
        );
    
         if(id == 'A'){
           setState(() {
             _image1 = File(image.path);
           });
         }else if(id == 'B'){
           setState(() {
             _image2 = File(image.path);
           });
         }
         else if(id == 'C'){
           setState(() {
             _image3 = File(image.path);
           });
         }
      }
    
    
      void _showPicker(context, String id) {
        showModalBottomSheet(
            context: context,
            builder: (BuildContext bc) {
              return SafeArea(
                child: Container(
                  child: new Wrap(
                    children: <Widget>[
                      new ListTile(
                          leading: new Icon(Icons.photo_library),
                          title: new Text('Photo Library'),
                          onTap: () {
                            _imgFromGallery(id);
                            Navigator.of(context).pop();
                          }),
                      new ListTile(
                        leading: new Icon(Icons.photo_camera),
                        title: new Text('Camera'),
                        onTap: () {
                          _imgFromCamera();
                          Navigator.of(context).pop();
                        },
                      ),
                    ],
                  ),
                ),
              );
            }
        );
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            iconTheme: IconThemeData(
              color: Colors.black, //change your color here
            ),
            title: Text('Upload vehicle'.toUpperCase(),
                style: TextStyle(color: Colors.black)),
            backgroundColor: Colors.yellowAccent.shade700,
            leading: GestureDetector(
                onTap: () {
                  Navigator.pop(context);
                },
                child: Icon(Icons.arrow_back)),
            actions: [
              Icon(Icons.person),
            ],
          ),
          body: SafeArea(
            child: Container(
              child: ModalProgressHUD(
                inAsyncCall: showSpinner,
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 24.0),
                  child: Column(
                    //mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: <Widget>[
                      SizedBox(
                        height: 40,
                      ),
                      Material(
                        elevation: 18,
                        shadowColor: Colors.black,
                        child: TextField(
                          style: TextStyle(
                            color: Colors.black,
                          ),
                          decoration: kRegisterTextFieldDecoration.copyWith(
                            prefixIcon: Icon(Icons.location_city,
                            color: Colors.black,
                            ),
                            hintText: 'Enter City',
                            fillColor: Colors.white,
                            border: InputBorder.none,
                            enabledBorder: InputBorder.none,
                            focusedBorder: InputBorder.none,
                          ),
                          autofocus: true,
                          onChanged: (value){
                            uCity = value;
                          },
                        ),
                      ),
                      SizedBox(
                        height: 40,
                      ),
                      Material(
                        elevation: 18,
                        shadowColor: Colors.black,
                        child: TextField(
                          style: TextStyle(
                            color: Colors.black,
                          ),
                          keyboardType: TextInputType.number,
                          decoration: kRegisterTextFieldDecoration.copyWith(
                            prefixIcon: Icon(
                              Icons.phone,
                              color: Colors.black,
                            ),
                            hintText: 'Enter Phone Number',
                            fillColor: Colors.white,
                            border: InputBorder.none,
                            enabledBorder: InputBorder.none,
                            focusedBorder: InputBorder.none,
                            focusColor: Colors.blue,
    
    
                          ),
    
                          onChanged: (value){
                            phoneNumber = value;
                          },
    
                        ),
                      ),
                      SizedBox(
                        height: 40,
                      ),
                      Row(
                        children: <Widget>[
                          Text(
                            'Select Vehicle:',
                            style: TextStyle(
                              color: Colors.blue,
                              fontSize: 15,
                            ),),
                          SizedBox(
                            width: 20,
                          ),
                          Center(
                            child: DropdownButton<String>(
                              value: uDropdownvalue,
                              elevation: 16,
                              dropdownColor: Colors.white,
                              icon: Icon(Icons.arrow_downward,
                                color: Colors.black,
                              ),
                              style: TextStyle(
                                color: Colors.black,
                                fontSize: 15,
                              ),
                              underline: Container(
                                height: 1,
                                color: Colors.black,
                              ),
                              items: vehicles.map<DropdownMenuItem<String>>((String vehicle) {
                                return DropdownMenuItem<String>(
                                  value: vehicle,
                                  child: Text(vehicle),
                                );
                              }).toList(),
                              onChanged: (String newValue) {
                                setState(() {
                                  uDropdownvalue = newValue;
                                });
                              },
                            ),
                          ),
                        ],
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      Text(
                        'Add Description:',
                        style: TextStyle(
                          color: Colors.blue,
                          fontSize: 18,
                        ),
                      ),
                      Expanded(
                        child: Container(
                            child: TextField(
                              keyboardType: TextInputType.multiline,
                              maxLines: null,
                              decoration: InputDecoration(
                                enabledBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(
                                    color: Colors.black,
                                  )
                                ),
                              ),
                              style: TextStyle(
                                color: Colors.black,
                              ),
                              onChanged: (value){
                                description=value;
                              },
                            ),
    
                        ),
                      ),
                      Row(
                        children: [
                          Expanded(
                            child: buildGestureDetector(context,_image1),
                          ),
                          Expanded(
                            child: buildGestureDetector(context,_image2),
                          ),
                          Expanded(
                            child: buildGestureDetector(context,_image3),
                          ),
                        ],
                      ),
                      Roundedbutton(
                        color: Colors.yellow,
                        title: 'Upload vehicle',
                        onPressed: () async {
                          setState(() {
                            showSpinner = true;
                          });
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(content: Text('Details uploaded successfully')),
                          );
                          _firestore.collection('Uploading Vehicle Details').add({
                            'City': uCity,
                            'Vehicle': uDropdownvalue,
                            'Description' : description,
                            'Phone.No#' : phoneNumber,
                          });
                          Navigator.pushNamed(context, HomeScreen.id);
                        },
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        );
      }
    
      GestureDetector buildGestureDetector(BuildContext context, File _image) {
        //GestureDetector({@required this._image});
        //File _image;
        return GestureDetector(
                            onTap: () {
                              _showPicker(context, 'A');
                            },
                            child: CircleAvatar(
                              radius: 53,
                              backgroundColor: Colors.black,
                              child: _image != null
                                  ? ClipRRect(
                                borderRadius: BorderRadius.circular(50),
                                child: Image.file(
                                  _image,
                                  width: 100,
                                  height: 100,
                                  fit: BoxFit.fitHeight,
                                ),
                              )
                                  : Container(
                                decoration: BoxDecoration(
                                    color: Colors.grey[200],
                                    borderRadius: BorderRadius.circular(50)),
                                width: 100,
                                height: 100,
                                child: Icon(
                                  Icons.camera_alt,
                                  color: Colors.grey[800],
                                ),
                              ),
                            ),
                          );
      }
    }

And below is the code for the user who wants to book vehicle in his city. So it should search in firebase if the required details are present in the firebase or not. If yes it should retrieve the details from the firebase and show it to the person who's looking for it.

import 'package:flash_chat/constants.dart';
import 'package:flash_chat/constraints/rounded_button.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:flash_chat/screens/uploading_vehicle.dart';

class Booking extends StatefulWidget {
  static const id = 'booking';


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

class _BookingState extends State<Booking> {

  FirebaseFirestore _firestore = FirebaseFirestore.instance;
  final UploadingVehicle uv = new UploadingVehicle();
  bool showSpinner = false;
  String city;
  String dropdownvalue = 'Hiace';
  var vehicles = ['Car','Suzuki Bolan','Hiace'];

  Object get uCity => null;

  Object get uDropdownvalue => null;


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        iconTheme: IconThemeData(
          color: Colors.black, //change your color here
        ),
        title: Text('Book vehicle'.toUpperCase(),
            style: TextStyle(color: Colors.black)),
        backgroundColor: Colors.yellowAccent.shade700,
        leading: GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: Icon(Icons.arrow_back)),
        actions: [
          Icon(Icons.person),
        ],
      ),
      body: SafeArea(
        child: Container(
          child: ModalProgressHUD(
            inAsyncCall: showSpinner,
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 24.0),
              child: Column(
                //mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  SizedBox(
                    height: 40,
                  ),
                  Material(
                    elevation: 18,
                    shadowColor: Colors.black,
                    child: TextField(
                      style: TextStyle(
                        color: Colors.black,
                      ),
                      decoration: kRegisterTextFieldDecoration.copyWith(
                        hintText: 'Enter City',
                        fillColor: Colors.white,
                        border: InputBorder.none,
                        enabledBorder: InputBorder.none,
                        focusedBorder: InputBorder.none,
                      ),
                      onChanged: (value){
                        city=value;
                      },
                    ),
                  ),
                  SizedBox(
                    height: 40,
                  ),
          Row(
          children: <Widget>[
            Text(
              'Select Vehicle:',
              style: TextStyle(
                color: Colors.blue,
                fontSize: 15,
              ),),
            SizedBox(
              width: 20,
            ),
                Center(
                  child: DropdownButton<String>(
                    value: dropdownvalue,
                    elevation: 16,
                    dropdownColor: Colors.white,
                    icon: Icon(Icons.arrow_downward,
                    color: Colors.black,
                    ),
                    style: TextStyle(
                        color: Colors.black,
                      fontSize: 15,
                    ),
                    underline: Container(
                      height: 1,
                      color: Colors.black,
                    ),
                    items: vehicles.map<DropdownMenuItem<String>>((String vehicle) {
                      return DropdownMenuItem<String>(
                        value: vehicle,
                        child: Text(vehicle),
                      );
                    }).toList(),
                    onChanged: (String newValue) {
                      setState(() {
                        dropdownvalue = newValue;
                      });
                    },
                  ),
                ),
            ],
          ),

                  Roundedbutton(
                    color: Colors.yellow,
                    title: 'Search for vehicle',
                    onPressed: () async {
                  setState(() {
                    showSpinner = true;
                  });
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('Searched')),
                  );
                  _firestore.collection('Booking Details').add({
                    'City': city,
                    'Vehicle': dropdownvalue,
                  });
                  Navigator.pushNamed(context, Booking.id);
                    },
                  ),
                  Container(
                    color: Colors.white,
                    child: Text('Details matched',
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 30,
                      ),
                    )
                        : Text(
                      'Details not matched',
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 30,
                      ),),
                    ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
  }

How am I supposed to do this?

Upvotes: 2

Views: 1192

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598750

As far as I can tell from the massive amount of code you shared, this is the code that adds the vehicle details to the database:

_firestore.collection('Uploading Vehicle Details').add({
  'City': uCity,
  'Vehicle': uDropdownvalue,
  'Description' : description,
  'Phone.No#' : phoneNumber,
});

If you want to search that information, you can use a query such as this one:

_firestore.collection('Uploading Vehicle Details')
  .where('City', isEqualTo: 'San Francisco')
  .where('Vehicle', isEqualTo: 'Toyota RAV4')
  .get()
  .then(...);

If you want to show this in the UI, you'll want to use snapshots instead of get and wrap it in a StreamBuilder as shown in the documentation on listening to realtime changes.

Upvotes: 4

Related Questions