gpt4 book ai didi

用于监控 Firebase Auth 状态的 Flutter StreamBuilder

转载 作者:行者123 更新时间:2023-12-05 05:47:08 24 4
gpt4 key购买 nike

当我有一个登录用户时,我的包装器会检查其他数据,一旦找到它就会打开我的应用程序的主屏幕。

但是,即使用户成功注销,Stream Builder 也不会返回登录屏幕。

正如我所看到的,主页是在不同的树中构建的(但是如何在主树中构建它?),不知道这是否会造成干扰。

主要代码:

void main() async {
WidgetsFlutterBinding.ensureInitialized();
if (kIsWeb) {
await Firebase.initializeApp(),
);
} else {
await Firebase.initializeApp();
}
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
Provider<AuthService>(
create: (_) => AuthService(),
),
],
child: GestureDetector(
onTap: () {
FocusScopeNode currentFocus = FocusScope.of(context);
if (!currentFocus.hasPrimaryFocus) {
FocusScope.of(context).requestFocus(FocusNode());
}
},
child: MaterialApp(
theme: ThemeData(
primaryColor: appColor,
primaryColorLight: appColor,
primaryColorDark: appColor,
),
debugShowCheckedModeBanner: false,
title: 'WhyBye',
//todo: Queste righe saranno necessarie quando avremo anche la versione WEB
// home: ResponsiveLayout(
// webScreenLayout: WebScreenLayout(),
// mobileScreenLayout: MobileScreenLayout()),
//todo.

initialRoute: '/wrapper',
routes: {
'/wrapper': (context) => const Wrapper(),
'/signInScreen': (context) => const SignInScreen(),
'/signUpScreen': (context) => const SignUpScreen(),
'/registrationScreen': (context) => const RegistrationScreen(),
'/homeScreen': (context) => const HomeScreen(),
'/recoverPasswordScreen': (context) =>
const RecoverPasswordScreen(),
},
),
),
);
}
}

我的包装代码:

class Wrapper extends StatelessWidget {
const Wrapper({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final authService = Provider.of<AuthService>(context);
return StreamBuilder<User?>(
stream: authService.user,
builder: (_, AsyncSnapshot<User?> snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
final User? user = snapshot.data;
//return user == null ? const SignInScreen() : const HomeScreen();
if (user == null) {
return const SignInScreen();
} else {
WidgetsBinding.instance
?.addPostFrameCallback((_) => asyncMethod(context));
return const Scaffold(
body: Center(
child: CircularProgressIndicator(
color: appBarColor,
),
),
);
}
} else {
return const Scaffold(
body: Center(
child: CircularProgressIndicator(
color: appBarColor,
),
),
);
}
},
);
}
}

void asyncMethod(BuildContext context) async {
final FirebaseMethods _firebase = FirebaseMethods();
bool isTrue = await _firebase.isRegistrationUserCompleted(_firebase.getUID());
if (!isTrue) {
Variables.isCustomUserPic = false;
Variables.isSocialUserPic = false;
await _firebase.loadDefaultUserPicUrl();
//& qui devo andare alla registrazione utente.
if (Variables.isSignUp) {
Navigator.of(context).pushReplacement(
MaterialPageRoute(builder: (context) => const RegistrationScreen()),
);
} else {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => const RegistrationScreen()),
);
}
//Navigator.pop(context);
} else {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => const HomeScreen()),
);
//Navigator.pop(context);
}
}

还有我非常简单的主屏幕:

class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);

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

class _HomeScreenState extends State<HomeScreen> {
@override
void initState() {
super.initState();
}

@override
Widget build(BuildContext context) {
return const IHome();
}
}

class IHome extends StatelessWidget {
const IHome({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return Container(
color: Colors.white,
child: Center(
child: ElevatedButton(
child: const Text('LogOut'),
onPressed: () async {
bool isTrue = await AuthMethods().signOut();
if (isTrue) {
//Navigator.pop(context);
}
//Navigator.pop(context);
},
),
),
);
}
}

这里是用户登录时的小部件树,包装器加载了主屏幕。

enter image description here

如您所见,我需要在切换到主屏幕之前检查其他数据,这是我需要的帐户后数据。

但是,当用户登录时,我直接从 Wrapper 打开主页,但无法识别注销(我检查了注销工作正常)。

此处是包装器选择登录屏幕时的小部件树(因为用户未登录)。

enter image description here

据我所知,我可能需要避免使用 Navigator 打开 HomeScreen,但我不知道该怎么做。

非常感谢您的支持。

最佳答案

authStatechange 时您没有重新路由的原因可能有几个:

可能是您的 providerstate notifiers 的创建和使用方式的主要问题。

我建议您改为在Wrapper Widget 中监听authStateChange,这是一个简短的示例:

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Your App Name',
home: _getLandingPage()
);
}

Widget _getLandingPage() {
return StreamBuilder<FirebaseUser>(
stream: FirebaseAuth.instance.onAuthStateChanged,
builder: (BuildContext context, snapshot) {
if (snapshot.hasData) {
return MainPage();
} else {
return LoginPage();
}
},
);
}

FirebaseAuth.instance
.userChanges()
.listen((User? user) {
if (user == null) {
print('User is currently signed out!');
} else {
print('User is signed in!');
}
});

您可以找到更多信息 here

关于用于监控 Firebase Auth 状态的 Flutter StreamBuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71058330/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com