-
Notifications
You must be signed in to change notification settings - Fork 31
/
api_services.dart
58 lines (52 loc) · 1.87 KB
/
api_services.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import 'package:cometchat_flutter_sample_app/models/material_button_user_model.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class ApiServices {
// Fetch users from the API
static Future<List<MaterialButtonUserModel>> fetchUsers() async {
try {
final response = await http.get(
Uri.parse('https://assets.cometchat.io/sampleapp/sampledata.json'),
);
if (response.statusCode == 200) {
final List<dynamic> data = json.decode(response.body)['users'] ?? [];
final List<MaterialButtonUserModel> userList = data
.map((user) => MaterialButtonUserModel(
user['name'] ?? "",
user['uid'] ?? "",
user['avatar'] ?? "",
))
.toList();
return userList;
} else {
throw Exception('Failed to load users');
}
} catch (e) {
debugPrint('Exception while fetching users: $e');
// Handle exception here, load users from local asset
return getDefaultUsers();
}
}
// Load default users from local asset
static Future<List<MaterialButtonUserModel>> getDefaultUsers() async {
Map<String, dynamic> jsonData =
await loadJsonFromAssets('assets/sample_app/sample_data.json');
final List<dynamic> data = jsonData['users'] ?? [];
final List<MaterialButtonUserModel> userList = data
.map((user) => MaterialButtonUserModel(
user['name'] ?? "",
user['uid'] ?? "",
user['avatar'] ?? "",
))
.toList();
return userList;
}
// Load JSON from local asset
static Future<Map<String, dynamic>> loadJsonFromAssets(
String filePath) async {
String jsonString = await rootBundle.loadString(filePath);
return jsonDecode(jsonString);
}
}