Flutter app login after a logout PostgresSQLException

Viewed 52

I'm working on a Flutter app using Riverpod for the state management and Postgres for the database. I try to do a simple thing: display a message in the home screen with the nickname of the current user. When I logout and login to check if my feature works, my user is null and my console display a PostgresSQLException :

PostgreSQLSeverity.error : Attempting to reopen a closed connection. Create a instance instead.

Any idea where I made a mistake? My user_repository:

 PostgreSQLConnection connection = PostgreSQLConnection(
      '10.0.2.2', 5432, DatabaseAccess.databaseName,
      queryTimeoutInSeconds: 3600,
      timeoutInSeconds: 3600,
      username: DatabaseAccess.databaseUser,
      password: DatabaseAccess.databasePassword);

  Future<AppUser?> getCurrentUser() async {
    try {
      await connection.open();
      final result = await connection.mappedResultsQuery(
        'select * from public.user where email = @emailValue',
        substitutionValues: {
          'emailValue': email,
        },
        allowReuse: true,
        timeoutInSeconds: 30,
      );

      final userFromDataBase = result[0]['user']!;
      return AppUser(
        email: userFromDataBase['email'],
        nickname: userFromDataBase['nickname'],
        role: userFromDataBase['role'],
        firstname: userFromDataBase['firstname'],
        lastname: userFromDataBase['lastname'],
      );
    } on PostgreSQLException catch(e) {
      print(ErrorHandler(message: e.toString()));
      return null;
    }
  }

My screen:

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final currentUser = ref.watch(currentUserProvider);
    return Scaffold(
      body: currentUser.when(
        data: (user) =>  _buildBody(context, user, ref),
        loading: () =>  const Center(child: CircularProgressIndicator()),
        error: (error, _) => _errorBody(context, ref),
      )
    );
  }

  Widget _buildBody(BuildContext context, AppUser? user, WidgetRef ref) {
    if(user == null) {
      return _errorBody(context, ref);
    } else {
      return Center(child: Text(
          'Welcome ${user.getNickname}',
        style: const TextStyle(fontSize: 20),
      ));
    }
  }

  Widget _errorBody(BuildContext context, WidgetRef ref) {
    return const Center(child: Text(
        "Error: No user found",
      style: TextStyle(fontSize: 20, color: Colors.red),
    ));
  }

}
0 Answers
Related