Home > other >  Flutter and Riverpod FutureBuilder never any data
Flutter and Riverpod FutureBuilder never any data

Time:09-11

I'm developing a Flutter app with Riverpod and getting a user from my postgres database as Future<AppUser?>. Anyone have any idea why my FutureBuilder never fetches my user data and always shows the CircularProgressIndicator? My home_screen.dart

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: Center(
        child: FutureBuilder<AppUser?>(
          future: currentUser,
          builder: (context, snapshot) {
            if(snapshot.hasData){
             return Text(
                'Welcome ${snapshot.data!.getNickname}',
                style: const TextStyle(fontSize: 20),
              );
            }
            return const CircularProgressIndicator();
          },
        ),
      ),
    );
  }
}

my user_provider.dart

final authRepositoryProvider = Provider<AuthRepository>((ref) {
  return AuthRepository(FirebaseAuth.instance);
});

final userRepositoryProvider = Provider<UserRepository>((ref) {
  return UserRepository(ref.read(authRepositoryProvider).currentUserEmail!);
});

final currentUserProvider = Provider<Future<AppUser?>>((ref) {
  return ref.read(userRepositoryProvider).getCurrentUser();
});

My user_repository.dart

class UserRepository {
  final String email;
  PostgreSQLConnection connection = PostgreSQLConnection(
      '10.0.2.2', 5432, DatabaseAccess.databaseName,
      queryTimeoutInSeconds: 3600,
      timeoutInSeconds: 3600,
      username: DatabaseAccess.databaseUser,
      password: DatabaseAccess.databasePassword);

  UserRepository(this.email);

  Future<AppUser?> getCurrentUser() async {
    try {
      await connection.open();
      final result = await connection.mappedResultsQuery(
        'select * from 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;
    }
  }
}

CodePudding user response:

Try changing

final currentUser = ref.watch(currentUserProvider);

to

final currentUser = ref.read(currentUserProvider);
  • Related