profiles provider

This commit is contained in:
SomnusVeritas
2023-10-20 23:21:36 +02:00
parent a5269f077b
commit 1e1a1d6e7c
2 changed files with 48 additions and 4 deletions

View File

@@ -3,6 +3,7 @@ import 'package:shared_preferences/shared_preferences.dart';
import 'package:supabase_flutter/supabase_flutter.dart'; import 'package:supabase_flutter/supabase_flutter.dart';
import '../models/feed_item.dart'; import '../models/feed_item.dart';
import '../models/profile.dart';
class DbHelper { class DbHelper {
static Future<SharedPreferences> get _prefs async => static Future<SharedPreferences> get _prefs async =>
@@ -65,6 +66,12 @@ class DbHelper {
return false; return false;
} }
static void logout() async {
final prefs = await _prefs;
await prefs.remove('username');
_supabase.auth.signOut();
}
static Future<List<FeedItem>> fetchFeed() async { static Future<List<FeedItem>> fetchFeed() async {
List<FeedItem> items = []; List<FeedItem> items = [];
final res = await _supabase.from('feed').select(); final res = await _supabase.from('feed').select();
@@ -74,12 +81,18 @@ class DbHelper {
return items; return items;
} }
static void logout() async { static Future<List<Profile>> fetchProfiles() async {
final prefs = await _prefs; List<Profile> items = [];
await prefs.remove('username'); final res = await _supabase.from('profiles').select();
_supabase.auth.signOut(); for (final map in res) {
items.add(Profile.fromMap(map));
}
return items;
} }
static Stream<List<Map<String, dynamic>>> get feedStream => static Stream<List<Map<String, dynamic>>> get feedStream =>
_supabase.from('feed').stream(primaryKey: ['timestamp']); _supabase.from('feed').stream(primaryKey: ['timestamp']);
static Stream<List<Map<String, dynamic>>> get profilesStream =>
_supabase.from('profiles').stream(primaryKey: ['id']);
} }

View File

@@ -0,0 +1,31 @@
import 'package:flutter/material.dart';
import '../models/profile.dart';
import 'db_helper.dart';
class Profiles extends ChangeNotifier {
final List<Profile> _profiles = [];
Stream<List<Map<String, dynamic>>>? _profilesStream;
List<Profile> get profiles {
if (_profilesStream == null) {
DbHelper.fetchProfiles().then((value) {
_profiles.clear();
_profiles.addAll(value);
});
_profilesStream = DbHelper.profilesStream;
_profilesStream!.listen(
(event) => _updateProfile(event),
);
}
return _profiles;
}
_updateProfile(List<Map<String, dynamic>> data) {
final List<Profile> profiles = data.map((e) => Profile.fromMap(e)).toList();
_profiles.clear();
_profiles.addAll(profiles);
notifyListeners();
}
}