AsyncError<Benutzer?>(Fehler: Nullprüfoperator für einen Nullwert verwendet, stackTrace: #0 currentUserDetailsProvider.<
Posted: 07 Jan 2025, 10:41
Zunächst wird „Benutzer N/A“ und „AsyncError“ angezeigt (Fehler: Nullprüfoperator für einen Nullwert verwendet, StackTrace: #0 currentUserDetailsProvider. Fehler, aber nach einem Warmstart funktioniert es einwandfrei. Warum?
Es funktioniert nach einem Warmstart. Wie passiert das?
Wie kann dafür gesorgt werden, dass es ordnungsgemäß funktioniert, ohne dass ein Neustart erforderlich ist? Kennt jemand die Lösung? Bitte helfen Sie!
Code: Select all
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:appwrite/models.dart' as model;
import '../apis/auth_api.dart';
import '../apis/user_api.dart';
import '../models/user_model.dart';
import '../widgets/snack_bar.dart';
final authControllerProvider =
StateNotifierProvider((ref) {
return AuthController(
authAPI: ref.watch(authAPIProvider),
userAPI: ref.watch(userAPIProvider),
);
});
final currentUserDetailsProvider = FutureProvider((ref) async {
final currentUserId = ref.watch(currentUserAccountProvider).value!.$id;
final userDetails = ref.watch(userDetailsProvider(currentUserId));
return userDetails.value;
});
final userDetailsProvider = FutureProvider.family((ref, String uid) async {
final authController = ref.watch(authControllerProvider.notifier);
return authController.getUserData(uid);
});
final currentUserAccountProvider = FutureProvider((ref) async {
final authController = ref.watch(authControllerProvider.notifier);
return authController.currentUser();
});
class AuthController extends StateNotifier {
final AuthAPI _authAPI;
final UserAPI _userAPI;
AuthController({required AuthAPI authAPI, required UserAPI userAPI})
: _authAPI = authAPI,
_userAPI = userAPI,
super(false);
Future currentUser() => _authAPI.currentUserAccount();
void signUp({
required String email,
required String password,
required BuildContext context,
}) async {
state = true;
final res = await _authAPI.signUp(email: email, password: password);
res.fold((failure) {
print('Sign up failed: ${failure.message}');
showSnackBar(context, failure.message);
}, (user) async {
User userModel = User(
email: email,
name: getNameFromEmail(email),
uid: user.$id,
patientName: '',
patientAge: 18,
patientGender: '--',
disorderName: '',
phoneNumber: '',
emotion: '',
sessionId: '');
final res2 = await _userAPI.saveUserData(userModel);
res2.fold((failure) {
print('Failed to save user data: ${failure.message}');
showSnackBar(context, 'Database creation failed: ${failure.message}');
}, (r) {
showSnackBar(context, 'Account Created Successfully!');
login(email: email, password: password, context: context);
});
});
state = false;
}
void login({
required String email,
required String password,
required BuildContext context,
}) async {
state = true;
final res = await _authAPI.login(email: email, password: password);
state = false;
res.fold(((l) {
showSnackBar(context, l.message);
}), (r) => Navigator.pushNamed(context, '/home'));
}
Future getUserData(String uid) async {
final document = await _userAPI.getUserData(uid);
final updatedUser = User.fromMap(document.data);
return updatedUser;
}
void update({required BuildContext context, required User userData}) async {
state = true;
final res = await _userAPI.updateUserData(userData.uid, userData);
state = false;
res.fold(
(l) => {showSnackBar(context, l.message)},
(r) =>
{showSnackBar(context, 'Patient details updated successfully!')});
}
Future updateUserSession({
required BuildContext context,
required User? updatedUser,
}) async {
state = true;
final currentUserId = await currentUser();
if (currentUserId == null) {
state = false;
showSnackBar(context, 'No user logged in.');
return;
}
try {
final res = await _userAPI.updateUserData(currentUserId.$id, updatedUser!);
res.fold(
(failure) {
showSnackBar(context, 'error occured: ${failure.message}');
},
(success) {
showSnackBar(context, 'Session updated successfully.');
},
);
} catch (e) {
print(e);
showSnackBar(context, 'Error updating session: $e');
}
state = false;
}
void logout(BuildContext context) async {
state = true;
final res = await _authAPI.logout();
state = false;
res.fold(
(l) => showSnackBar(context, l.message),
(r) => Navigator.pushNamedAndRemoveUntil(
context,
'/landing',
(route) => false,
),
);
}
}
Code: Select all
import 'package:appwrite/appwrite.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'appwrite.dart';
final appwriteClientProvider = Provider((ref) {
Client client = Client();
return client
.setEndpoint(AppWrite.endPoint)
.setProject(AppWrite.projectId)
.setSelfSigned(status: true);
});
final appwriteAccountProvider = Provider((ref) {
final client = ref.watch(appwriteClientProvider);
return Account(client);
});
final appwriteDatabseProvider = Provider((ref) {
final client = ref.watch(appwriteClientProvider);
return Databases(client);
});
Code: Select all
import 'package:caregiver_app/widgets/loading_page.dart';
import 'package:caregiver_app/widgets/snack_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter/services.dart';
import '../constants/auth_controller.dart';
class ProfileScreen extends ConsumerWidget {
const ProfileScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final currentUser = ref.watch(currentUserDetailsProvider);
print(currentUser);
return currentUser == null
? Loader()
: Scaffold(
body: Column(
children: [
const Expanded(flex: 2, child: TopPortion()),
Expanded(
flex: 3,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
currentUser.when(
data: (user) {
if (user == null) {
return Text('User: N/A');
}
return Text(
'name: ${user.name}',
style: TextStyle(
fontSize: 20, fontStyle: FontStyle.italic),
);
},
error: (e, st) {
print('Error occurred: $e');
print('Stack trace: $st');
return Center(child: Text('User: N/A'));
},
loading: () =>
Center(child: CircularProgressIndicator()),
),
const SizedBox(height: 16),
currentUser.when(
data: (user) {
return Text(
'name: ${user?.email}',
style: TextStyle(
fontSize: 20, fontStyle: FontStyle.italic),
);
},
error: (e, st) => Center(child: Text('User: N/A')),
loading: () =>
Center(child: CircularProgressIndicator())),
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: currentUser.when(
data: (user) {
return Text(
'name: ${user?.uid}',
style: TextStyle(
fontSize: 20,
fontStyle: FontStyle.italic),
);
},
error: (e, st) =>
Center(child: Text('User: N/A')),
loading: () => Center(
child: CircularProgressIndicator())),
),
IconButton(
icon: const Icon(Icons.copy),
onPressed: () {
if (currentUser != null) {
Clipboard.setData(ClipboardData(
text: currentUser.value?.uid));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content:
Text('UID copied to clipboard!')),
);
}
},
),
],
),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FloatingActionButton.extended(
onPressed: () {
Navigator.pushNamed(context, '/patient');
},
heroTag: 'Patient Data',
elevation: 0,
backgroundColor: Color(0xff0043ba),
label: const Text('Patient Data',
style: TextStyle(color: Colors.white)),
icon: const Icon(Icons.person_add_alt_1,
color: Colors.white),
),
const SizedBox(width: 16.0),
FloatingActionButton.extended(
onPressed: () {},
heroTag: 'chat',
elevation: 0,
backgroundColor: Color(0xff0043ba),
label: const Text('Chat',
style: TextStyle(color: Colors.white)),
icon: const Icon(Icons.message_rounded,
color: Colors.white),
),
],
),
const SizedBox(height: 16),
const ProfileInfoRow()
],
),
),
),
],
),
);
}
}
class ProfileInfoRow extends StatelessWidget {
const ProfileInfoRow({Key? key}) : super(key: key);
final List
_items = const [
ProfileInfoItem('Days', 900),
ProfileInfoItem('active', 120),
ProfileInfoItem('status', 200),
];
@override
Widget build(BuildContext context) {
return SizedBox(
height: 80,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: _items.map((item) {
final index = _items.indexOf(item);
return Expanded(
child: Row(
children: [
if (index != 0) const VerticalDivider(),
Expanded(child: singleItem(context, item)),
],
),
);
}).toList(),
),
);
}
Widget singleItem(BuildContext context, ProfileInfoItem item) => Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
item.value.toString(),
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
),
Text(
item.title,
style: Theme.of(context).textTheme.caption,
)
],
);
}
class ProfileInfoItem {
final String title;
final int value;
const ProfileInfoItem(this.title, this.value);
}
class TopPortion extends StatelessWidget {
const TopPortion({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Stack(
fit: StackFit.expand,
children: [
Container(
margin: const EdgeInsets.only(bottom: 50),
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: Alignment.topCenter,
colors: [Color(0xff0043ba), Color(0xff006df1)]),
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(50),
bottomRight: Radius.circular(50),
)),
),
Align(
alignment: Alignment.bottomCenter,
child: SizedBox(
width: 150,
height: 150,
child: Stack(
fit: StackFit.expand,
children: [
Container(
decoration: const BoxDecoration(
color: Colors.black,
shape: BoxShape.circle,
image: DecorationImage(
fit: BoxFit.cover,
image: AssetImage('assets/images/medical_team.png'),
),
)),
],
),
),
)
],
);
}
}