problem in flutter with fireStore in QuerySnapshot its always null - firebase

i wil put all the code below this explanation
so i just create a CollectionReference like this
in class DataBaseServices
final CollectionReference brewCollection =
Firestore.instance.collection('brews');
and i add data normally
after i use it in stream
Stream<QuerySnapshot> get brews {
return brewCollection.snapshots();
}
and i put the value in widget
Widget build(BuildContext context) {
return StreamProvider<QuerySnapshot>.value(
value: DataBaseServices().brews,
and in another widget
i call it
final snapshot = Provider.of<QuerySnapshot>(context);
and after i check here if it is null i find that it is null
the code :
class database
import 'package:cloud_firestore/cloud_firestore.dart';
class DataBaseServices {
final CollectionReference brewCollection =
Firestore.instance.collection('brews');
final String uid;
DataBaseServices({this.uid});
Future updateUserData({int sugar, String name, int strength}) async {
return await brewCollection.document(uid).setData(
{'sugar': sugar, 'name': name, 'strength': strength},
);
}
Stream<QuerySnapshot> get brews {
return brewCollection.snapshots();
}
}
home class
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:crewbrewapp/screens/home/brews_list.dart';
import 'package:crewbrewapp/services/auth.dart';
import 'package:crewbrewapp/services/database.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
AuthServices _auth = AuthServices();
#override
Widget build(BuildContext context) {
return StreamProvider<QuerySnapshot>.value(
value: DataBaseServices().brews,
child: Scaffold(
backgroundColor: Colors.brown.shade100,
appBar: AppBar(
title: Text('Home'),
centerTitle: true,
backgroundColor: Colors.brown.shade500,
actions: <Widget>[
FlatButton.icon(
icon: Icon(Icons.person),
label: Text('Log out'),
onPressed: () async {
await _auth.signOut();
},
),
],
leading: Icon(Icons.menu),
),
body: BrewsList(),
),
);
}
}
class brewList
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:crewbrewapp/screens/home/brew_tile.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:crewbrewapp/models/brew.dart';
class BrewsList extends StatefulWidget {
#override
_BrewsListState createState() => _BrewsListState();
}
class _BrewsListState extends State<BrewsList> {
List<Brew> brews;
#override
Widget build(BuildContext context) {
final snapshot = Provider.of<QuerySnapshot>(context);
if (snapshot != null) {
snapshot.documents.map(
(element) {
brews = [
Brew(
sugar: element.data['sugar'] ?? 0,
strength: element.data['strength'] ?? 0,
name: element.data['name'] ?? '',
),
];
},
);
}
return brews == null
? Container(
child: Text('Empty'),
)
: ListView.builder(
itemCount: brews.length,
itemBuilder: (context, index) {
return BrewTile(brew: brews[index]);
},
);
}
}
i tried everything but it still show nothing

Rather you should assign brews to the whole map:
if (snapshot != null) {
brews = snapshot.documents.map(
(element) {
return Brew(
sugar: element.data['sugar'] ?? 0,
strength: element.data['strength'] ?? 0,
name: element.data['name'] ?? '',
);
},
).toList();
}

I believe your snapshot is not quite created by the time it is called in brewList.
A progress indicator may work for you;
if (snapshot == null) return CircularProgressIndicator();
snapshot.documents.map(
(element) {
brews = [
Brew(
sugar: element.data['sugar'] ?? 0,
strength: element.data['strength'] ?? 0,
name: element.data['name'] ?? '',
),
];
);
}

add if
call doc.data() - data with () operator ,see below code in the class BrewList:
final brews = Provider.of<QuerySnapshot>(context);
//print(brews);
if (brews != null) {
for (var doc in brews.docs) {
print(doc.data());
}
}
call BrewList() class with provider from Home class,
see below code in the class Home :
> return StreamProvider<QuerySnapshot>.value(
> initialData: null,
> value: DatabaseBrews(uid:'').brews,
> child: Scaffold(...
> body: BrewList(),)

Related

Flutter and firestore web app - Assertion failed: Map =! null is not true

I'm trying to create a chart on a Flutter web app by accessing data from Cloud Firestore.
However, it can't seem to extract and map the details from Firestore.
Firebase console
main.dart
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
);
}
}
home.dart
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:inglesy/items.dart';
import 'package:charts_flutter/flutter.dart' as charts;
class Home extends StatefulWidget {
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<charts.Series<Item, String>>? _seriesBarData; //Try (dynamic,String)
List<Item>? myData;
_generateData(myData) {
print("_generateData worked");
_seriesBarData?.add(
charts.Series(
domainFn: (Item item, _) => item.itemstring.toString(),
measureFn: (Item item, _) => item.itemvotes,
id: 'Items',
data: myData,
),
);
}
#override
Widget build(BuildContext context) {
print("returning AppBar/scaffold now");
return Scaffold(
appBar: AppBar(
title: const Text("This is a title."),
foregroundColor: Colors.pink,
),
body: _buildBody(context),
);
}
Widget _buildBody(context) {
print("Doing _buildBody now");
final Stream<QuerySnapshot> _userStream =
FirebaseFirestore.instance.collection("poll").snapshots();
return StreamBuilder<QuerySnapshot>(
stream: _userStream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Something went wrong');
} else {
List<Item> item = snapshot.data!.docs
.map((DocumentSnapshot document) =>
Item.fromMap(document.data() as Map<String, dynamic>))
.toList();
return _buildChart(context, item);
}
},
);
}
Widget _buildChart(BuildContext context, List<Item> item) {
myData = item;
_generateData(myData);
return Padding(
padding: EdgeInsets.all(8.0),
child: Container(
child: Center(
child: Column(
children: [
Text("This is a text"),
SizedBox(height: 10.0),
Expanded(
child: charts.BarChart(
_seriesBarData!,
animate: true,
animationDuration: const Duration(seconds: 2),
),
)
],
),
),
),
);
}
}
items.dart
class Item {
final String? itemstring;
final int? itemvotes;
Item({this.itemstring, this.itemvotes});
Item.fromMap(Map<String, dynamic> map)
: assert(map['itemstring'] != null),
assert(map['itemvotes'] != null),
itemstring = map['itemstring'],
itemvotes = map['itemvotes'];
#override
String toString() {
return "Item string: $itemstring | Item votes: $itemvotes";
}
}
It shows this error
PS, I've already done the necessary set-up i.e. I've already installed Firebase CLI and have it generated firbase_options.dart
PPS, I have also already set up Firebase (anonymous) authentication and it works with no errors. But for now, I'm not using it and I'm automatically running home.dart to focus on the Firebase database aspect.
Why don’t you try making the Item.fromMap method a regular factory method like:
factory Item.fromMap(Map<String, dynamic> map) {
return Item(
itemstring = map['itemstring'] ?? '',
itemvotes = map['itemvotes'] ?? ''
);
}

Why calling an async function whose defination is given in another program returns null or Future<type> instance for the first time as output?

Hello Im very to the flutter framework, so please let me know if im going wrong anywhere and the appropriate way of doing the things.
this is a drawerPage.dar file
In this file im trying to call a function getData for retrieving the data from firebase,this fucntion is in Database.dart file.
Database.dart
In the Database.dart file i wrote the getData function inside which im retrieving a particular record from the firebase and storing in a global variable. And then im trying to print the global variable in the drawerPage.dart file.But here when ever i run the program, for the first time the variable is having a null value and upon hot reload the actual value is getting stored in the variable.Please let me know how can i get rid of this problem.
output
drawerPageOutput
drawerPage.dart
import 'package:attendee/constants.dart';
import 'package:attendee/models/userdeails.dart';
import 'package:attendee/pages/profile.dart';
import 'package:attendee/services/authentication_service.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:attendee/services/database.dart';
import 'package:provider/provider.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:attendee/pages/userdetails.dart';
class StudentDashboard extends StatefulWidget {
#override
_StudentDashboardState createState() => _StudentDashboardState();
}
class _StudentDashboardState extends State<StudentDashboard> {
userdetails userdetail;
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
final AuthenticationService _auth = AuthenticationService();
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
DatabaseService().getData('email');
final drawerHeader = UserAccountsDrawerHeader(
accountName: Text(userName),
accountEmail: Text('${result}'),
currentAccountPicture
: CircleAvatar(
child: FlutterLogo(size: 42.0),
backgroundColor: Colors.white,
);
final drawerItems = ListView(
children: <Widget>[
drawerHeader,
ListTile(
title: Row(
children: <Widget>[
Icon(Icons.perm_identity_outlined),
Text(' Profile'),
],
),
onTap: () => Navigator.of(context).push(MaterialPageRoute(builder: (context)=>Profile())),
),
ListTile(
title: Text('To page 2'),
onTap: () => Navigator.of(context).push(_NewPage(2)),
),
ListTile(
title:Row(
children: <Widget>[
Icon(Icons.exit_to_app_rounded),
Text(' Logout'),
],
),
onTap: () async {
await _auth.signOut();
Navigator.of(context).pushNamed('/homepage');
},
),
],
);
return StreamProvider<List<userdetails>>.value(
value: DatabaseService().students,
initialData: [],
child: SafeArea(
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.lightGreen,
title: Text('Student Welcome'),
actions: <Widget>[
TextButton.icon(
onPressed: () async {
await _auth.signOut();
Navigator.of(context).pushNamed('/homepage');
},
icon: Icon(Icons.person),
label: Text('Logout'))
],
),
body:
UserDetails(),
drawer: GestureDetector(
onTap: display,
child: Drawer(
child: drawerItems,
),
),
),
),
);
}
display() async{
await DatabaseService().getData('email');
}
}
// <Null> means this route returns nothing.
class _NewPage extends MaterialPageRoute<Null> {
_NewPage(int id)
: super(builder: (BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Page $id'),
elevation: 1.0,
),
body: Center(
child: Text('Page $id'),
),
);
});
}
database.dart
import 'package:attendee/models/userdeails.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_icons/flutter_icons.dart';
import '../constants.dart';
class DatabaseService{
final String uid;
DatabaseService({this.uid});
//collection reference
final CollectionReference user_details=FirebaseFirestore.instance.collection('users');`
final CollectionReference tutor_details` `=FirebaseFirestore.instance.collection("tutors");`
Future updateStudentData(String fullname,String mobilenumber,String `email,String rollno,String tutorid,String role) async {`
return await user_details.doc(uid).set({
'fullname' : fullname,
'mobilenumber': mobilenumber,
'email' : email,
'rollno': rollno,
'tutorid': tutorid,
'role' : role,//FMERT series
});
}
Future updateTutorData(String fullname,String mobilenumber,String `email,String rollno,String tutorid,String role) async {`
return await tutor_details.doc(uid).set({
'fullname' : fullname,
'mobilenumber': mobilenumber,
'email' : email,
'rollno': rollno,
'tutorid': tutorid,
'role' : role,//FMERT series
});
}
//studentDetails from snapshot
List<userdetails> _studentDetailsFromSnapshot(QuerySnapshot snapshot){
return snapshot.docs.map((doc){
return userdetails(
fullname: doc.data()['fullname'] ?? '',
mobilenumber: doc.data()['mobilenumber'] ?? '',
email: doc.data()['email'] ?? '',
rollno: doc.data()['rollno'] ?? '',
tutorid: doc.data()['tutorid'] ?? '',
//role: doc.data()['role'] ?? '',
);
}).toList();
}
//get students stream
Stream<List<userdetails>> get students {
return user_details.snapshots()
.map(_studentDetailsFromSnapshot);
}
//tutorsDetails from snapshot
List<userdetails> _tutorDetailsFromSnapshot(QuerySnapshot snapshot){
return snapshot.docs.map((doc){
return userdetails(
fullname: doc.data()['fullname'] ?? '',
mobilenumber: doc.data()['mobilenumber'] ?? '',
email: doc.data()['email'] ?? '',
rollno: doc.data()['rollno'] ?? '',
tutorid: doc.data()['tutorid'] ?? '',
);
}).toList();
}
//get tutors stream
Stream<List<userdetails>> get tutors {
return user_details.snapshots()
.map(_studentDetailsFromSnapshot);
}
void display() {
tutor_details.get().then((querySnapshot) {
querySnapshot.docs.forEach((result) {
print(result.data());
});
});
}
getData (String string) async{
String userId = await FirebaseAuth.instance.currentUser.uid;
final document = isTutor ? `FirebaseFirestore.instance.doc('tutors/$userId') :`
await FirebaseFirestore.instance.doc('users/$userId');
document.get().then((DocumentSnapshot) async {
if(string =='role') {
checkRole = DocumentSnapshot.data()[string].toString();
print('$checkRole inside getData Function');
//return checkRole;
print(checkRole);
}
else {
print(result);
result = await DocumentSnapshot.data()[string].toString();
print('${DocumentSnapshot.data()[string].toString()} in the `database else block');`
//return result;
}
//print(document("name"));
});
}
}
After changes
terminaloutput
draweroutput
""when ever i run the program, for the first time the variable is having a null value and upon hot reload the actual value is getting stored in the variable""
When we try to get data from http / https request, it takes some time. Meanwhile the page gets loaded and you get null values.
You can use Provider package to resolve this issue, or try the below code. Please add the below code in your drawerPage.dart.
What I have done below is made getData() return type. Only on receiving a value from this function, _loadOnce will change to false & final screen will be shown.
Database.dart
Future<bool> getData (String string) async{
String userId = await FirebaseAuth.instance.currentUser.uid;
final document = isTutor ? `FirebaseFirestore.instance.doc('tutors/$userId') :`
await FirebaseFirestore.instance.doc('users/$userId');
document.get().then((DocumentSnapshot) async {
if(string =='role') {
checkRole = DocumentSnapshot.data()[string].toString();
print('$checkRole inside getData Function');
//return checkRole;
print(checkRole);
return true;
}
else {
print(result);
result = await DocumentSnapshot.data()[string].toString();
print('${DocumentSnapshot.data()[string].toString()} in the `database else block');`
//return result;
return false;
}
//print(document("name"));
});
}
}
/// create a new variable.
bool _loadOnce = true;
/// shift your code `DatabaseService().getData('email');`
#override
void didChangeDependencies() {
if(_loadOnce == true) {
DatabaseService().getData('email').then((value) {
if(value == true){
setState(() {
_loadOnce = false;
});
} else {
/// you can write your code here
setState(() {
_loadOnce = false;
});
}
)}
}
super.didChangeDependencies();
}
Below code will show a spinner till the time all the code gets executed and values are retreived.
/// in your main page under Scaffold
body: _loadOnce == true
? Center(
child: CircularProgressIndicator(
backgroundColor: Theme.of(context).primaryColor,
),
)
: UserDetails(),

Why is the data I pulled from firebase coming from null?

Patients model dart file;
import 'package:flutter/material.dart';
class Patients {
String patientId;
String nurseId;
String username;
DateTime date;
int age;
List<String> diseases;
//final fotograf olacak
Patients({#required this.patientId,this.nurseId,this.date,this.username,this.age,this.diseases});
factory Patients.fromJson(Map<String, dynamic> json){
return Patients(
patientId: json["patientId"],
nurseId: json["nurseId"],
username: json["username"],
date: json["date"],
age: json["age"],
diseases: json["diseases"],
);
}
Map<String,dynamic> toMap(){
return {
"patientId": patientId,
"nurseId" : nurseId,
"username" : username,
"date" : date,
"age" : age,
"diseases" : diseases,
};
}
}
PatientsProvider dart file;
import 'package:flutter/material.dart';
import 'package:imlearningfirebase/model/patients.dart';
import 'package:uuid/uuid.dart';
import 'package:imlearningfirebase/services/fireStoreService.dart';
class PatientsProvider with ChangeNotifier{
final fireStoreService = FireStoreService();
String _patientId;
String _nurseId;
DateTime _date;
String _username;
int _age;
List<String> _diseases;
var uuid = Uuid();
///Getters
String get username =>_username;
int get age => _age;
List<String> get diseases => _diseases;
DateTime get date => _date;
Stream<List<Patients>> get getPatients => fireStoreService.getEntries();
savePatient(int agee,String usernamee,List<String> diseasess){
if(_nurseId == null){
///add
var newPatient = Patients(patientId: uuid.v1(),nurseId:fireStoreService.getCurrentUserId().toString(),date:DateTime.now(),username: usernamee,age: agee,diseases: diseasess);
print(newPatient.username);
fireStoreService.setPatients(newPatient);
}else{
var updatedPatients = Patients(patientId: uuid.v1(),nurseId:fireStoreService.getCurrentUserId().toString(),date:DateTime.now(),username: usernamee,age: agee,diseases: diseasess);
fireStoreService.setPatients(updatedPatients);
}
}
}
FireStoreService dart file;
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
/// Local Importlar
import '../model/patients.dart';
class FireStoreService{
FirebaseFirestore _db = FirebaseFirestore.instance;
final FirebaseAuth auth = FirebaseAuth.instance;
///Get Entries
Stream<List<Patients>> getEntries(){
return _db
.collection("patients")
.snapshots()
.map((snapshot) => snapshot.docs
.map((doc) => Patients.fromJson(doc.data()))
.toList());
}}
Home screen;
import 'package:flutter/material.dart';
import 'package:imlearningfirebase/provider/patienstProvider.dart';
import 'package:provider/provider.dart';
class HomePage extends StatelessWidget{
#override
Widget build(BuildContext context) {
final patientsProvider = Provider.of<PatientsProvider>(context);
return Scaffold(
appBar: AppBar(
title: Text("Patients"),
),
floatingActionButton: Padding(
padding: const EdgeInsets.fromLTRB(0, 0, 0, 50.0),
child: FloatingActionButton(
onPressed: () async {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => AddPatient()),
);
},
child: Icon(
Icons.add,
color: Colors.blueAccent,
),
backgroundColor: Colors.green,
),
),
body:StreamBuilder<List<Patients>>(
stream: patientsProvider.getPatients,
builder: (context,snapshot){
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context,index){
return ListTile(
trailing:
Icon(Icons.edit, color: Theme.of(context).accentColor),
title: Text('${DateTime.now()}'
),
);
}
);
}
)
);
}
}
I am trying to create a system where a person has to register and register another person. I created a model so that the registered person creates the profile of the other person. The name of this model is patients. I use the provider package to access patients functions. I have created a function named take patients in Firestore and put it in the patient provider. Finally, I call this on the Home page. but the length came null. I can not see the error I would be glad if you help.
I didn't use your FireStoreService() class. This might be a bit messy but it worked for me. let me know if it works.
Try this:
class PatientsProvider with ChangeNotifier {
...
List<Patients> _patients = [];
// ///Getters
...
// Stream<List<Patients>> get getPatients => fireStoreService.getEntries();
List<Patients> get getPatients => _patients;
FirebaseFirestore _fs = FirebaseFirestore.instance;
StreamSubscription<QuerySnapshot> _stream;
PatientsProvider() {
_stream = _fs.collection('patients').snapshots().listen((snapshot) {
_patients = [];
snapshot.docs.forEach((queryDocumentSnapshot) {
_patients.add(Patients.fromJson(queryDocumentSnapshot.data()));
});
notifyListeners();
});
}
#override
void dispose() {
super.dispose();
_stream.cancel();
}
// savePatient(int agee, String usernamee, List<String> diseasess) {
...
// }
}
Then instead if creating a streambuilder, the provider will update the list when the data changes:
#override
Widget build(BuildContext context) {
PatientsProvider _provider = Provider.of<PatientsProvider >(context);
return Scaffold(
body: ListView.builder(
itemCount: _provider.getPatients.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
trailing: Icon(Icons.edit, color: Theme.of(context).accentColor),
title: Text('${...}'),
);
},
),
);
}
To get more information on the listener see this documentation:
https://firebase.google.com/docs/firestore/query-data/listen

What does this statemement mean in Future class in dart : FutureOr<R> Function(dynamic) onValue

Future<R> then<R>(FutureOr<R> onValue(T value), {Function onError});
Could someone please in simple language explain what this syntax means [ FutureOr Function(dynamic) onValue ]
FutureOr<R> Function(dynamic) onValue means:
onValue is a Function that receives a dynamic and can return Future<R> or R
Here is an example to see how you can pass asynchronous or synchronous functions to then:
Future<int> fetchNumber() async {
print("fetch number");
Future.delayed(Duration(seconds: 3));
return 1;
}
String getText(int value) {
return "one = $value";
}
Future<String> fetchText(int value) async {
print("fetch text");
Future.delayed(Duration(seconds: 3));
return "one = $value";
}
void main() {
Future<int> firstNumber = fetchNumber();
Future<String> firstNumberText = firstNumber.then(getText);
firstNumberText.then(print);
Future<int> secondNumber = fetchNumber();
Future<String> secondNumberText = secondNumber.then(fetchText);
secondNumberText.then(print);
// This is the same but with anonymous function calls:
Future<int> firstNumber = fetchNumber();
Future<String> firstNumberText = firstNumber.then((value) {
return getText(value);
});
firstNumberText.then((text) {
print(text);
});
Future<int> secondNumber = fetchNumber();
Future<String> secondNumberText = secondNumber.then((value) {
return fetchText(value);
});
secondNumberText.then((text) {
print(text);
});
}
Output:
I/flutter ( 8169): fetch number
I/flutter ( 8169): fetch number
I/flutter ( 8169): one = 1
I/flutter ( 8169): fetch text
I/flutter ( 8169): one = 1
As the documentation description explains the FutureOr will either return the value you expect or a Future that you can await on. Take a look at the functions of this example, copy the code and try it yourself:
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.orange,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin{
AnimationController _animationController;
#override
void initState() {
_animationController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 500),
);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Stackoverflow playground'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: () => printString(),
child: Text('Without await'),
),
RaisedButton(
onPressed: () => printStringWithAwait(),
child: Text('With await'),
),
],
),
)
);
}
void printString() {
String string = newString();
print('Without await $string');
}
void printStringWithAwait() async {
String string = await newString();
print('With await $string');
}
FutureOr<String> newString(){
return 'FutureOr';
}
}

Flutter Retrieve Data from Firebase

I tried this tutorial
https://www.youtube.com/watch?v=ZiagJJTqnZQ
but my data didn't show, the length is still showing 0
This is my firebase https://i.imgur.com/D6kBpp8.png
Code
questions.dart
class Questions {
String question, questioner, status;
Questions(this.question, this.questioner, this.status);
}
timeline.dart
import 'package:flutter/material.dart';
import 'questions.dart';
import 'package:firebase_database/firebase_database.dart';
class TimeLine extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return _TimeLineState();
}
}
class _TimeLineState extends State<TimeLine> {
final primaryColor = const Color(0xFF006FB9);
final bgColor = const Color(0xFFFEFEFE);
List<Questions> questionsList = [];
#override
void initState() {
super.initState();
DatabaseReference questionsRef = FirebaseDatabase.instance.reference().child("Questions");
questionsRef.once().then((DataSnapshot snap)
{
var KEYS = snap.value.keys;
var DATA = snap.value;
questionsList.clear();
for(var individualKey in KEYS) {
Questions questi = new Questions(
DATA[individualKey]['question'],
DATA[individualKey]['questioner'],
DATA[individualKey]['status'],
);
questionsList.add(questi);
}
setState(() {
print('Length : $questionsList.length');
});
});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 1,
title: Text('Discover'),
backgroundColor: primaryColor,
),
backgroundColor: bgColor,
body: Container(
child: Text(
questionsList.length.toString()
)
/*questionsList.length == 0 ? new Text("No Blog Post Available") : new ListView.builder(
itemCount: questionsList.length,
itemBuilder: (_, index) {
return QuestionsGrid(questionsList[index].question, questionsList[index].questioner, questionsList[index].status);
}
),*/
),
);
}
Widget QuestionsGrid(String question, String questioner, String status) {
return new Container(
height: 1000,
width: 1000,
child: Text(
question
),
);
}
}
Your code is perfect but you have to change in to your firebase code line like
DatabaseReference questionsRef = FirebaseDatabase.instance.reference().child("questions");
Instand of
DatabaseReference questionsRef = FirebaseDatabase.instance.reference().child("Questions");
Thanks

Resources