Flutter项目中基于Firestore用户集合导航至对应仪表盘时Courier用户出现Navigator空值异常的问题求助
Let's break down what's causing this issue:
When a user is a Customer, your code runs Navigator.pushNamed which removes the current LoginScreen from the widget tree. But your code doesn't stop there—it continues to run the second Firestore query for the Couriers collection. Once that query finishes, you try to call Navigator.pushNamed again, but the original context is no longer valid (the widget was already destroyed), which triggers the null check error you're seeing.
On top of that, your conditional logic uses separate if statements instead of else if, so both queries run every time—this is a waste of resources and directly leads to the context problem.
We need to adjust the logic to stop executing code immediately after navigating, and avoid unnecessary Firestore calls. Here's the revised code:
// First check if the user is a Customer var customerDoc = await FirebaseFirestore.instance.collection('Customers').doc(user.uid).get(); if (customerDoc.exists) { print('Customer exists'); Navigator.pushNamed(context, '/dashboardLocation'); return; // Exit the function after navigation to stop further code } // If not a Customer, check if they're a Courier var courierDoc = await FirebaseFirestore.instance.collection('Couriers').doc(user.uid).get(); if (courierDoc.exists) { print('Courier exists'); Navigator.pushNamed(context, '/courierDashboard'); return; // Exit after navigation } // Handle users who are neither Customer nor Courier print('User is not in Customers or Couriers collection'); // Add logic here (e.g., redirect to registration)
For better performance and safety, consider these tweaks:
- Parallelize Firestore queries
Instead of waiting for one query to finish before starting the next, run both at the same time to cut down on wait time:
// Start both queries simultaneously final customerFuture = FirebaseFirestore.instance.collection('Customers').doc(user.uid).get(); final courierFuture = FirebaseFirestore.instance.collection('Couriers').doc(user.uid).get(); // Wait for both to complete final results = await Future.wait([customerFuture, courierFuture]); final isCustomer = results[0].exists; final isCourier = results[1].exists; // Navigate based on results if (isCustomer) { Navigator.pushNamed(context, '/dashboardLocation'); } else if (isCourier) { Navigator.pushNamed(context, '/courierDashboard'); } else { // Handle unknown user case }
- Validate context before navigating
Add a check to ensure the widget is still mounted before callingNavigator—this adds an extra layer of safety against context-related errors:
if (mounted) { Navigator.pushNamed(context, '/dashboardLocation'); }
内容的提问来源于stack exchange,提问作者sleor

