如何使用供应商?
How to use provider?
经过几天尝试改变我的方法,我终于得到了结果。但这是我的问题:每次我重新启动应用程序时,我都有一个从 main 调用的包装器。我想在我的包装器中使用它 class:
if(FirebaseAuth.instance.currentUser.emailVerified){}
这是我目前的包装 class:
import 'package:flutter/material.dart';
import 'package:projectandroidstudiodenya/seitenleiste/homepage.dart';
import 'package:provider/provider.dart';
import 'authenticate/authenticate.dart';
import 'models/user.dart';
class Wrapper extends StatelessWidget {
static const route='/Wrapper';
@override
Widget build(BuildContext context) {
//Auth.auth().currentUser.isEmailVerified;
//final user = Provider.of<UserCredential>(context);
final user = Provider.of<User>(context);
if(user == null){
return Authenticate();
}else {
return Homepage();
}
//return Home or Authenticate widget
}
}
它应该是这样的:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:projectandroidstudiodenya/seitenleiste/homepage.dart';
import 'package:provider/provider.dart';
import 'authenticate/authenticate.dart';
import 'models/user.dart';
class Wrapper extends StatelessWidget {
static const route='/Wrapper';
@override
Widget build(BuildContext context) {
//Auth.auth().currentUser.isEmailVerified;
//final user = Provider.of<UserCredential>(context);
final user = Provider.of<User>(context);
if(user == null){
return Authenticate();
}else if(FirebaseAuth.instance.currentUser.emailVerified){
return Homepage();
}
//return Home or Authenticate widget
}
}
所以你可以看到我打电话给 user.emailVerified。但这是错误的,我真正需要的是您在顶部看到的内容。但是当我尝试更改我的代码时,我收到了这个错误
The name 'User' is defined in the libraries 'package:firebase_auth/firebase_auth.dart' and 'package:projectandroidstudiodenya/models/user.dart'.
我真的不知道该怎么做以及如何改变。
这是我的授权class:
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/cupertino.dart';
import 'package:projectandroidstudiodenya/authenticate/register.dart';
import 'package:projectandroidstudiodenya/authenticate/signin.dart';
import 'package:projectandroidstudiodenya/authenticate/verifyemail.dart';
import 'package:projectandroidstudiodenya/models/user.dart' as Model;
import 'package:projectandroidstudiodenya/services/database.dart';
import 'database.dart';
import 'database.dart';
import 'database.dart';
class AuthService {
// final FirebaseAuth _auth = FirebaseAuth.instance.currentUser as FirebaseAuth;
final FirebaseAuth _auth = FirebaseAuth.instance ;
String error;
String result="";
//create user obj based on FirebasedUser
Model.Userr _userFromFirebaseUser(User user) {
return user != null ? Model.Userr(uid: user.uid) : null;
}
Stream <Model.Userr> get user{
return FirebaseAuth.instance.authStateChanges().map(_userFromFirebaseUser);
}
//SIGNOUT
Future<void> signOut() async {
await FirebaseAuth.instance.signOut();
}
//sign in anon
Future signInAnon() async {
try {
UserCredential result = await _auth.signInAnonymously();
User user = result.user;
return _userFromFirebaseUser(user);
} catch (e) {
print(e.toString());
return null;
}
}
//sign in with passwort and email
Future signIN(String email, String password) async {
try {
//if (FirebaseAuth.instance.currentUser.emailVerified) {print('fuckyooooooo');
(await _auth.signInWithEmailAndPassword(
email: email.trim(), password: password)).user?.emailVerified;
}
on FirebaseAuthException catch (e) {
switch (e.code) {
case 'invalid-email':
{
return 'Email is not valid';
}
case 'user-disabled':
{
return 'Account is not active';
}
case 'user-not-found':
{
return 'No user found';
}
case 'wrong-password':
{
return 'wrong password';
}
default:
{
return 'Please verify you account and restart the App';
}
}
}
return null;
}
//register with passwort an email
Future signUp(String email, String password,) async {
try {
UserCredential result =await _auth.createUserWithEmailAndPassword(
email: email, password: password);
result.user?.sendEmailVerification();
User user =result?.user;
await DatbaseService(uid:user.uid).updateUserData('0','new crew member','100','dfdssf');
return ;
//user.sendEmailVerification();
// ( await DatbaseService(uid:user).updateUserData('0','new crew member','100','dfdssf')).user.uid;;
} on FirebaseAuthException catch (e) {
switch (e.code) {
case 'invalid-email':
{
return 'Email is not valid';
}
case 'user-disabled':
{
return 'Account is not active';
}
case 'user-not-found':
{
return 'No user found';
}
case 'wrong-password':
{
return 'wrong password';
}
default:
{
return 'Unexpected error!';
}
}
}
return null;
}
Model.Userr getCurrentUser(User user) {
return user != null ? Model.Userr() : null;
}
//resetpassword
Future sendPasswordResetEmail(String email) async {
try {
return await _auth.sendPasswordResetEmail(email: email);
} on FirebaseAuthException catch (e) {
switch (e.code) {
case 'invalid-email':
{
return 'Email is not valid';
}
case 'user-disabled':
{
return 'Account is not active';
}
case 'user-not-found':
{
return 'No user found';
}
case 'wrong-password':
{
return 'wrong password';
}
default:
{
return 'Unexpected error!';
}
return null;
}
}
}
}
这是我的主要内容
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context){
return
StreamProvider<Userr>.value(
child: MaterialApp(
debugShowCheckedModeBanner: false,
title:'Appbar Scaffold',
theme: ThemeData(
scaffoldBackgroundColor: Colors.white,
primaryColor: Colors.white,
),
//home: Homepage(),
//initialRoute: '/',
// initialRoute: FirebaseAuth.instance.currentUser==null?LoginScreen():Homepage.route(),
routes:{'/':(_)=>Wrapper(),
Homepage.route:(_)=> Homepage(),
Beitraegedieichmag.route:(_)=> Beitraegedieichmag(),
MeinAccount.route:(_)=> MeinAccount(),
MeineBeitraege.route:(_)=>MeineBeitraege(),
MeineFreunde.route:(_)=> MeineFreunde(),
Nachrchten.route:(_)=> Nachrchten(),
LoginScreen.route:(_)=> LoginScreen(),
} ,
这是错误:
======== Exception caught by widgets library =======================================================
The following ProviderNotFoundException was thrown building Wrapper(dirty):
Error: Could not find the correct Provider<User> above this Wrapper Widget
This happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:
- You added a new provider in your `main.dart` and performed a hot-reload.
To fix, perform a hot-restart.
- The provider you are trying to read is in a different route.
Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.
- You used a `BuildContext` that is an ancestor of the provider you are trying to read.
Make sure that Wrapper is under your MultiProvider/Provider<User>.
This usually happens when you are creating a provider and trying to read it immediately.
For example, instead of:
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// Will throw a ProviderNotFoundError, because `context` is associated
// to the widget that is the parent of `Provider<Example>`
child: Text(context.watch<Example>()),
),
}
consider using `builder` like so:
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// we use `builder` to obtain a new `BuildContext` that has access to the provider
builder: (context) {
// No longer throws
return Text(context.watch<Example>()),
}
),
}
If none of these solutions work, consider asking for help on Whosebug:
https://whosebug.com/questions/tagged/flutter
The relevant error-causing widget was:
Wrapper file:///Users/yavuzatmaca/StudioProjects/projectandroidstudiodenya/lib/main.dart:44:36
When the exception was thrown, this was the stack:
#0 Provider._inheritedElementOf (package:provider/src/provider.dart:332:7)
#1 Provider.of (package:provider/src/provider.dart:284:30)
#2 Wrapper.build (package:projectandroidstudiodenya/wrapper.dart:20:27)
#3 StatelessElement.build (package:flutter/src/widgets/framework.dart:4661:28)
#4 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4587:15)
====================================================================================================
Reloaded 16 of 687 libraries in 640ms.
这是我的用户class
import 'package:flutter/cupertino.dart';
class Userr{
final String uid;
Userr({this.uid});
}
现在的错误是:
======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building Wrapper(dirty, dependencies: [_InheritedProviderScope<Userr>]):
The getter 'emailVerified' was called on null.
Receiver: null
Tried calling: emailVerified
The relevant error-causing widget was:
Wrapper file:///Users/yavuzatmaca/StudioProjects/projectandroidstudiodenya/lib/main.dart:47:36
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 Wrapper.build (package:projectandroidstudiodenya/wrapper.dart:22:42)
#2 StatelessElement.build (package:flutter/src/widgets/framework.dart:4661:28)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4587:15)
#4 Element.rebuild (package:flutter/src/widgets/framework.dart:4281:5)
...
====================================================================================================
======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building Wrapper(dirty, dependencies: [_InheritedProviderScope<Userr>]):
The getter 'emailVerified' was called on null.
Receiver: null
Tried calling: emailVerified
The relevant error-causing widget was:
Wrapper file:///Users/name/StudioProjects/projectname/lib/main.dart:47:36
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 Wrapper.build (package:projectname/wrapper.dart:22:42)
#2 StatelessElement.build (package:flutter/src/widgets/framework.dart:4661:28)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4587:15)
#4 Element.rebuild (package:flutter/src/widgets/framework.dart:4281:5)
...
====================================================================================================
试试这个:
class Wrapper extends StatelessWidget {
static const route='/Wrapper';
@override
Widget build(BuildContext context) {
final user = Provider.of<Userr>(context);
if(user == null){
return Authenticate();
}else if(FirebaseAuth.instance.currentUser.emailVerified){
return Homepage();
}
//return Home or Authenticate widget
}}
Main.dart:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(StreamProvider<Userr>.value(
value: AuthService().user,
child: MaterialApp(
home: MyApp(),
),
));
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
...
);
}
}
经过几天尝试改变我的方法,我终于得到了结果。但这是我的问题:每次我重新启动应用程序时,我都有一个从 main 调用的包装器。我想在我的包装器中使用它 class:
if(FirebaseAuth.instance.currentUser.emailVerified){}
这是我目前的包装 class:
import 'package:flutter/material.dart';
import 'package:projectandroidstudiodenya/seitenleiste/homepage.dart';
import 'package:provider/provider.dart';
import 'authenticate/authenticate.dart';
import 'models/user.dart';
class Wrapper extends StatelessWidget {
static const route='/Wrapper';
@override
Widget build(BuildContext context) {
//Auth.auth().currentUser.isEmailVerified;
//final user = Provider.of<UserCredential>(context);
final user = Provider.of<User>(context);
if(user == null){
return Authenticate();
}else {
return Homepage();
}
//return Home or Authenticate widget
}
}
它应该是这样的:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:projectandroidstudiodenya/seitenleiste/homepage.dart';
import 'package:provider/provider.dart';
import 'authenticate/authenticate.dart';
import 'models/user.dart';
class Wrapper extends StatelessWidget {
static const route='/Wrapper';
@override
Widget build(BuildContext context) {
//Auth.auth().currentUser.isEmailVerified;
//final user = Provider.of<UserCredential>(context);
final user = Provider.of<User>(context);
if(user == null){
return Authenticate();
}else if(FirebaseAuth.instance.currentUser.emailVerified){
return Homepage();
}
//return Home or Authenticate widget
}
}
所以你可以看到我打电话给 user.emailVerified。但这是错误的,我真正需要的是您在顶部看到的内容。但是当我尝试更改我的代码时,我收到了这个错误
The name 'User' is defined in the libraries 'package:firebase_auth/firebase_auth.dart' and 'package:projectandroidstudiodenya/models/user.dart'.
我真的不知道该怎么做以及如何改变。
这是我的授权class:
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/cupertino.dart';
import 'package:projectandroidstudiodenya/authenticate/register.dart';
import 'package:projectandroidstudiodenya/authenticate/signin.dart';
import 'package:projectandroidstudiodenya/authenticate/verifyemail.dart';
import 'package:projectandroidstudiodenya/models/user.dart' as Model;
import 'package:projectandroidstudiodenya/services/database.dart';
import 'database.dart';
import 'database.dart';
import 'database.dart';
class AuthService {
// final FirebaseAuth _auth = FirebaseAuth.instance.currentUser as FirebaseAuth;
final FirebaseAuth _auth = FirebaseAuth.instance ;
String error;
String result="";
//create user obj based on FirebasedUser
Model.Userr _userFromFirebaseUser(User user) {
return user != null ? Model.Userr(uid: user.uid) : null;
}
Stream <Model.Userr> get user{
return FirebaseAuth.instance.authStateChanges().map(_userFromFirebaseUser);
}
//SIGNOUT
Future<void> signOut() async {
await FirebaseAuth.instance.signOut();
}
//sign in anon
Future signInAnon() async {
try {
UserCredential result = await _auth.signInAnonymously();
User user = result.user;
return _userFromFirebaseUser(user);
} catch (e) {
print(e.toString());
return null;
}
}
//sign in with passwort and email
Future signIN(String email, String password) async {
try {
//if (FirebaseAuth.instance.currentUser.emailVerified) {print('fuckyooooooo');
(await _auth.signInWithEmailAndPassword(
email: email.trim(), password: password)).user?.emailVerified;
}
on FirebaseAuthException catch (e) {
switch (e.code) {
case 'invalid-email':
{
return 'Email is not valid';
}
case 'user-disabled':
{
return 'Account is not active';
}
case 'user-not-found':
{
return 'No user found';
}
case 'wrong-password':
{
return 'wrong password';
}
default:
{
return 'Please verify you account and restart the App';
}
}
}
return null;
}
//register with passwort an email
Future signUp(String email, String password,) async {
try {
UserCredential result =await _auth.createUserWithEmailAndPassword(
email: email, password: password);
result.user?.sendEmailVerification();
User user =result?.user;
await DatbaseService(uid:user.uid).updateUserData('0','new crew member','100','dfdssf');
return ;
//user.sendEmailVerification();
// ( await DatbaseService(uid:user).updateUserData('0','new crew member','100','dfdssf')).user.uid;;
} on FirebaseAuthException catch (e) {
switch (e.code) {
case 'invalid-email':
{
return 'Email is not valid';
}
case 'user-disabled':
{
return 'Account is not active';
}
case 'user-not-found':
{
return 'No user found';
}
case 'wrong-password':
{
return 'wrong password';
}
default:
{
return 'Unexpected error!';
}
}
}
return null;
}
Model.Userr getCurrentUser(User user) {
return user != null ? Model.Userr() : null;
}
//resetpassword
Future sendPasswordResetEmail(String email) async {
try {
return await _auth.sendPasswordResetEmail(email: email);
} on FirebaseAuthException catch (e) {
switch (e.code) {
case 'invalid-email':
{
return 'Email is not valid';
}
case 'user-disabled':
{
return 'Account is not active';
}
case 'user-not-found':
{
return 'No user found';
}
case 'wrong-password':
{
return 'wrong password';
}
default:
{
return 'Unexpected error!';
}
return null;
}
}
}
}
这是我的主要内容
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context){
return
StreamProvider<Userr>.value(
child: MaterialApp(
debugShowCheckedModeBanner: false,
title:'Appbar Scaffold',
theme: ThemeData(
scaffoldBackgroundColor: Colors.white,
primaryColor: Colors.white,
),
//home: Homepage(),
//initialRoute: '/',
// initialRoute: FirebaseAuth.instance.currentUser==null?LoginScreen():Homepage.route(),
routes:{'/':(_)=>Wrapper(),
Homepage.route:(_)=> Homepage(),
Beitraegedieichmag.route:(_)=> Beitraegedieichmag(),
MeinAccount.route:(_)=> MeinAccount(),
MeineBeitraege.route:(_)=>MeineBeitraege(),
MeineFreunde.route:(_)=> MeineFreunde(),
Nachrchten.route:(_)=> Nachrchten(),
LoginScreen.route:(_)=> LoginScreen(),
} ,
这是错误:
======== Exception caught by widgets library =======================================================
The following ProviderNotFoundException was thrown building Wrapper(dirty):
Error: Could not find the correct Provider<User> above this Wrapper Widget
This happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:
- You added a new provider in your `main.dart` and performed a hot-reload.
To fix, perform a hot-restart.
- The provider you are trying to read is in a different route.
Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.
- You used a `BuildContext` that is an ancestor of the provider you are trying to read.
Make sure that Wrapper is under your MultiProvider/Provider<User>.
This usually happens when you are creating a provider and trying to read it immediately.
For example, instead of:
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// Will throw a ProviderNotFoundError, because `context` is associated
// to the widget that is the parent of `Provider<Example>`
child: Text(context.watch<Example>()),
),
}
consider using `builder` like so:
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// we use `builder` to obtain a new `BuildContext` that has access to the provider
builder: (context) {
// No longer throws
return Text(context.watch<Example>()),
}
),
}
If none of these solutions work, consider asking for help on Whosebug:
https://whosebug.com/questions/tagged/flutter
The relevant error-causing widget was:
Wrapper file:///Users/yavuzatmaca/StudioProjects/projectandroidstudiodenya/lib/main.dart:44:36
When the exception was thrown, this was the stack:
#0 Provider._inheritedElementOf (package:provider/src/provider.dart:332:7)
#1 Provider.of (package:provider/src/provider.dart:284:30)
#2 Wrapper.build (package:projectandroidstudiodenya/wrapper.dart:20:27)
#3 StatelessElement.build (package:flutter/src/widgets/framework.dart:4661:28)
#4 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4587:15)
====================================================================================================
Reloaded 16 of 687 libraries in 640ms.
这是我的用户class
import 'package:flutter/cupertino.dart';
class Userr{
final String uid;
Userr({this.uid});
}
现在的错误是:
======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building Wrapper(dirty, dependencies: [_InheritedProviderScope<Userr>]):
The getter 'emailVerified' was called on null.
Receiver: null
Tried calling: emailVerified
The relevant error-causing widget was:
Wrapper file:///Users/yavuzatmaca/StudioProjects/projectandroidstudiodenya/lib/main.dart:47:36
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 Wrapper.build (package:projectandroidstudiodenya/wrapper.dart:22:42)
#2 StatelessElement.build (package:flutter/src/widgets/framework.dart:4661:28)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4587:15)
#4 Element.rebuild (package:flutter/src/widgets/framework.dart:4281:5)
...
====================================================================================================
======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building Wrapper(dirty, dependencies: [_InheritedProviderScope<Userr>]):
The getter 'emailVerified' was called on null.
Receiver: null
Tried calling: emailVerified
The relevant error-causing widget was:
Wrapper file:///Users/name/StudioProjects/projectname/lib/main.dart:47:36
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 Wrapper.build (package:projectname/wrapper.dart:22:42)
#2 StatelessElement.build (package:flutter/src/widgets/framework.dart:4661:28)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4587:15)
#4 Element.rebuild (package:flutter/src/widgets/framework.dart:4281:5)
...
====================================================================================================
试试这个:
class Wrapper extends StatelessWidget {
static const route='/Wrapper';
@override
Widget build(BuildContext context) {
final user = Provider.of<Userr>(context);
if(user == null){
return Authenticate();
}else if(FirebaseAuth.instance.currentUser.emailVerified){
return Homepage();
}
//return Home or Authenticate widget
}}
Main.dart:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(StreamProvider<Userr>.value(
value: AuthService().user,
child: MaterialApp(
home: MyApp(),
),
));
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
...
);
}
}