i want to create a listview with firebase in flutter that will show title subtitle and image and when user click on listview that will open a webview - firebase

I sm creating a flutter app where i want to create a listview with firebase in flutter that will show title subtitle and image and when user click on listview that will open a webview but I want the web view URL should come from the firebase title subtitle and the image part already working I stuck in the URL part please help how to do this
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:watched_movie_list/Widget/webviewx.dart';
class ListviewPage extends StatefulWidget {
final firBaseLists;
final String webviewTitle;
final String weburl;
ListviewPage(
{this.firBaseLists, required this.webviewTitle, required this.weburl});
#override
_ListviewPageState createState() => _ListviewPageState();
}
class _ListviewPageState extends State<ListviewPage> {
#override
Widget build(BuildContext context) {
return StreamBuilder(
stream: FirebaseFirestore.instance.collection('listview').snapshots(),
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData) {
return Center(
child: CupertinoActivityIndicator(
radius: 20,
),
);
}
return Scaffold(
appBar: AppBar(
title: Text(
' नवीनतम सूचनाएं',
style: TextStyle(color: Colors.black),
),
leading: BackButton(color: Colors.black),
backgroundColor: Colors.white,
),
body: Container(
height: 800,
color: Color(0xfff5f5f5),
child: ListView(
children: snapshot.data!.docs.map((DocumentSnapshot document) {
Map<String, dynamic> data =
document.data()! as Map<String, dynamic>;
return InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => InAppWebViewx(
title: widget
.firBaseLists["${data['titletext']}"],
url: widget.firBaseLists("${data['url']}"),
)));
},
child: Container(
height: 150,
decoration: BoxDecoration(
color: Colors.lightGreen,
borderRadius: BorderRadius.circular(18)),
margin:
EdgeInsets.only(top: 8, right: 12, left: 12, bottom: 2),
child: Row(
children: [
Container(
padding: const EdgeInsets.only(top: 15, left: 20),
height: 150,
width: 330,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Image.network(
"${data['img']}",
height: 40,
width: 40,
),
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
"${data['titletext']}",
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text(
"${data['subtitle']}",
maxLines: 2,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
],
),
),
],
),
),
);
}).toList(),
),
),
);
},
);
}
}```

You should use Listview.builder instead of Listview. Inside the Listview.builder you could capture the data with index of the itemBuilder and pass it to the WebView. Here's the link to get started on Listview.builder https://www.geeksforgeeks.org/listview-builder-in-flutter/

Related

How to put different images and redirect users to other pages in ListView Builder?

Writing a code in Flutter right now and I can display a database with ListView.
However, I want to put pictures of the destination according to its location so I was wondering how to put different images for each different item? The same goes for the onTap void callback function as well. I want each list item to go to different pages where further details of the destination is given.
Code:
class _DispDestState extends State<DispDest> {
List<AllDestinations> destinationsList = [];
#override
void initState() {
super.initState();
DatabaseReference referenceAllCourses = FirebaseDatabase.instance
.reference()
.child('Database')
.child('Destinations');
referenceAllCourses.once().then(((DataSnapshot dataSnapshot) {
destinationsList.clear();
var keys = dataSnapshot.value.keys;
var values = dataSnapshot.value;
for (var key in keys) {
AllDestinations allDestinations = new AllDestinations(
values[key]['name'],
values[key]['description'],
values[key]['category'],
);
if (allDestinations.category.toString() == 'Destination')
destinationsList.add(allDestinations);
}
setState(() {});
}));
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: EdgeInsets.fromLTRB(20, 5, 20, 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Come and Explore",
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 14,
fontStyle: FontStyle.italic,
fontWeight: FontWeight.w500,
letterSpacing: 0.5,
),
),
SizedBox(height: 15),
Expanded(
child: SingleChildScrollView(
child: Column(children: <Widget>[
destinationsList.length == 0
? Center(
child: Text(
"Loading...",
style: TextStyle(fontSize: 15),
))
: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: destinationsList.length,
itemBuilder: (_, index) {
return DestinationCard(
title: destinationsList[index].destname,
onTap: () {},
img: 'assets/icons/temp.png');
})
]),
),
),
])));
}
}
class DestinationCard extends StatelessWidget {
final String title, img;
final VoidCallback onTap;
const DestinationCard({
Key? key,
required this.title,
required this.img,
required this.onTap,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
width: 400,
height: 190,
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(15, 155, 0, 0),
width: 350,
height: 190,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
image: DecorationImage(
image: AssetImage(img), fit: BoxFit.cover),
),
child: Text(
title,
style: TextStyle(
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.bold),
),
),
],
),
),
),
);
}
}
You should add a parameter named imagePath to AllDestinations class. So when you use DestinationCard in ListView.builder, you can add:
return DestinationCard(
title: destinationsList[index].destname,
onTap: () {},
img: destinationsList[index].imagePath,
);

Error is not showing after scanning a item thats not on the firestore database

I did this personal project of mine where a barcode scanner would scan for data inside firestore database. I have this problem when I scanned a barcode thats not on the database it wont show the error message is just shows a empty scan item container which I made. Let me know if someone can figure why. I tried everything still couldnt fix it.
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance
.collection("products")
.where("barcode", isEqualTo: '$barcodeScanRes')
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Dialog(
child: Container(
height: 300,
child: Text('Product Not Found'),
),
);
} else {
return Dialog(
child: Container(
height: 350,
child: Column(children: [
Container(
height: 350,
width: 165,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
DocumentSnapshot products =
snapshot.data!.docs[index];
return ScanCard(products: products);
},
)),
]),
),
);
#Scan Card
class ScanCard extends StatelessWidget {
const ScanCard({
Key? key,
required this.products,
}) : super(key: key);
final DocumentSnapshot products;
#override
Widget build(BuildContext context) {
final user = FirebaseAuth.instance.currentUser;
String _userId = user!.uid;
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: EdgeInsets.all(10.0),
height: 180,
width: 160,
decoration: BoxDecoration(
color: Colors.blueAccent,
borderRadius: BorderRadius.circular(16)),
child: Image.network(products['img']),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 20.0 / 4),
child: Text(
products['name'],
style: TextStyle(
color: Colors.blueGrey,
fontSize: 18,
),
),
),
Column(
children: [
Text(
"Size: " + products['size'],
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14, color: Colors.brown),
),
SizedBox(
width: 30,
),
],
),
Row(
children: [
Text(
"\tRs. " + products['price'],
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
),
SizedBox(
width: 40,
),
Icon(
Icons.add_shopping_cart,
color: Colors.black,
size: 25,
),
],
),
SizedBox(
width: 10,
),
SizedBox(
child: Padding(
padding: const EdgeInsets.all(10),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0)),
color: Colors.red,
child: Text(
"Add to cart",
style: TextStyle(color: Colors.white),
),
onPressed: () {
DocumentReference documentReference = FirebaseFirestore.instance
.collection('userData')
.doc(_userId)
.collection('cartData')
.doc();
documentReference.set({
'uid': FirebaseAuth.instance.currentUser!.uid,
'barcode': products['barcode'],
'img': products['img'],
'name': products['name'],
'size': products['size'],
'price': products['price'],
'id': documentReference.id
}).then((result) {
addToCartMessage(context).then((value) => {
Navigator.pop(context)
});
}).catchError((e) {
print(e);
});
},
),
),
)
],
);
}
}
The thing is you are showing Product not found based on the condition:- !snapshot.hasData but this conditon means that data is being fetched so at this time rather show a progress indicator.
And to handle when data is not present in backend then add another condition:- if(snapshot.data.docs.isEmpty) and here show your dialogbox of Product not found...
Final Code Snippet will look like:-
if (!snapshot.hasData)
return Center(child:CircularProgressIndicator));//or return a black container if you don't want to show anything while fetching data from firestore
else if (snapshot.data.docs.isEmpty) {
return Dialog(
child: Container(
height: 300,
child: Text('Product Not Found'),
),
);
} else {
return Dialog(
child: Container(
height: 350,
child: Column(children: [
Container(
height: 350,
width: 165,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
DocumentSnapshot products =
snapshot.data!.docs[index];
return ScanCard(products: products);
},
)),
]),
),
);
}

Cant Figure Out How To display Only the post details for the post I have clicked on

So I have this code here and I would like to display post details from firebase for the post which I have clicked on, but instead, it lists post details for every single post in the database one after another.
Can anyone help me figure out how I can make it so that when A post is clicked, details will show for only the post which was clicked, and not for all of the posts? Any help would be greatly appreciated, thank you.
The Info I would like to display on the post is
postTitle
postDesc
postAuthor
Here is what the firebase looks like
Code Here:
import 'package:tennis_event_app/services/crud.dart';
import 'package:tennis_event_app/views/create_blog.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
CrudMethods crudMethods = new CrudMethods();
QuerySnapshot? blogSnapshot;
#override
void initState() {
crudMethods.getData()?.then((result) {
blogSnapshot = result;
setState(() {});
});
super.initState();
}
Widget blogsList() {
return Container(
child: ListView.builder(
padding: EdgeInsets.only(top: 24),
itemCount: blogSnapshot!.docs.length,
itemBuilder: (context, index) {
return BlogTile(
author: blogSnapshot!.docs[index].get('author'),
title: blogSnapshot!.docs[index].get('title'),
desc: blogSnapshot!.docs[index].get('desc'),
imgUrl: blogSnapshot!.docs[index].get('imgUrl'),
);
},
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Flutter",
style: TextStyle(fontSize: 22),
),
Text(
"Blog",
style: TextStyle(fontSize: 22, color: Colors.blue),
)
],
),
backgroundColor: Colors.transparent,
elevation: 0.0,
),
body: Container(
child: blogSnapshot != null
? blogsList()
: Container(
child: Center(
child: CircularProgressIndicator(),
))),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => CreateBlog()));
},
),
);
}
}
class BlogTile extends StatelessWidget {
final String imgUrl, title, desc, author;
BlogTile(
{required this.author,
required this.desc,
required this.imgUrl,
required this.title});
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(bottom: 16, right: 16, left: 16),
child: Stack(
children: <Widget>[
Container(
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(8)),
child: Image.network(
imgUrl,
width: MediaQuery.of(context).size.width,
fit: BoxFit.cover,
height: 170,
),
),
),
Container(
height: 170,
decoration: BoxDecoration(
color: Colors.black45.withOpacity(0.3),
borderRadius: BorderRadius.circular(6)),
),
Container(
height: 170,
width: MediaQuery.of(context).size.width,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
title,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 25, fontWeight: FontWeight.w500),
),
SizedBox(height: 4),
Text(
'$desc',
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w400),
),
SizedBox(
height: 4,
),
Text(author),
],
)),
Container(
child: SizedBox(
height: 170,
width: MediaQuery.of(context).size.width,
child: TextButton(
style: TextButton.styleFrom(
textStyle: const TextStyle(fontSize: 20),
),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => DetailPage()));
},
child: const Text(''),
),
),
),
],
),
);
}
}
class DetailPage extends StatefulWidget {
#override
_DetailPageState createState() => _DetailPageState();
}
class _DetailPageState extends State<DetailPage> {
CrudMethods crudMethods = new CrudMethods();
QuerySnapshot? blogSnapshot;
#override
void initState() {
crudMethods.getData()?.then((result) {
blogSnapshot = result;
setState(() {});
});
super.initState();
}
Widget blogsList2() {
return Container(
child: ListView.builder(
padding: EdgeInsets.only(top: 24),
itemCount: blogSnapshot!.docs.length,
itemBuilder: (context, index) {
return PageContent(
postAuthor: blogSnapshot!.docs[index].get('postAuthor'),
postTitle: blogSnapshot!.docs[index].get('postTitle'),
postDesc: blogSnapshot!.docs[index].get('postDesc'),
imgUrl: blogSnapshot!.docs[index].get('imgUrl'),
);
},
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Flutter",
style: TextStyle(fontSize: 22),
),
Text(
"Blog",
style: TextStyle(fontSize: 22, color: Colors.blue),
)
],
),
backgroundColor: Colors.transparent,
elevation: 0.0,
),
body: Container(
child: blogSnapshot != null
? blogsList2()
: Container(
child: Center(
child: CircularProgressIndicator(),
))),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => CreateBlog()));
},
),
);
}
}
class PageContent extends StatelessWidget {
final String imgUrl, postTitle, postDesc, postAuthor;
PageContent(
{required this.postAuthor,
required this.postDesc,
required this.imgUrl,
required this.postTitle});
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(bottom: 16, right: 16, left: 16),
child: Card(
child: ListTile(
title: Text(
postTitle,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 25, fontWeight: FontWeight.w500),
),
subtitle: Text(
'$postDesc',
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w400),
),
)
)
);
}
}
I also reference crud.dart in that code, so incase you need it, here it is:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:collection';
class CrudMethods {
Future<void> addData(blogData) async {
print(blogData);
FirebaseFirestore.instance
.collection("blogs")
.add(blogData)
.then((value) => print(value))
.catchError((e) {
print(e);
});
}
getData() async {
return await FirebaseFirestore.instance
.collection("blogs")
.orderBy("ts", descending: true)
.get();
}
}
Thank you again for any help!
First I would recommend to modelize your data in an object for exemple a class Article that is easier to serialize and manipulate.
Then instead of requesting another time the database you should save your data in a List<Article> for example then you only update this list on refresh from your main page. That way you don'y manipulate a QuerySnapshot or Future but just your list of objects.
Finally and to answer your question, you could simply pass the clicked item Article to your details page and only display its content. Because here, you have the same construction as your main page with the same request that is resent.
Usually you can build your route like that (adding a parameter to your details with the index you clicked on for example)
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => DetailPage(article: _data[i])));
},
Here is an article on serialization from Flutter docs, it shows how to build your model with the toMap, toJson and fromJson methods.

Undefined name 'firebase' Flutter

Hello I am trying to implement firebase authentication in my flutter app I am getting this error
Undefined name 'firebase'
Here is the code for reference:
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:multi_purpose_scope/Animation/FadeAnimation.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
Future<void>main() async{
WidgetsFlutterBinding.ensureInitialized();
}
class HomePage extends StatelessWidget {
final FirebaseApp _fbApp=Firebase.initializeApp();
final _formKey = GlobalKey<FormState>();
TextEditingController _emailController = TextEditingController();
TextEditingController _passwordController = TextEditingController();
gotoSecondActivity(BuildContext context){
final mq=MediaQuery.of(context);
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondActivity()),
);
}
#override
Widget build(BuildContext context) {
TextEditingController _emailControllerField=TextEditingController();
TextEditingController _passwordControllerField=TextEditingController();
return Scaffold(
backgroundColor: Colors.white,
body: SingleChildScrollView(
child: RaisedButton(
onPressed: () async {
gotoSecondActivity(context);
try{
FirebaseUser user=(await FirebaseAuth.instance.signInWithEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
));
if(user!=null){
Navigator.of(context).pushNamed(gotoSecondActivity(context).menu);
}
}
catch(e){
print(e);
_emailController.text='';
_passwordController.text='';
}
},
child: Container(
child: Column(
children: <Widget>[
Container(
height: 400,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/loginHeader.png'),
fit: BoxFit.fill
)
),
child: Stack(
children: <Widget>[
],
),
),
Padding(
padding: EdgeInsets.all(30.0),
child: Column(
children: <Widget>[
FadeAnimation(1.8, Container(
padding: EdgeInsets.all(5),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Color.fromRGBO(143, 148, 251, .2),
blurRadius: 20.0,
offset: Offset(0, 10)
)
]
),
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(
color: Colors.grey[100]))
),
child: TextField(
controller: _emailControllerField,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Email or Phone number",
hintStyle: TextStyle(
color: Colors.grey[400])
),
),
),
Container(
padding: EdgeInsets.all(8.0),
child: TextField(
obscureText: true,
controller: _passwordControllerField,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Password",
hintStyle: TextStyle(
color: Colors.grey[400])
),
),
)
],
),
)),
SizedBox(height: 30,),
FadeAnimation(2, Container(
height: 50,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
gradient: LinearGradient(
colors: [
Color.fromRGBO(214, 0, 27, 1),
Color.fromRGBO(214, 0, 27, 1),
]
)
),
child: Center(
child: Text("Login", style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold),),
),
)),
SizedBox(height: 70,),
FadeAnimation(1.5, Text("Forgot Password?",
style: TextStyle(
color: Color.fromRGBO(214, 0, 27, 1)),)),
],
),
)
],
),
),
)
),
);
}
}
class SecondActivity extends StatelessWidget {
gotoRegister(BuildContext context){
Navigator.push(
context,
MaterialPageRoute(builder: (context) =>Register()),
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
child: Container(
height: 174,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/patient_list.png'),
)
),
child: Stack(
children: <Widget>[
Container(
alignment: Alignment.center,
height: 128,
child: Text(
'Patient List',
style: TextStyle(
fontWeight: FontWeight.bold,fontSize: 30,
color: Colors.white
),
),
)
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
gotoRegister(context);
},
tooltip: 'Increment',
child: Icon(Icons.add),
backgroundColor: Color.fromRGBO(214, 0, 27,1),
),
),
);
}
}
class Register extends StatelessWidget {
goBack(BuildContext context) {
Navigator.pop(context);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 40),
child: Column(
children: <Widget>[
Stack(
alignment: Alignment.center,
children: <Widget>[
Image.asset('assets/images/patient_list.png'),
Text('Registration',style: TextStyle(fontWeight:FontWeight.bold,fontSize: 30,color: Colors.white),)
]
),
const SizedBox(height: 10),
const SampleTextField(hintText: 'Enter Name'),
const SizedBox(height:10),
const SampleTextField(hintText: 'Enter MR-Number'),
const SizedBox(height: 10),
const SampleTextField(hintText: 'Enter Phone Number'),
const SizedBox(height: 10),
const SampleTextField(hintText: 'Enter Hospital Name'),
const SizedBox(height:10),
FlatButton(
onPressed: () {
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
// materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
// visualDensity: VisualDensity.compact,
padding: const EdgeInsets.symmetric(vertical: 20),
color: Color.fromRGBO(214, 0, 27,1),
child: const Center(
child: Text('Register User'),
),
),
]
),
),
),
),
);
}
}
class SampleTextField extends StatelessWidget {
const SampleTextField({
this.controller,
this.hintText = '',
});
final TextEditingController controller;
final String hintText;
#override
Widget build(BuildContext context) {
return TextField(
controller: controller,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
borderSide: const BorderSide(
width: 1,
color: Colors.black54,
),
),
hintText: hintText,
hintStyle: const TextStyle(
color: Colors.black54,
),
contentPadding: const EdgeInsets.only(left: 20),
),
// textAlign: TextAlign.center, // Align vertically and horizontally
);
}
}
class ForgotPassword extends StatelessWidget{
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 40),
child: Column(
children: <Widget>[
const SizedBox(height: 10),
const SampleTextField(hintText: 'Enter Your Email'),
FlatButton(
onPressed: () {
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
padding: const EdgeInsets.symmetric(vertical: 20),
),
]
),
),
),
),
);
}
}
I googled my problem but can't seem to find the solution to my problem. I do know that there is something wrong with my initialization but i cant seem to connect the dots and find out where am i going wrong
You have to have the firebase core package added
firebase_core: ^7.0.1 (check the actual package version)
flutter pub get
and add the package to your code
import 'package:firebase_core/firebase_core.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(HomePage());
}
I fixed the issue by upgrading to a newer version of firebase_core (I went with 1.0.0)
You need to initialize your Firebase into your main method
First flutter pub get
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(HomePage());
}
Add 'firebase_core: ^1.7.0' to pubspec.yaml file. And then flutter pub get. problem will solved.
I had a similar problem. Using firebase_core : ^1.0.1 worked for me in Ubuntu.
As Shubham already mentioned you have to initialize the Firebase instance before using it - although it doesn't necessarily have to be put into main.
You can initialize it anywhere outside of the widget in which you are trying to use the Firebase instance.
Firebase lazily creates its instance (most likely via proxy pattern) because its creation is expensive.
Therefore it can't find it immediately after you are trying to reference it :)

Closure call with mismatched arguments: function '[]' in flutter

** I am getting this error**
Closure call with mismatched arguments: function '[]'
Receiver: Closure: (dynamic) => dynamic from Function 'get':.
Tried calling: []("url")
Found: [](dynamic) => dynamic
my code where I am receiving the data from firestore is this..
import 'package:flutter/material.dart';
import 'package:riyazat_quiz/services/database.dart';
import 'package:riyazat_quiz/views/create_quiz.dart';
import 'package:riyazat_quiz/widgets/widgets.dart';
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
Stream quizStream;
DatabaseService databaseService = DatabaseService(); // this is to call the getQuizData() async{
return await FirebaseFirestore.instance.collection("Quiz").snapshots();
}
Widget quizList(){
return Container(
child: StreamBuilder(
stream:quizStream ,
builder: (context,snapshort){
return snapshort.data == null ? CircularProgressIndicator(): ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount : snapshort.data.documents.length ,
itemBuilder : (context,index){ return QuizTile(url:snapshort.data.documents[index].get['url'],
title:snapshort.data.documents[index].get['title'] ,
desc: snapshort.data.documents[index].get['desc'],);}
);
}
),
);
}
#override
void initState() {
databaseService.getQuizData().then((val){
setState(() {
quizStream =val;
});
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Center(
child: appBar(context),
),
backgroundColor: Colors.transparent,
elevation: 0.0,
brightness: Brightness.light,
),
body:
Column(
children: [
quizList(),
FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => CreateQuiz()));
},
),
],
),
);
}
}
class QuizTile extends StatelessWidget {
final String url,title,desc;
QuizTile({#required this.url,#required this.title,#required this.desc});
#override
Widget build(BuildContext context) {
return Container(
child: Stack(
children: [
Image.network(url),
Container(
child: Column(
children: [
Text(title),
Text(desc),
],
),
)
],
),
);
}
}
can someone tell me where I am going wrong
ps: this is a quiz app where I am getting the data from the firestore,
using streams.
data saved on the firestore has three fields, "url", "title" "desc".
I want to retrieve them in the below widget and want to display them in a stack, but this error got me stuck in-between.
You need to do the following:
itemCount : snapshort.data.docs.length ,
itemBuilder : (context,index){
return QuizTile(url:snapshort.data.docs[index].data()['url'],
title:snapshort.data.docs[index].data()['title'] ,
desc: snapshort.data.docs[index].data()['desc'],
);
}
);
Since you are reference a collection, then you need to use docs which will retrieve a list of documents inside that collection:
https://github.com/FirebaseExtended/flutterfire/blob/master/packages/cloud_firestore/cloud_firestore/lib/src/query_snapshot.dart#L18
Then to access each field in the document, you need to call data()
The answer by #Peter Haddad is correct. Just to highlight the difference with an example from my own code:
The previous version of code which created the same error:
snapshot.data.docs[index].data["chatRoomID"]
Updated version of code which solved the error:
snapshot.data.docs[index].data()["chatRoomID"]
Updated Version:
snapshot.data[i]['Email'],
Future getRequests() async {
QuerySnapshot snapshot = await FirebaseFirestore.instance.collection("Buyer Requests").get();
return snapshot.docs;
}
body: FutureBuilder(
initialData: [],
future: getRequests(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
indexLength = snapshot.data.length;
if (snapshot.hasData)
return SizedBox(
child: PageView.builder(
itemCount: indexLength,
controller: PageController(viewportFraction: 1.0),
onPageChanged: (int index) => setState(() => _index = index),
itemBuilder: (_, i) {
return SingleChildScrollView(
child: Card(
margin: EdgeInsets.all(10),
child: Wrap(
children: <Widget>[
ListTile(
leading: CircleAvatar(
backgroundImage: AssetImage(
'assets/images/shafiqueimg.jpeg'),
),
title: Text(
snapshot.data[i]['Email'],
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w700,
color: Colors.black.withOpacity(0.7),
),
),
subtitle: Text(
snapshot.data[i]['Time'],
style: TextStyle(
color: Colors.black.withOpacity(0.6)),
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.all(Radius.circular(5)),
color: Colors.grey[200],
),
padding: EdgeInsets.all(10),
child: Text(
snapshot.data[i]['Description'],
style: TextStyle(
color: Colors.black.withOpacity(0.6)),
),
),
SizedBox(
height: 8,
),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(5)),
border: Border.all(
color: Colors.grey[300])),
child: ListTile(
leading: Icon(Icons.category_outlined),
title: Text(
'Category : ${snapshot.data[i]['Category']}',
style: TextStyle(
fontSize: 14,
color: Colors.grey,
),
),
),
),
SizedBox(height: 8),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(5)),
border: Border.all(
color: Colors.grey[300])),
child: ListTile(
leading: Icon(Icons.location_pin),
title: Text(
snapshot.data[i]['Location'],
style: TextStyle(
fontSize: 14,
color: Colors.grey,
),
),
),
),
SizedBox(height: 8),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(5)),
border: Border.all(
color: Colors.grey[300])),
child: ListTile(
leading: Icon(
Icons.attach_money,
color: kGreenColor,
),
title: Text(
'Rs.${snapshot.data[i]['Budget']}',
style: TextStyle(
fontSize: 14,
color: kGreenColor,
),
),
),
),
SizedBox(height: 8),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(5)),
border: Border.all(
color: Colors.grey[300])),
child: ListTile(
leading: Icon(Icons.timer),
title: Text(
'Duration : ${snapshot.data[i]['Duration']}',
style: TextStyle(
fontSize: 14,
color: Colors.grey,
),
),
),
),
SizedBox(
height: 35,
),
RaisedButton(
padding: EdgeInsets.symmetric(vertical: 10),
child: Text('Send Offer'),
textColor: Colors.white,
color: Colors.green,
onPressed: () {
// Respond to button press
},
),
SizedBox(
height: 15,
),
Center(
child: Text(
"${i + 1}/$indexLength",
style: TextStyle(fontSize: 13),
),
),
],
),
),
],
),
),
);
},
),
);
else
return Center(
child: Text("Null"),
);
},
),
Given that you are referencing a collection, you must use docs to acquire a list of the documents included in that collection:
https://github.com/FirebaseExtended/flutterfire/blob/master/packages/cloud firestore/cloud firestore/lib/src/query snapshot.dart#L18
then you must call data() in order to access each field in the document.

Resources