Ravikant Sontakke
Ravikant Sontakke

Reputation: 23

In Flutter app, not fetching data from Firebase

I am new in Flutter, I am trying to fetch database from firebase but I am not displaying data on screen here is my code

pubspec.yaml

name: umhelogin
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3
  provider: ^5.0.0
  firebase_core: ^1.2.0
  cloud_firestore: ^2.2.0
  firebase_auth: ^1.4.1


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  #  assets:
  #  - images/my-photo.jpg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

home_screen.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:umhelogin/model/databaseManager.dart';
import 'package:umhelogin/screen/formalMeet_screen.dart';
import '/screen/contact.dart';
import '/screen/about.dart';
import '/screen/login_screen.dart';


class HomeScreen extends StatefulWidget {
  static const routeName = '/home';

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

class _HomeScreenState extends State<HomeScreen> {

  List productList = [];
  // final productList = FirebaseFirestore.instance.collection('formalMeet');

  @override
  void initState() {
    super.initState();
    fetchDatabaseList();
  }

  fetchDatabaseList() async {
    dynamic resultant = await DatabaseManager().getUserList();

    if(resultant == null) {
      print("Unable to retrieve");
    } else {
      setState(() {
        productList = resultant;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final _width = MediaQuery.of(context).size.width;
    final _height = MediaQuery.of(context).size.height;
    return Scaffold(
      appBar: AppBar(
        title: Text('UMHE Portal'),
        centerTitle: true,
        actions: <Widget>[
          IconButton(onPressed: () {
            Navigator.of(context).pushReplacementNamed(LoginScreen.routeName);
          },
              icon: Icon(
                Icons.exit_to_app,
                color: Colors.white60,
                size: 30,
              ),
          )
        ],
      ),
      drawer: new Drawer(
        child: ListView(
          children: <Widget>[
            new UserAccountsDrawerHeader(
              accountName: new Text('Ravikant Sontakke'),
              accountEmail: new Text('ravi@umhe.com'),
              currentAccountPicture: new CircleAvatar(
                backgroundImage: new NetworkImage('http://darwishcybertech.com/knowledgehub/wp-content/uploads/2020/05/rs.jpg'),
              ),
            ),
            new ListTile(
              title: Text("About"),
              onTap: () {
                Navigator.of(context).pop();
                Navigator.push(context, new MaterialPageRoute(
                    builder: (BuildContext context) => new AboutPage())
                );
                // Navigator.of(context).pushReplacementNamed(AboutPage.routeName);
              },
            ),
            new Divider(
              color: Colors.black,
              height: 5.0,
            ),
            new ListTile(
              title: Text("Contact"),
              onTap: () {
                Navigator.of(context).pop();
                Navigator.push(context, new MaterialPageRoute(
                    builder: (BuildContext context) => new ContactPage())
                );
                // Navigator.of(context).pushReplacementNamed(AboutPage.routeName);
              },
            ),
          ],
        ),
      ),
      body: Stack(
        children: <Widget>[
          Center(
            child: Text(
              'This is my UMHE Home Screen',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 20,
              ),
            ),
          ),
        Container(
          child: ListView.builder(
            itemCount: productList.length,
            itemBuilder: (context, index) {
              return Card(
                child: ListTile(
                  title: Text(productList[index]['Company Name']),
                  subtitle: Text(productList[index]['Contact Person']),
                ),
              );
            },
          ),
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.end,
          children: <Widget>[
            ButtonTheme(
                minWidth: 410,
                height: 50,
                child: RaisedButton(
                  child: Text('Add Formal Meeting', style: TextStyle(fontSize: 20),),
                  onPressed: () {
                    Navigator.push(context, MaterialPageRoute(builder: (context) => FormalMeetScreen()));
                  },
                  // shape: RoundedRectangleBorder(
                  //   borderRadius: BorderRadius.circular(30),
                  // ),
                  color: Color(0xffc4921b),
                  textColor: Colors.white,
                ))
          ],
        ),
      ],),
    );
  }
}

In above code for fetch database, I also tried out second way that is in comment but still not working

databaseManager.dart

import 'package:cloud_firestore/cloud_firestore.dart';

class DatabaseManager {
  final CollectionReference productList = FirebaseFirestore.instance.collection("formalList");

  Future getUserList() async {
    List itemList = [];

    try{
      await productList.get().then((querySnapshot) {
        querySnapshot.docs.forEach((element) {
          itemList.add(element.data());
        });
      });
    } catch(e){
      print(e.toString());
      return null;
    }
  }
}

formalMeet_screen.dart

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:umhelogin/model/formal_meet.dart';
import 'package:umhelogin/screen/product_screen.dart';
import '/widgets/provider_widget.dart';

class FormalMeetScreen extends StatefulWidget {
  final FormalMeet formalMeet;
  FormalMeetScreen({Key key, @required this.formalMeet}) : super(key: key);
  @override
  _FormalMeetScreenState createState() => _FormalMeetScreenState();
}

class _FormalMeetScreenState extends State<FormalMeetScreen> {
  GlobalKey<FormState> formKey = GlobalKey<FormState>();

  TextEditingController companyName = TextEditingController();
  TextEditingController contactPerson = TextEditingController();
  TextEditingController contactNumber = TextEditingController();
  TextEditingController jobTitle = TextEditingController();
  TextEditingController email = TextEditingController();
  TextEditingController potentialInformation = TextEditingController();

  var formalMeet = FormalMeet(null, null, null, null, null, null);
  CollectionReference ref = FirebaseFirestore.instance.collection('formalMeet');


  buildCompanyName() => TextFormField(
        controller: companyName,
        decoration: InputDecoration(
          labelText: 'Company Name',
          border: OutlineInputBorder(),
        ),
        validator: (value) {
          if (value.isEmpty) {
            return 'Company Name can not be empty';
          }
          return null;
        },
        onSaved: (value) => setState(() => formalMeet.companyName = value),
      );

  Widget buildContactPerson() => TextFormField(
        controller: contactPerson,
        decoration: InputDecoration(
          labelText: 'Contact Person',
          border: OutlineInputBorder(),
        ),
        validator: (value) {
          if (value.isEmpty) {
            return 'Contact Person can not be empty';
          }
          return null;
        },
        maxLength: 30,
        onSaved: (value) => setState(() => formalMeet.contactPerson = value),
      );

  Widget buildContactNumber() => TextFormField(
        controller: contactNumber,
        decoration: InputDecoration(
          labelText: 'Contact Number',
          border: OutlineInputBorder(),
        ),
        validator: (value) {
          if (value.isEmpty) {
            return 'Contact Number can not be empty';
          }
          return null;
        },
        maxLength: 10,
        onSaved: (value) =>
            setState(() => formalMeet.contactNumber = value as int),
      );

  Widget buildJobTitle() => TextFormField(
        controller: jobTitle,
        decoration: InputDecoration(
          labelText: 'Job Title',
          border: OutlineInputBorder(),
        ),
        validator: (value) {
          if (value.isEmpty) {
            return 'Job Title can not be empty';
          }
          return null;
        },
        onSaved: (value) => setState(() => formalMeet.jobTitle = value),
      );

  Widget buildEmail() => TextFormField(
        controller: email,
        decoration: InputDecoration(
          labelText: 'Email',
          border: OutlineInputBorder(),
        ),
        validator: (value) {
          final pattern =
              r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+";
          final regExp = RegExp(pattern);
          if (value.isEmpty) {
            return 'Email can not be empty';
          } else if (!regExp.hasMatch(value)) {
            return 'Enter a valid email';
          }
          return null;
        },
        keyboardType: TextInputType.emailAddress,
        onSaved: (value) => setState(() => formalMeet.email = value),
      );

  Widget buildPotentialInformation() => TextFormField(
        controller: potentialInformation,
        decoration: InputDecoration(
          labelText: 'Potential Information',
          border: OutlineInputBorder(),
        ),
        validator: (value) {
          if (value.isEmpty) {
            return 'Potential Information can not be empty';
          }
          return null;
        },
        onSaved: (value) =>
            setState(() => formalMeet.potentialInformation = value),
      );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(
          'Formal Meet',
        ),
      ),
      body: Form(
        key: formKey,
        child: ListView(
          padding: EdgeInsets.all(16),
          children: [
            buildCompanyName(),
            const SizedBox(height: 32),
            buildContactPerson(),
            const SizedBox(height: 16),
            buildContactNumber(),
            const SizedBox(height: 32),
            buildJobTitle(),
            const SizedBox(height: 32),
            buildEmail(),
            const SizedBox(height: 32),
            buildPotentialInformation(),
            const SizedBox(height: 32),
            ElevatedButton(
                child: Text(
                  'Submit',
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                onPressed: () {
                  final isValid = formKey.currentState.validate();
                  FocusScope.of(context).unfocus();
                  if (isValid) {
                    ref.add({
                      'Company Name': companyName.text,
                      'Contact Person': contactPerson.text,
                      'Contact Number': contactNumber.text,
                      'Job Title': jobTitle.text,
                      'Email': email.text,
                      'Potential Information': potentialInformation.text,
                      'time': DateTime.now()
                    });
                    formKey.currentState.reset();
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => ProductScreen()));
                  }
                }),
          ],
        ),
      ),
    );
  }
}

product_screen.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:umhelogin/model/product.dart';

class ProductScreen extends StatefulWidget {
  // static const routeName = '/about';
  const ProductScreen({Key key}) : super(key: key);

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

class _ProductScreenState extends State<ProductScreen> {
  GlobalKey<FormState> formKey = GlobalKey<FormState>();

  TextEditingController productName = TextEditingController();
  TextEditingController productBrand = TextEditingController();
  TextEditingController productModel = TextEditingController();
  TextEditingController productQuantity = TextEditingController();

  var product = Product(null, null, null, null);

  CollectionReference ref = FirebaseFirestore.instance.collection('product');


  buildProductName() => TextFormField(
    controller: productName,
    decoration: InputDecoration(
      labelText: 'Product Name',
      border: OutlineInputBorder(),
    ),
    validator: (value) {
      if (value.isEmpty) {
        return 'Product Name can not be empty';
      }
      return null;
    },
    onSaved: (value) => setState(() => product.name = value),
  );

  buildProductBrand() => TextFormField(
    controller: productBrand,
    decoration: InputDecoration(
      labelText: 'Product Brand',
      border: OutlineInputBorder(),
    ),
    validator: (value) {
      if (value.isEmpty) {
        return 'Product Brand can not be empty';
      }
      return null;
    },
    onSaved: (value) => setState(() => product.brand = value),
  );

  buildProductModel() => TextFormField(
    controller: productModel,
    decoration: InputDecoration(
      labelText: 'Product Model',
      border: OutlineInputBorder(),
    ),
    validator: (value) {
      if (value.isEmpty) {
        return 'Product Model can not be empty';
      }
      return null;
    },
    onSaved: (value) => setState(() => product.model = value),
  );

  buildProductQuantity() => TextFormField(
    controller: productQuantity,
    decoration: InputDecoration(
      labelText: 'Product Quantity',
      border: OutlineInputBorder(),
    ),
    validator: (value) {
      if (value.isEmpty) {
        return 'Product Quantity can not be empty';
      }
      return null;
    },
    onSaved: (value) => setState(() => product.quantity = value),
  );


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Product Screen"),
        centerTitle: true,
      ),
      body: Form(
        key: formKey,
        child: ListView(
          padding: EdgeInsets.all(16),
          children: [
            buildProductName(),
            SizedBox(height: 32,),
            buildProductBrand(),
            SizedBox(height: 32,),
            buildProductModel(),
            SizedBox(height: 32,),
            buildProductQuantity(),
            SizedBox(height: 32,),
            ElevatedButton(
                child: Text(
                    'Submit',
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold
                  ),
                ),
                onPressed: () {
                  final isValid = formKey.currentState.validate();
                  FocusScope.of(context).unfocus();
                  if(isValid) {
                    ref.add({
                      'Product Name': productName.text,
                      'Product Brand': productBrand.text,
                      'Product Model': productModel.text,
                      'Product Quantity': productQuantity.text
                    });
                    formKey.currentState.reset();
                    Navigator.of(context).popUntil((route) => route.isFirst);
                  }
                }),
          ],
        ),
      ),
    );
  }
}

formal_meet.dart

class FormalMeet {
   String companyName;
   String contactPerson;
   int contactNumber;
   String jobTitle;
   String email;
   String potentialInformation;

  FormalMeet(
      this.companyName,
      this.contactPerson,
      this.contactNumber,
      this.jobTitle,
      this.email,
      this.potentialInformation
      );
}

product.dart

class Product {
   String name;
   String brand;
   String model;
   String quantity;

  Product(
      this.name,
      this.brand,
      this.model,
      this.quantity
      );
}

formalMeet Cloud Firestore database

enter image description here

product Cloud Firestore database

enter image description here

Upvotes: 0

Views: 1653

Answers (2)

pr0gramista
pr0gramista

Reputation: 9038

I think you are not returning your list of products from DatabaseManager. This is corrected code:

class DatabaseManager {
  final CollectionReference productList = FirebaseFirestore.instance.collection("formalList");

  Future<List?> getUserList() async { // Added List? for better typing
    List itemList = [];

    try{
      await productList.get().then((querySnapshot) {
        querySnapshot.docs.forEach((element) {
          itemList.add(element.data());
        });
      });

      return itemList; // This is missing
    } catch(e){
      print(e.toString());
      return null;
    }
  }
}

Upvotes: 2

SARVESH TANDON
SARVESH TANDON

Reputation: 151

Does your main function just create an instance of HomeScreen? If so, you have forgotten to initialize your firebase app. I strongly recommend that you refer to the following link in order to do so. You need to initialize flutterfire for it to work properly. Also for next time, remember to add your program's output to your question.

https://firebase.flutter.dev/docs/overview#initializing-flutterfire

Upvotes: 0

Related Questions