All course files for the Flutter & Firebase tutorial playlist on The Net Ninja YouTube channel
Each lesson in the playlist has it's own code in it's own branch. To see the code for lesson 7, for example, you would select the lesson-7 branch.
All course files for the Flutter & Firebase tutorial playlist on The Net Ninja YouTube channel
i have problem in sign_in.dart
the import 'package:coffe_cafe/services/auth.dart';
the flutter say remove unused import
and another
_final AuthService auth = AuthService();
undefined class 'AuthService'.
Try changing the name to the name of an existing class, or creating a class with the name 'AuthService'.dart(undefined_class)
What up bros..
.
I just finished following 'Flutter & Firebase App Tutorial #15 - Loading Widget'
I noticed the error comment based on what we wrote in the coding.
.
Question: How to change the sign-in/register comment the same as comment on console?
AuthResult is deprecated and is now UserCredential
FirebaseUser is now User
I want to add more fields to User model, for example, name, sex, job title, age, etc. Here is my code:
Stream<User> get user {
// return _auth.onAuthStateChanged.map(_fromFirebaseUser);
final theUser = _auth.onAuthStateChanged.map((firebaseUser) {
final result = Firestore.instance.collection("users")
.document(firebaseUser.uid).snapshots().map((snapshot) {
return User(
uid: user.uid,
name: snapshot.data['name'],
email: user.email,
age: snapshot.data['age'],
gender: snapshot.data['gender']
);
}
return result;
});
return theUser;
}
The basic idea is I will get the data from users collection and populate the User model. But I got the following error message:
The argument type 'Stream<Stream>' can't be assigned to the parameter type 'Stream'.
Need your advice. Thanks.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:googletestconnection/models/userData.dart';
class DatabaseService{
final String uid;
DatabaseService ({this.uid});
//collection Refferences
final CollectionReference userDataCollection = FirebaseFirestore.instance.collection('userData');
Future updateUserData(String sugars, String name, int strength) async {
return await userDataCollection.doc(uid).set({
'sugars': sugars,
'name': name,
'strength': strength,
});
}
//User data collection
List _userDataListFromSnapshot(QueryDocumentSnapshot snapshot) {
return snapshot.get('doc').map((doc) {
return UserDataList(
name: doc.data['name'] ?? '',
strength: doc.data['strength'] ?? 0,
sugars: doc.data['sugars'] ?? '0'
);
});
}
//get user profile data
Stream<QueryDocumentSnapshot<List>> get userData {
return userDataCollection.snapshots()
.map(_userDataListFromSnapshot);
}
}
lib/screens/home/home.dart:16:32: Error: The argument type 'Stream<QueryDocumentSnapshot<List>>' can't be assigned to the parameter type 'Stream<QuerySnapshot>'.
The code final Function toggleView; SignIn({this.toggleView});
and
final Function toggleView; Register({this.toggleView});
are both returning this error:
The parameter 'toggleView' can't have a value of 'null' because of its type, but the implicit default value is 'null'. (Documentation) Try adding either an explicit non-'null' default value or the 'required' modifier.
I got this error after I we set the (dynamic result = await _auth.signInAnon(); in sign_in.dart )
and I add this code to the main.dart to initialize firebase
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: FirebaseOptions(apiKey: "XXXX",
appId: "",
messagingSenderId: "",
projectId: "XXXX")
);
and it works , my issue why we should do that, cause in the course it works without adding these lines.
I followed the tutorials thoroughly, but loading widget is shown infinitely. I printed a message in output before if statement and it shows that snapshot has no data and so it goes to else statement and shows loading widget infinitely.
your code
This issue has been faced with some more coders as can be seen in comments for video 25
When I register a new user this error shows up:
W/Firestore(22296): (22.1.1) [Firestore]: Write failed at brews/...: Status{code=PERMISSION_DENIED, description=Missing or insufficient permissions., cause=null}
My Firestore rules:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, update, write: if request.auth != null;
}
}
}
The brews collection doesn't get created. What am I doing wrong?
I am working up to lesson 23, everything is perfect in the first time.
But when I restart and re-build, I got this error. I tried update Google play service of emulator but it still not working.
Can anyone help me with this?
Anyway, thank you for everything you give us, Shaun. You are amazing!
W/DynamiteModule( 3465): Local module descriptor class for providerinstaller not found. I/TetheringManager( 3465): registerTetheringEventCallback:com.mtlu_brew_crew I/DynamiteModule( 3465): Considering local module providerinstaller:0 and remote module providerinstaller:0 W/ProviderInstaller( 3465): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
wrapper.dart file is missing in lib
value: (_currentStrength ?? userData.strength).toDouble()
This code is giving an error because of userData.strength.
the brew tile or order tile on my version of your code is not showing a value on my
subtitle. can you check my repo at
https://github.com/ernestsheldon/grub_retriever
see if you can spot why i am getting a null value on subtitle of the listtile but the value is in the var and saves to db thanks man.
I have been following the netninja tutorial on Firebase Auth but I have run into a problem. My signing is working well and the listener in my wrapper send the user directly to my homepage after signing in. However, my register page doesnt send the user onwards despite successfull registration. I have to update with hotrestart for the homescreen to appear.
Any and all help on this would be appreciated.
Here is my registration page:
class SignUpWidget extends StatefulWidget {
@override
SignUpState createState() => SignUpState();
}
class SignUpState extends State<SignUpWidget> {
final AuthService _auth = AuthService();
final _formKey = GlobalKey<FormState>();
String error = '';
bool loading = false;
// text field state
String displayName = '';
String email = '';
String password = '';
@override
Widget build(BuildContext context) {
return loading
? Loading()
: Scaffold(
backgroundColor: const Color.fromARGB(255, 69, 90, 100),
key: _mainScaffoldKey,
body: SafeArea(
child: Container(
alignment: Alignment.center,
padding: const EdgeInsets.only(top: 40, left: 20, right: 20),
child: Column(
children: <Widget>[
Card(
elevation: 2.0,
color: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0),
),
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
Container(
padding:
const EdgeInsets.only(top: 30, bottom: 30),
child: const Icon(
FontAwesomeIcons.bookOpen,
size: 60,
color: Color.fromARGB(255, 69, 90, 100),
),
),
Padding(
padding: const EdgeInsets.only(
top: 1.0,
bottom: 1.0,
left: 25.0,
right: 25.0,
),
child: TextFormField(
validator: (val) =>
val!.isEmpty ? 'Enter your name' : null,
onChanged: (val) {
setState(() => displayName = val);
},
style: const TextStyle(
fontFamily: "Montserrat",
fontSize: 16.0,
color: Colors.black,
),
decoration: const InputDecoration(
border: InputBorder.none,
icon: Icon(
FontAwesomeIcons.solidUser,
color: Color.fromARGB(255, 69, 90, 100),
size: 22.0,
),
hintText: "Enter name",
hintStyle: TextStyle(
fontFamily: "Montserrat",
fontSize: 18.0,
),
),
),
),
Container(
width: 250.0,
height: 1.0,
color: Colors.grey,
),
Padding(
padding: const EdgeInsets.only(
top: 5.0,
bottom: 5.0,
left: 25.0,
right: 25.0,
),
child: TextFormField(
validator: (val) =>
val!.isEmpty ? 'Enter your email' : null,
onChanged: (val) {
setState(() => email = val);
},
style: const TextStyle(
fontFamily: "Montserrat",
fontSize: 16.0,
color: Colors.black,
),
decoration: const InputDecoration(
border: InputBorder.none,
icon: Icon(
FontAwesomeIcons.solidEnvelope,
color: Color.fromARGB(255, 69, 90, 100),
size: 22.0,
),
hintText: "Enter email",
hintStyle: TextStyle(
fontFamily: "Montserrat",
fontSize: 18.0,
),
),
),
),
Container(
width: 250.0,
height: 1.0,
color: Colors.grey,
),
Padding(
padding: const EdgeInsets.only(
top: 5.0,
bottom: 5.0,
left: 25.0,
right: 25.0,
),
child: TextFormField(
validator: (val) => val!.length < 6
? 'Enter a password 6+ chars long'
: null,
obscureText: true,
onChanged: (val) {
setState(() => password = val);
},
style: const TextStyle(
fontFamily: "Montserrat",
fontSize: 16.0,
color: Colors.black,
),
decoration: const InputDecoration(
border: InputBorder.none,
icon: Icon(
FontAwesomeIcons.lock,
color: Color.fromARGB(255, 69, 90, 100),
size: 22.0,
),
hintText: "Enter password",
hintStyle: TextStyle(
fontFamily: "Montserrat",
fontSize: 18.0,
),
),
),
),
Container(
width: 250.0,
height: 1.0,
color: Colors.grey,
),
Container(
margin: const EdgeInsets.only(top: 40.0),
decoration: const BoxDecoration(
borderRadius:
BorderRadius.all(Radius.circular(5.0)),
boxShadow: <BoxShadow>[
BoxShadow(
color: AppColours.colorStart,
offset: Offset(1.0, 6.0),
blurRadius: 20.0,
),
BoxShadow(
color: AppColours.colorEnd,
offset: Offset(1.0, 6.0),
blurRadius: 20.0,
),
],
gradient: LinearGradient(
colors: [
AppColours.colorEnd,
AppColours.colorStart
],
begin: FractionalOffset(0.2, 0.2),
end: FractionalOffset(1.0, 1.0),
stops: [0.1, 1.0],
tileMode: TileMode.clamp,
),
),
child: MaterialButton(
highlightColor: Colors.transparent,
splashColor: AppColours.colorEnd,
child: const Padding(
padding: EdgeInsets.symmetric(
vertical: 10.0,
horizontal: 42.0,
),
child: Text(
"Register",
style: TextStyle(
fontFamily: "Montserrat-bold",
color: Colors.white,
fontSize: 22.0,
),
),
),
onPressed: () async {
if (_formKey.currentState!.validate()) {
setState(() => loading = true);
dynamic result = await _auth
.registerWithEmailandPassword(
displayName, email, password);
if (result == null) {
setState(() {
error = 'please supply a valid email';
loading = false;
});
}
}
},
),
),
SizedBox(
height: 20,
),
Text(
error,
style: TextStyle(
color: Colors.red,
fontSize: 14,
),
),
Padding(
padding: const EdgeInsets.only(top: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
Colors.black12,
Colors.black,
],
// ignore: use_named_constants
begin: FractionalOffset(0.0, 0.0),
// ignore: use_named_constants
end: FractionalOffset(1.0, 1.0),
stops: [0.0, 1.0],
tileMode: TileMode.clamp,
),
),
width: 100.0,
height: 1.0,
),
const Padding(
padding: EdgeInsets.only(
left: 15.0, right: 15.0),
child: Text(
"Or register with",
style: TextStyle(
color: Colors.black,
decoration: TextDecoration.none,
fontSize: 16.0,
fontFamily: "Montserrat",
),
),
),
Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
Colors.black,
Colors.black12,
],
begin: FractionalOffset(0.0, 0.0),
end: FractionalOffset(1.0, 1.0),
stops: [0.0, 1.0],
tileMode: TileMode.clamp,
),
),
width: 100.0,
height: 1.0,
),
],
),
),
Padding(
padding: const EdgeInsets.only(
top: 20,
bottom: 20,
),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
children: <Widget>[
GestureDetector(
onTap: () => {},
child: Container(
child: const Icon(
FontAwesomeIcons.facebook,
color: Color(0xFF0084ff),
size: 60,
),
),
),
GestureDetector(
onTap: () => {},
child: Container(
child: const Icon(
FontAwesomeIcons.instagram,
color: Color.fromARGB(255, 240, 58, 83),
size: 60,
),
),
),
GestureDetector(
onTap: () => {},
child: Container(
child: const Icon(
FontAwesomeIcons.twitter,
color: Color(0xFF0084ff),
size: 60,
),
),
),
GestureDetector(
onTap: () => {},
child: Container(
padding: const EdgeInsets.only(top: 5),
child: const Image(
height: 50,
width: 50,
image: AssetImage(
'images/google_logo.png'),
),
//FontAwesomeIcons.google,
//color: const Color(0xFF0084ff),
//size: 60,
),
),
],
),
),
],
),
),
),
],
),
),
),
);
}
}
Here is my wrapper:
class Wrapper extends StatelessWidget {
@override
Widget build(BuildContext context) {
final user = Provider.of<User?>(context);
//return either homepage or Login widget
if (user == null) {
return LoginWidget();
} else {
return HomePage();
}
}
}
Here is my main:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(App());
}
class App extends StatefulWidget {
@override
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: _initialization,
builder: (context, snapshot) {
if (snapshot.hasError) {
return const SomethingWentWrong();
}
if (snapshot.connectionState == ConnectionState.done) {
return const MyApp();
}
return const CircularProgressIndicator();
},
);
}
}
class SomethingWentWrong extends StatelessWidget {
const SomethingWentWrong({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: Row(
children: const <Widget>[
Text('something went wrong!'),
],
),
);
}
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return StreamProvider<User?>.value(
value: AuthService().user,
initialData: null,
child: MaterialApp(
title: 'The Book Club',
debugShowCheckedModeBanner: false,
theme: ThemeData(
canvasColor: const Color.fromARGB(255, 207, 216, 220),
fontFamily: 'Montserrat-SemiBold',
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: Wrapper(),
),
);
}
}
and finally here is my auth:
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
//auth change user stream
Stream<User?> get user {
return _auth.authStateChanges();
}
//sign in with email and password
Future logInWithEmailandPassword(String email, String password) async {
try {
UserCredential result = await _auth.signInWithEmailAndPassword(
email: email, password: password);
User? user = result.user;
return user;
} catch (e) {
print(e.toString());
return null;
}
}
//register with email and password
Future registerWithEmailandPassword(
String name, String email, String password) async {
try {
UserCredential result = await _auth.createUserWithEmailAndPassword(
email: email, password: password);
User? user = result.user;
return user;
} catch (e) {
print(e.toString());
return null;
}
}
//sign out
Future signOut() async {
try {
return await _auth.signOut();
} catch (e) {
print(
e.toString(),
);
return null;
}
}
}
let me know if more files/details are necessary in order to answer my question, I cannot understand why it is not loading the homepage properly.
While pushing logout you are actually logged out from Firebase but it won't return to authentication screen.
Error:
Exception caught by provider
The following assertion was thrown:
An exception was throw by _MapStream<FirebaseUser, User> listened by
StreamProvider, but no catchError
was provided.
Exception:
NoSuchMethodError: The getter 'uid' was called on null.
Receiver: null
Tried calling: uid
FIX:
@OverRide
Widget build(BuildContext context) {
return StreamProvider.value(
catchError: (_, __) => null,
//add above to main.dart
value: AuthService().user,
child: MaterialApp(
home: Wrapper(),
onAuthStateChanged is now refactor to authStateChanges
The following assertion was thrown:
An exception was throw by _MapStream<FirebaseUser, User> listened by
StreamProvider, but no catchError
was provided.
Exception:
NoSuchMethodError: invalid member on null: 'providerId'
The code:
onPressed: () async {
if(_formKey.currentState.validate()){
setState(() => loading = true);
dynamic result = await _auth.signInWithEmailAndPassword(email, password);
if(result == null) {
setState(() {
loading = false;
error = 'Could not sign in with those credentials';
});
}
}
}
The setState
for loading = false
is never called. Although I set the breakpoint in signInWithEmailAndPassword
, it did return null
. What could be the reason? Thanks.
this is of branch lesson 21
`
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building BrewList(dirty, dependencies: [InheritedProvider<List>], state: _BrewListState#f51fb):
The getter 'length' was called on null.
Receiver: null
Tried calling: length
User-created ancestor of the error-causing widget was:
Scaffold file:///home/ndragonx/flutterprojectsvscode/grub_retriever/grub_retriever/lib/screens/home/home.dart:26:14
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 _BrewListState.build (package:grub_retriever/screens/home/brew_list.dart:17:24)
#2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4047:27)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3941:15)
#4 Element.rebuild (package:flutter/src/widgets/framework.dart:3738:5)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
`
Use this for the query snapshot:
List _brewListFromSnapshot(QuerySnapshot snapshot){
return snapshot.docs.map((doc){
return Brew(
name: doc.get('name') ?? '',
sugars: doc.get('sugars') ?? '0',
strength: doc.get('strength') ?? 0
);
}).toList();
}
Lesson 11:
void toggleView(){
//print(showSignIn.toString());
setState(() => showSignIn = !showSignIn);
}
@override
Widget build(BuildContext context) {
if (showSignIn) {
return SignIn(toggleView: toggleView);
} else {
return Register(toggleView: toggleView);
}
}```
throws error: this expression has a type of void so it's value can't be used parameter type function
I get an error at
Navigator.pop(context)
Exception has occurred.
FlutterError (Looking up a deactivated widget's ancestor is unsafe.
At this point the state of the widget's element tree is no longer stable.
To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.)
import 'package:flutter/material.dart';
import 'package:flutter_app1/Screens/Authenticate/register.dart';
import 'package:flutter_app1/Screens/Authenticate/sign_in.dart';
class Authenticate extends StatefulWidget {
@OverRide
_AuthenticateState createState() => _AuthenticateState();
}
class _AuthenticateState extends State {
bool showSignIn=false;
void toggleview(){
setState(() => showSignIn = !showSignIn);
}
@OverRide
Widget build(BuildContext context) {
if(showSignIn){
return SignIn(toggleview:toggleview);
} else{
return Register(toggleview:toggleview); /** @/this part is not working.
} //page is not changing while clicking but when we change value
//to false manually then only page changes .but donot respond to
//click**
}
}
When I register with a new user, a new user is created in Firebase, but I get the following error message and no entry is made in the database:
W/Firestore( 7435): (21.3.0) [Firestore]: Write failed at rimu/1xxbkZLfhCe9Lukign3jyimgimo2: Status{code=PERMISSION_DENIED, description=Missing or insufficient permissions., cause=null} I/flutter ( 7435): PlatformException(Error performing setData, PERMISSION_DENIED: Missing or insufficient permissions., null)
Hi Shaun,
In lesson 26, the call to Navigator.pop(context)
(SettingsForm) doesn't close the form.
Any idea how to fix this issue?
Thanks
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.