ExampleStorage · Database
File Upload
Pick an image from the device, upload it to Koolbase Storage, and save it on the user's profile in the database.
Prerequisites
Add image_picker to your pubspec.yaml and create a public avatars bucket and a profiles collection in the dashboard. Give user_id a unique constraint so each person has one profile.
pubspec.yaml
YAML
dependencies:
koolbase_flutter: ^12.60.0
image_picker: ^1.0.0Profile avatar upload
lib/screens/profile_screen.dart
Dart
class ProfileScreen extends StatefulWidget {
const ProfileScreen({super.key});
@override
State<ProfileScreen> createState() => _ProfileScreenState();
}
class _ProfileScreenState extends State<ProfileScreen> {
String? _avatarUrl;
bool _uploading = false;
Future<void> _pickAndUpload() async {
final picker = ImagePicker();
final picked = await picker.pickImage(
source: ImageSource.gallery,
maxWidth: 800,
imageQuality: 85,
);
if (picked == null) return;
setState(() => _uploading = true);
try {
final user = Koolbase.auth.currentUser!;
final bytes = await picked.readAsBytes();
final path = 'user_${user.id}.jpg';
// 1. Upload the picture
await Koolbase.storage.uploadBytes(
bucket: 'avatars',
path: path,
bytes: bytes,
contentType: 'image/jpeg',
overwrite: true,
onProgress: (p) {
// Optional: show p.bytesSent of p.bytesTotal
},
);
// 2. Save the file's path on the person's profile.
// Save the path, not a download link: links expire.
await Koolbase.db.upsert(
collection: 'profiles',
match: {'user_id': user.id},
data: {'avatar_path': path},
);
// 3. Show it. 'avatars' is a public bucket, so this link lasts.
setState(() => _avatarUrl =
Koolbase.storage.publicUrlFor(bucket: 'avatars', path: path));
} finally {
setState(() => _uploading = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GestureDetector(
onTap: _uploading ? null : _pickAndUpload,
child: CircleAvatar(
radius: 50,
backgroundImage: _avatarUrl != null
? NetworkImage(_avatarUrl!)
: null,
child: _uploading
? const CircularProgressIndicator()
: (_avatarUrl == null ? const Icon(Icons.add_a_photo) : null),
),
),
const SizedBox(height: 16),
const Text('Tap to change avatar'),
],
),
),
);
}
}Load profile on startup
lib/screens/profile_screen.dart
Dart
@override
void initState() {
super.initState();
_loadProfile();
}
Future<void> _loadProfile() async {
final user = Koolbase.auth.currentUser;
if (user == null) return;
final result = await Koolbase.db
.collection('profiles')
.where('user_id', isEqualTo: user.id)
.limit(1)
.get();
if (result.records.isEmpty) return;
final path = result.records.first.data['avatar_path'] as String?;
if (path == null) return;
setState(() => _avatarUrl =
Koolbase.storage.publicUrlFor(bucket: 'avatars', path: path));
}