Initial commit: Penyerahan final Source code Tugas Akhir

This commit is contained in:
ferdiakhh
2025-07-10 19:15:14 +07:00
commit e1f2206b8a
687 changed files with 80132 additions and 0 deletions

17
lib/base_service.dart Normal file
View File

@ -0,0 +1,17 @@
import 'package:flutter_dotenv/flutter_dotenv.dart';
// Ganti baseUrl jadi ngambil dari file .env
String? baseUrl = dotenv.env['BASE_URL_API'];
const Map<String, String> baseHeader = {
'Content-Type': 'application/json',
'Accept': 'application/json',
};
Map<String, String> headerWithToken(String? token) {
return {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
};
}

0
lib/components/.gitkeep Normal file
View File

85
lib/firebase_options.dart Normal file
View File

@ -0,0 +1,85 @@
// File generated by FlutterFire CLI.
// ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
import 'package:flutter/foundation.dart'
show defaultTargetPlatform, kIsWeb, TargetPlatform;
/// Default [FirebaseOptions] for use with your Firebase apps.
///
/// Example:
/// ```dart
/// import 'firebase_options.dart';
/// // ...
/// await Firebase.initializeApp(
/// options: DefaultFirebaseOptions.currentPlatform,
/// );
/// ```
class DefaultFirebaseOptions {
static FirebaseOptions get currentPlatform {
if (kIsWeb) {
return web;
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
return android;
case TargetPlatform.iOS:
return ios;
case TargetPlatform.macOS:
return macos;
case TargetPlatform.windows:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for windows - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.linux:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for linux - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
default:
throw UnsupportedError(
'DefaultFirebaseOptions are not supported for this platform.',
);
}
}
static const FirebaseOptions web = FirebaseOptions(
apiKey: 'AIzaSyDXtaFclWaNaXjMnPsLrsRzEya5c1Lx54U',
appId: '1:652715934272:web:8a2a174bdd075e9b3195a5',
messagingSenderId: '652715934272',
projectId: 'vocasia-bbfb5',
authDomain: 'vocasia-bbfb5.firebaseapp.com',
storageBucket: 'vocasia-bbfb5.appspot.com',
measurementId: 'G-W7Z8ESP739',
);
static const FirebaseOptions android = FirebaseOptions(
apiKey: 'AIzaSyAiHFJENCvW1B8RClUfdZXwk1H6suWtGUU',
appId: '1:652715934272:android:6069e948b9052d2d3195a5',
messagingSenderId: '652715934272',
projectId: 'vocasia-bbfb5',
storageBucket: 'vocasia-bbfb5.appspot.com',
);
static const FirebaseOptions ios = FirebaseOptions(
apiKey: 'AIzaSyDVS6d5Y3GBQXVhk1HfL2GdiC1Wx251b_c',
appId: '1:652715934272:ios:0620353fdfbf6d0a3195a5',
messagingSenderId: '652715934272',
projectId: 'vocasia-bbfb5',
storageBucket: 'vocasia-bbfb5.appspot.com',
androidClientId: '652715934272-8bgpnurmsj0lg8e6c9cg1ccogptm6erm.apps.googleusercontent.com',
iosClientId: '652715934272-89m63o0o412jr6irvf5pnurb7076ajlp.apps.googleusercontent.com',
iosBundleId: 'com.example.initialFolder',
);
static const FirebaseOptions macos = FirebaseOptions(
apiKey: 'AIzaSyDVS6d5Y3GBQXVhk1HfL2GdiC1Wx251b_c',
appId: '1:652715934272:ios:05922d3f99967a1b3195a5',
messagingSenderId: '652715934272',
projectId: 'vocasia-bbfb5',
storageBucket: 'vocasia-bbfb5.appspot.com',
androidClientId: '652715934272-8bgpnurmsj0lg8e6c9cg1ccogptm6erm.apps.googleusercontent.com',
iosClientId: '652715934272-4vdmmf2mdh5nb4j0lnutspkcceh8brdn.apps.googleusercontent.com',
iosBundleId: 'com.example.initialFolder.RunnerTests',
);
}

26
lib/get_it.dart Normal file
View File

@ -0,0 +1,26 @@
import 'package:get_it/get_it.dart';
import 'package:initial_folder/providers/announcement_provider.dart';
import 'package:initial_folder/providers/detail_course_coupon_provider.dart';
import 'package:initial_folder/providers/detail_course_provider.dart';
import 'package:initial_folder/providers/qna_provider.dart';
import 'package:initial_folder/providers/reply_announcement_provider.dart';
import 'package:initial_folder/providers/reply_qna_provider.dart';
final qnaGetIt = GetIt.instance;
final replyQnaGetIt = GetIt.instance;
final detailGetIt = GetIt.instance;
final detailCouponGetIt = GetIt.instance;
final announcementGetIt = GetIt.instance;
final replyAnnouncementGetIt = GetIt.instance;
void setup() {
qnaGetIt.registerSingleton<QnaProvider>(QnaProvider());
replyQnaGetIt.registerSingleton<ReplyQnaProvider>(ReplyQnaProvider());
detailGetIt.registerSingleton<DetailProvider>(DetailProvider());
detailCouponGetIt
.registerSingleton<DetailCouponProvider>(DetailCouponProvider());
announcementGetIt
.registerSingleton<AnnouncementProvider>(AnnouncementProvider());
replyAnnouncementGetIt.registerSingleton<ReplyAnnouncementProvider>(
ReplyAnnouncementProvider());
}

73
lib/helper/user_info.dart Normal file
View File

@ -0,0 +1,73 @@
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class UsersInfo {
final storage = new FlutterSecureStorage();
Future setToken(String? value) async {
final SharedPreferences pref = await SharedPreferences.getInstance();
return pref.setString("token", value!);
}
Future setRefreshToken(String? value) async {
final SharedPreferences pref = await SharedPreferences.getInstance();
return pref.setString('refresh_token', value!);
}
Future setEmail(String? value) async {
final SharedPreferences pref = await SharedPreferences.getInstance();
return pref.setString("email", value!);
}
Future setIdUser(int? value) async {
final SharedPreferences pref = await SharedPreferences.getInstance();
return pref.setInt('idUser', value!);
}
setListData(String key, List<String> value) async {
SharedPreferences myPrefs = await SharedPreferences.getInstance();
myPrefs.setStringList(key, value);
}
Future setStateintro(String? value) async {
await storage.write(key: 'intro', value: value);
}
Future<List<String>?> getListData(String key) async {
SharedPreferences myPrefs = await SharedPreferences.getInstance();
return myPrefs.getStringList(key);
}
Future<String?> getToken() async {
final SharedPreferences pref = await SharedPreferences.getInstance();
return pref.getString("token");
}
Future<String?> getRefreshToken() async {
final SharedPreferences pref = await SharedPreferences.getInstance();
return pref.getString("refresh_token");
}
Future<String?> getEmail() async {
final SharedPreferences pref = await SharedPreferences.getInstance();
return pref.getString("email");
}
Future<int?> getIdUser() async {
final SharedPreferences pref = await SharedPreferences.getInstance();
return pref.getInt("idUser");
}
Future<String?> getStateintro() async {
// String value = await storage.read(key: 'intro');
print(await storage.read(key: 'intro'));
return await storage.read(key: 'intro');
}
Future logout() async {
final SharedPreferences pref = await SharedPreferences.getInstance();
pref.clear();
}
}

368
lib/helper/validator.dart Normal file
View File

@ -0,0 +1,368 @@
import 'package:initial_folder/theme.dart';
import 'package:intl/intl.dart';
import 'package:recase/recase.dart';
import 'package:flutter/material.dart';
String? validateName(String? value) {
if (value!.isEmpty) {
return 'Nama lengkap tidak boleh kosong';
} else if (!RegExp(r'^[a-zA-Z]+(?: [a-zA-Z]+)*$').hasMatch(value)) {
return 'Format Nama Tidak Valid';
} else {
return null;
}
}
String? validatePassword(String? value) {
if (value!.isEmpty) {
return 'Password tidak boleh kosong';
} else if (value.length < 8) {
return 'Password Tidak Sesuai';
} else {
return null;
}
}
String? validateRePassword(String? value, String password) {
if (value!.isEmpty) {
return 'Password tidak boleh kosong';
} else if (value.length < 8) {
return 'Password minimal harus berjumlah 8 karakter';
} else if (value != password) {
return 'Password tidak sama';
}
return null;
}
String? validateEmail(String? value) {
Pattern pattern =
r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
RegExp regex = RegExp(pattern.toString());
if (value!.isEmpty) {
return 'Email tidak boleh kosong';
} else if (!regex.hasMatch(value)) {
return 'Mohon masukkan email yang valid';
} else {
return null;
}
}
String? validateReEmail(String? value, String email) {
Pattern pattern =
r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$';
RegExp regex = RegExp(pattern.toString());
if (value!.isEmpty) {
return 'Konfirmasi email tidak boleh kosong';
} else if (!regex.hasMatch(value)) {
return 'Mohon masukkan konfirmasi email yang valid';
} else if (value != email) {
return 'Email tidak sama';
} else {
return null;
}
}
String? validatePhone(String? value) {
Pattern pattern = r'^[0][0-9]{9,30}$';
RegExp regex = RegExp(pattern.toString());
if (value!.isEmpty) {
return 'Nomor telepon tidak boleh kosong';
} else if (!regex.hasMatch(value)) {
return 'Mohon masukkan nomor telepon yang valid';
} else if (value!.length > 15) {
return 'Nomor telepon maksimal 15 karakter';
} else {
return null;
}
}
String? validateNomorKartu(String? value) {
if (value!.length != 22) {
return 'Panjang Nomor Kartu harus 16 karakter';
} else {
return null;
}
}
String? validateCoupon(String? value) {
if (value!.contains(' ')) {
return 'Harap masukkan kupon tanpa spasi';
} else {
return null;
}
}
String? validateMasaBerlaku(String? value) {
if (value!.length != 5) {
return 'Data belum lengkap';
} else {
return null;
}
}
String? validateKodeKeamanan(String? value) {
if (value!.length != 3) {
return 'Panjang Kode Keamanan harus 3 karakter';
} else {
return null;
}
}
String? validateDate(String? value) {
if (value!.isEmpty) {
return 'Data tidak boleh kosong';
}
int year;
int month;
// The value contains a forward slash if the month and year has been
// entered.
if (value.contains(new RegExp(r'(\/)'))) {
var split = value.split(new RegExp(r'(\/)'));
// The value before the slash is the month while the value to right of
// it is the year.
month = int.parse(split[0]);
year = int.parse(split[1]);
} else {
// Only the month was entered
month = int.parse(value.substring(0, (value.length)));
year = -1; // Lets use an invalid year intentionally
}
if ((month < 1) || (month > 12)) {
// A valid month is between 1 (January) and 12 (December)
return 'Masukkan Bulan yang valid';
}
var fourDigitsYear = convertYearTo4Digits(year);
if ((fourDigitsYear < 1) || (fourDigitsYear > 2099)) {
// We are assuming a valid year should be between 1 and 2099.
// Note that, it's valid doesn't mean that it has not expired.
return 'Masukkan Tahun yang valid';
}
if (!hasDateExpired(month, year)) {
return "Kartu telah kadaluarsa";
}
return null;
}
/// Convert the two-digit year to four-digit year if necessary
int convertYearTo4Digits(int year) {
if (year < 100 && year >= 0) {
var now = DateTime.now();
String currentYear = now.year.toString();
String prefix = currentYear.substring(0, currentYear.length - 2);
year = int.parse('$prefix${year.toString().padLeft(2, '0')}');
}
return year;
}
bool hasDateExpired(int? month, int? year) {
return !(month == null || year == null) && isNotExpired(year, month);
}
bool isNotExpired(int year, int month) {
// It has not expired if both the year and date has not passed
return !hasYearPassed(year) && !hasMonthPassed(year, month);
}
bool hasMonthPassed(int year, int month) {
var now = DateTime.now();
// The month has passed if:
// 1. The year is in the past. In that case, we just assume that the month
// has passed
// 2. Card's month (plus another month) is less than current month.
return hasYearPassed(year) ||
convertYearTo4Digits(year) == now.year && (month < now.month + 1);
}
bool hasYearPassed(int year) {
int fourDigitsYear = convertYearTo4Digits(year);
var now = DateTime.now();
// The year has passed if the year we are currently, is greater than card's
// year
return fourDigitsYear < now.year;
}
String cleanTagHtml(String htmlText) {
RegExp exp = RegExp(r"<[^>]*>", multiLine: true, caseSensitive: true);
return htmlText.replaceAll(exp, '');
}
String filterDuration(String str) {
str = str.replaceAll('m', ' menit ');
str = str.replaceAll('j', ' jam ');
str = str.replaceAll('d', ' detik video pembelajaran');
return str;
}
// numberFormat(String? discountPrice) {
// return NumberFormat.currency(
// locale: 'id',
// decimalDigits: 0,
// symbol: 'Rp. ',
// ).format(int.parse(discountPrice ?? '0'));
// }
String? birthDateValidator(String? value) {
final DateTime now = DateTime.now();
final DateFormat formatter = DateFormat('yyyy');
final String formatted = formatter.format(now);
String? str1 = value;
List<String> str2 = str1!.split('/');
String month = str2.isNotEmpty ? str2[0] : '';
String day = str2.length > 1 ? str2[1] : '';
String year = str2.length > 2 ? str2[2] : '';
if (value!.isEmpty) {
return 'BirthDate is Empty';
} else if (int.parse(month) > 13) {
return 'Month is invalid';
} else if (int.parse(day) > 32) {
return 'Day is invalid';
} else if ((int.parse(year) > int.parse(formatted))) {
return 'Year is invalid';
} else if ((int.parse(year) < 1920)) {
return 'Year is invalid';
}
return null;
}
String validatorSearch(String inputSearch) {
print("ini search");
inputSearch = inputSearch.trimLeft();
inputSearch = inputSearch.replaceAll(' ', '%');
return inputSearch;
}
String validatorSearchFilter(String inputSearch) {
print("ini search");
inputSearch = inputSearch.trimLeft();
inputSearch = inputSearch.replaceAll(' ', '%');
return inputSearch;
}
String dateFormatUlasan(String date) {
date = date.replaceAll(' ', '-');
date = date.replaceAll('Januari', 'Jan');
date = date.replaceAll('Februari', 'Feb');
date = date.replaceAll('Maret', 'Mar');
date = date.replaceAll('April', 'Apr');
date = date.replaceAll('Juni', 'Jun');
date = date.replaceAll('Juli', 'Jul');
date = date.replaceAll('Agustus', 'Agu');
date = date.replaceAll('September', 'Sep');
date = date.replaceAll('Oktober', 'Okt');
date = date.replaceAll('November', 'Nov');
date = date.replaceAll('Desember', 'Des');
return date;
}
String formatAktivitas(String input) {
if (input.length >= 6) {
input = input.replaceAll('m', ':');
input = input.replaceAll('j', ':');
input = input.replaceAll('d', '');
return input = '0' + input;
} else {
input = input.replaceAll('m', ':');
input = input.replaceAll('j', ':');
input = input.replaceAll('d', '');
}
return input;
}
String persentaseUlasan(String input) {
input = input.replaceAll('%', '');
if (input.length > 4) {
input = input.replaceAll('.', '');
input = input.substring(0, 2);
}
return input;
}
String iconCategory(String input) {
input = input.replaceAll('fas fa-', '');
return input.camelCase;
}
// late List<String> _words;
// String _upperCaseFirstLetter(String word) {
// return '${word.substring(0, 1).toUpperCase()}${word.substring(1).toLowerCase()}';
// }
// String getCamelCase({String separator: ''}) {
// List<String> words = _words.map(_upperCaseFirstLetter).toList();
// if (_words.isNotEmpty) {
// words[0] = words[0].toLowerCase();
// }
// return words.join(separator);
// }
// List<String> words(String subject, [Pattern customPattern = defaultPattern]) {
// if (subject is! String || subject.length == 0) {
// return [];
// }
// RegExp pattern;
// if (customPattern is String) {
// pattern = RegExp(customPattern);
// } else if (customPattern is RegExp) {
// pattern = customPattern;
// }
// return pattern.allMatches(subject).map((m) => m.group(0)).toList();
// }
// String camelCase(String subject) {
// List<String> _splittedString = words(subject);
// if (_splittedString.length == 0) {
// return '';
// }
// String _firstWord = lowerCase(_splittedString[0]);
// List<String> _restWords = _splittedString
// .sublist(1)
// .map((String x) => capitalize(x, true))
// .toList();
// return _firstWord + _restWords.join('');
// }
String filterAnd(String input) {
input = input.replaceAll('&amp;', '&');
return input;
}
numberFormat(String? discountPrice) {
return NumberFormat.currency(
locale: 'id',
decimalDigits: 0,
symbol: 'Rp ',
).format(int.parse(discountPrice ?? '0'));
}
customTextValidator(bool? isTextEmpty, String validatorText) {
return Text(
isTextEmpty == null
? ''
: isTextEmpty
? " $validatorText"
: '',
style: primaryTextStyle.copyWith(
color: Colors.red[700],
fontSize: 12.5,
height: isTextEmpty == null
? 0
: isTextEmpty
? null
: 0,
),
textAlign: TextAlign.start,
);
}

348
lib/main.dart Normal file
View File

@ -0,0 +1,348 @@
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:initial_folder/firebase_options.dart';
import 'package:initial_folder/get_it.dart';
import 'package:initial_folder/providers/announcement_provider.dart';
import 'package:initial_folder/providers/auth_provider.dart';
import 'package:initial_folder/providers/banners_provider.dart';
import 'package:initial_folder/providers/cart_provider.dart';
import 'package:initial_folder/providers/carts_provider.dart';
import 'package:initial_folder/providers/categories_provider.dart';
import 'package:initial_folder/providers/certificate_provider.dart';
import 'package:initial_folder/providers/checkbox_provider.dart';
import 'package:initial_folder/providers/data_diri_provider.dart';
import 'package:initial_folder/providers/detail_course_provider.dart';
import 'package:initial_folder/providers/filters_course_provider.dart';
import 'package:initial_folder/providers/firebase_authentication_provider.dart';
import 'package:initial_folder/providers/forgot_password_provider.dart';
import 'package:initial_folder/providers/incomplete_profile_provider.dart';
import 'package:initial_folder/providers/history_transactions_provider.dart';
import 'package:initial_folder/providers/latest_course_provider.dart';
import 'package:initial_folder/providers/lesson_course_provider.dart';
import 'package:initial_folder/providers/like_announcement.dart';
import 'package:initial_folder/providers/like_or_unlike_provider.dart';
import 'package:initial_folder/providers/login_provider.dart';
import 'package:initial_folder/providers/my_course_provider.dart';
import 'package:initial_folder/providers/notification_provider.dart';
import 'package:initial_folder/providers/order_provider.dart';
import 'package:initial_folder/providers/others_course_provider.dart';
import 'package:initial_folder/providers/payments_provider.dart';
import 'package:initial_folder/providers/play_video_course_provider.dart';
import 'package:initial_folder/providers/posting_announcement_reply_provider.dart';
import 'package:initial_folder/providers/posting_qna_provider.dart';
import 'package:initial_folder/providers/posting_qna_reply_provider.dart';
import 'package:initial_folder/providers/profile_image_provider.dart';
import 'package:initial_folder/providers/promo_course_provider.dart';
import 'package:initial_folder/providers/radeem_voucher_provider.dart';
import 'package:initial_folder/providers/registrasi_google_provider.dart';
import 'package:initial_folder/providers/reset_provider.dart';
import 'package:initial_folder/providers/search_provider.dart';
import 'package:initial_folder/providers/section_lesson_provider.dart';
import 'package:initial_folder/providers/selected_title_provider.dart';
import 'package:initial_folder/providers/stream_invoice_provider.dart';
import 'package:initial_folder/providers/tab_play_course_provider.dart';
import 'package:initial_folder/providers/description_provider.dart';
import 'package:initial_folder/providers/metode_provider.dart';
import 'package:initial_folder/providers/page_provider.dart';
import 'package:initial_folder/providers/profile_provider.dart';
import 'package:initial_folder/providers/tab_provider.dart';
import 'package:initial_folder/providers/top_course_provider.dart';
import 'package:initial_folder/providers/total_price_provider.dart';
import 'package:initial_folder/providers/update_data_diri_provider.dart';
import 'package:initial_folder/providers/update_password_provider.dart';
import 'package:initial_folder/providers/user_info_provider.dart';
import 'package:initial_folder/providers/whislist_provider.dart';
import 'package:initial_folder/providers/theme_provider.dart';
import 'package:initial_folder/providers/wishlist_post_provider.dart';
import 'package:initial_folder/screens/cart/cart_page.dart';
import 'package:initial_folder/screens/course/play_course_page.dart';
// import 'package:initial_folder/screens/home/components/notification.dart';
import 'package:initial_folder/screens/splash/splash_screen_login.dart';
import 'package:initial_folder/services/all_certificate_service.dart';
import 'package:initial_folder/services/announcement_service.dart';
import 'package:initial_folder/services/banners_service.dart';
import 'package:initial_folder/services/cart_service.dart';
import 'package:initial_folder/services/categories_service.dart';
import 'package:initial_folder/services/course_service.dart';
import 'package:initial_folder/services/history_transactions_service.dart';
import 'package:initial_folder/services/lesson_course_service.dart';
import 'package:initial_folder/services/notification_service.dart';
import 'package:initial_folder/services/payment_service.dart';
import 'package:initial_folder/services/search_service.dart';
import 'package:initial_folder/services/user_info_service.dart';
import 'package:initial_folder/theme.dart';
import 'package:provider/provider.dart';
import 'package:initial_folder/routes.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:responsive_framework/responsive_framework.dart';
import 'package:initial_folder/base_service.dart';
import 'package:initial_folder/providers/detail_invoice_provider.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
// Import library dan provider yang dibutuhkan untuk seluruh aplikasi
// Fungsi handler untuk pesan notifikasi Firebase yang diterima saat aplikasi di background
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// Jika ingin menggunakan service Firebase lain di background, inisialisasi dulu
// print pesan jika mode debug
}
final globalScaffoldKey = GlobalKey<ScaffoldState>();
GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
await dotenv.load();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
await FirebaseMessaging.instance.getToken();
setup();
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
FirebaseMessaging.onMessageOpenedApp.listen((event) {
if (kDebugMode) {
print(event);
}
if (event.data['route'] == "/cart") {
navigatorKey.currentState?.push(MaterialPageRoute(
builder: (context) => const CartPage(),
));
} else if (event.data['route'] == "/play_course") {
navigatorKey.currentState?.push(
MaterialPageRoute(
builder: (context) => MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => LessonCourseProvider(
lessonCourseService: LessonCourseService(),
id: int.parse(event.data['id_course'] ?? '0'),
),
),
ChangeNotifierProvider(
create: (context) => DetailCourseProvider(
courseService: CourseService(),
id: event.data['id_course'] ?? '1'))
],
child: PlayCourse(
judul: event.data['title'] ?? '',
instruktur: event.data['instructur_name'] ?? '',
thumbnail: event.data['thumbnail'] ??
"$baseUrl/uploads/courses_thumbnail/course_thumbnail_default_57.jpg",
courseeid: event.data['id_course'],
isQna: true,
),
),
),
);
}
});
ThemeProvider themeProvider = ThemeProvider();
await themeProvider.loadTheme();
runApp(MyApp(themeProvider: themeProvider));
}
class MyApp extends StatelessWidget {
const MyApp({Key? key, required this.themeProvider}) : super(key: key);
final ThemeProvider themeProvider;
@override
Widget build(BuildContext context) {
// Provider untuk Theme agar bisa diakses seluruh aplikasi
return ChangeNotifierProvider<ThemeProvider>.value(
value: themeProvider,
child: MultiProvider(
// MultiProvider: daftar semua provider yang digunakan di aplikasi
providers: [
ChangeNotifierProvider(
create: (context) => ThemeProvider(),
),
ChangeNotifierProvider(
create: (context) => StreamInvoiceProvider(),
),
ChangeNotifierProvider(
create: (context) => TabProvider(),
),
ChangeNotifierProvider(
create: (context) => DetailInvoiceProvider(),
),
ChangeNotifierProvider(
create: (context) => SelectedTitleProvider(),
),
ChangeNotifierProvider(
create: (context) => LikeOrUnlikeProvider(),
),
ChangeNotifierProvider(
create: (context) => LikeOrAnnouncementProvider(),
),
ChangeNotifierProvider(
create: (context) => AnnouncementProvider(),
),
ChangeNotifierProvider(
create: (context) => PostingQnaReplyProvider(),
),
ChangeNotifierProvider(
create: (context) => PostingAnnouncementReplyProvider(),
),
ChangeNotifierProvider(
create: (context) => ForgotPasswordProvider(),
),
ChangeNotifierProvider(
create: (context) => PostingQnaProvider(),
),
ChangeNotifierProvider(
create: (context) => DataDiriProvider(
userInfoService: UserInfoService(),
),
),
ChangeNotifierProvider(
create: (context) => UpdateDataDiriProvider(),
),
ChangeNotifierProvider(
create: (context) => UpdatePasswordProvider(),
),
ChangeNotifierProvider(
create: (context) => TabPlayCourseProvider(),
),
ChangeNotifierProvider(
create: (context) => SectionLessonProvider(),
),
ChangeNotifierProvider(
create: (context) => PageProvider(),
),
ChangeNotifierProvider(
create: (context) => ProfileImageProvider(),
),
ChangeNotifierProvider(
create: (context) => WishlistPostProvider(),
),
ChangeNotifierProvider(
create: (context) => ProfileProvider(),
),
ChangeNotifierProvider(
create: (context) => CheckboxProvider(),
),
ChangeNotifierProvider(
create: (context) => UserInfoProvider(
userInfoService: UserInfoService(),
)),
ChangeNotifierProvider(
create: (context) => NotificationProvider(
notificationServices: NotificationServices(),
)),
ChangeNotifierProvider(
create: (context) => DescriptionProvider(),
),
ChangeNotifierProvider(
create: (context) => TotalPriceProvider(),
),
ChangeNotifierProvider(
create: (context) => MetodeProvider(),
),
ChangeNotifierProvider(
create: (context) => FirebaseAuthenticationProvider(),
),
ChangeNotifierProvider(
create: (context) => RegistrasiGoogleProvider(),
),
ChangeNotifierProvider(
create: (context) => RegistrasiGoogleProvider(),
),
ChangeNotifierProvider(create: (context) => ResetProvider()),
ChangeNotifierProvider(
create: (context) => AuthProvider(),
),
ChangeNotifierProvider(
create: (context) =>
CategoriesProvider(categoriesService: CategoriesService()),
),
ChangeNotifierProvider(
create: (context) =>
BannersProvider(bannersService: BannersService()),
),
ChangeNotifierProvider(
create: (context) =>
OthersCourseProvider(otherCourseService: CourseService()),
),
ChangeNotifierProvider(
create: (context) => CartsProvider(cartService: CartService()),
),
ChangeNotifierProvider(
create: (context) => CartProvider(cartService: CartService()),
),
ChangeNotifierProvider<WishlistProvider>(
create: (context) => WishlistProvider(),
),
ChangeNotifierProvider(
create: (context) => PaymentsProvider(
paymentServices: PaymentServices(),
),
),
ChangeNotifierProvider(
create: (context) => PlayVideoCourseProvider(),
),
ChangeNotifierProvider(
create: (context) =>
MyCourseProvider(courseService: CourseService()),
),
ChangeNotifierProvider(
create: (context) =>
FilterCourseProvider(searchService: SearchService()),
),
ChangeNotifierProvider(
create: (context) => SearchProvider(searchService: SearchService()),
),
ChangeNotifierProvider(
create: (context) =>
TopCourseProvider(courseService: CourseService()),
),
ChangeNotifierProvider(
create: (context) =>
LatestCourseProvider(courseService: CourseService()),
),
ChangeNotifierProvider(
create: (context) =>
PromoCourseProvider(courseService: CourseService()),
),
ChangeNotifierProvider(create: (context) => OrderProvider()),
ChangeNotifierProvider(create: (context) => LoginProvider()),
ChangeNotifierProvider(
create: (context) => CertificateProvider(
certificateServices: AllCertificateServices())),
ChangeNotifierProvider(create: (context) => RadeemVoucherProvider()),
ChangeNotifierProvider(
create: (context) => IncompleteProfileProvider(
userInfoService: UserInfoService(),
)),
ChangeNotifierProvider(
create: (context) => HistoryTranscationsProvider(
historyTransactionService: HistoryTransactionService()))
],
child: Consumer<ThemeProvider>(builder: (context, themeProvider, child) {
// MaterialApp sebagai root aplikasi
return MaterialApp(
navigatorKey: navigatorKey, // Untuk navigasi global
builder: (context, widget) => ResponsiveBreakpoints.builder(
child: ClampingScrollWrapper.builder(context, widget!),
breakpoints: [
const Breakpoint(start: 0, end: 450, name: MOBILE),
const Breakpoint(start: 451, end: 800, name: TABLET),
const Breakpoint(start: 801, end: 1920, name: DESKTOP),
const Breakpoint(start: 1921, end: double.infinity, name: '4K'),
],
),
debugShowCheckedModeBanner: false,
title: 'Vocasia',
theme: themeProvider.themeData, // Tema aplikasi
home: const SplashScreenLogin(), // Halaman pertama (Splash)
routes: routes, // Daftar route aplikasi
);
}),
),
);
}
}

0
lib/models/.gitkeep Normal file
View File

157
lib/models/Product.dart Normal file
View File

@ -0,0 +1,157 @@
// import 'package:flutter/material.dart';
// import '../size_config.dart';
// import '../theme.dart';
// // class Product {
// // final int id;
// // final String title;
// // final RichText description;
// // final List<String> images;
// // final List<Color> colors;
// // final double rating, price, disc;
// // final bool isFavourite, isPopular;
// // Product({
// // required this.id,
// // required this.images,
// // required this.colors,
// // this.rating = 0.0,
// // this.isFavourite = false,
// // this.isPopular = false,
// // required this.title,
// // required this.price,
// // required this.disc,
// // required this.description,
// // });
// // }
// // Our demo Products
// final TextStyle light = primaryTextStyle.copyWith(
// letterSpacing: 0.5,
// color: secondaryColor,
// fontSize: getProportionateScreenWidth(10),
// fontWeight: reguler);
// final TextStyle thick = primaryTextStyle.copyWith(
// letterSpacing: 0.5,
// color: secondaryColor,
// fontSize: getProportionateScreenWidth(10),
// fontWeight: semiBold);
// List<Product> demoProducts = [
// Product(
// id: 1,
// images: [
// "assets/images/Kur1.png",
// ],
// colors: [
// Color(0xFFF6625E),
// Color(0xFF836DB8),
// Color(0xFFDECB9C),
// Colors.white,
// ],
// title: "Menjadi Pengusaha Sukses dan Bertalenta",
// price: 250000,
// disc: 1250000,
// description: RichText(
// text: new TextSpan(
// // Note: Styles for TextSpans must be explicitly defined.
// // Child text spans will inherit styles from parent
// style: TextStyle(
// fontSize: 10, color: Colors.white, fontWeight: FontWeight.w300),
// //maxLines: 1,
// children: <TextSpan>[
// new TextSpan(text: 'Oleh ', style: light),
// new TextSpan(text: 'Farid Subkhan', style: thick),
// ],
// ),
// ),
// rating: 4.8,
// isFavourite: true,
// isPopular: true,
// ),
// Product(
// id: 2,
// images: [
// "assets/images/Kur2.png",
// ],
// colors: [
// Color(0xFFF6625E),
// Color(0xFF836DB8),
// Color(0xFFDECB9C),
// Colors.white,
// ],
// title: "Kiat Menjadi Youtuber",
// price: 500500,
// disc: 1500000,
// description: RichText(
// text: new TextSpan(
// // Note: Styles for TextSpans must be explicitly defined.
// // Child text spans will inherit styles from parent
// style: TextStyle(fontSize: 10, fontWeight: FontWeight.w300),
// children: <TextSpan>[
// new TextSpan(text: 'Oleh ', style: light),
// new TextSpan(text: 'Farid Subkhan', style: thick),
// ],
// ),
// ),
// rating: 4.1,
// isPopular: true,
// ),
// Product(
// id: 3,
// images: [
// "assets/images/Kur3.png",
// ],
// colors: [
// Color(0xFFF6625E),
// Color(0xFF836DB8),
// Color(0xFFDECB9C),
// Colors.white,
// ],
// title: "Menjadi Pengusaha Sukses dan Berjiwa Entrepreneur",
// price: 365500,
// disc: 1500000,
// description: RichText(
// text: new TextSpan(
// // Note: Styles for TextSpans must be explicitly defined.
// // Child text spans will inherit styles from parent
// style: TextStyle(fontSize: 10, fontWeight: FontWeight.w300),
// children: <TextSpan>[
// new TextSpan(text: 'Oleh ', style: light),
// new TextSpan(text: 'Ali Sanjani', style: thick),
// ],
// ),
// ),
// rating: 4.1,
// isFavourite: true,
// isPopular: true,
// ),
// Product(
// id: 4,
// images: [
// "assets/images/Kur4.png",
// ],
// colors: [
// Color(0xFFF6625E),
// Color(0xFF836DB8),
// Color(0xFFDECB9C),
// Colors.white,
// ],
// title: "Menguasai Excel dengan Cepat dan Handal Banget",
// price: 200500,
// disc: 1000000,
// description: RichText(
// text: new TextSpan(
// // Note: Styles for TextSpans must be explicitly defined.
// // Child text spans will inherit styles from parent
// style: TextStyle(fontSize: 10, fontWeight: FontWeight.w300),
// children: <TextSpan>[
// new TextSpan(text: 'Oleh ', style: light),
// new TextSpan(text: 'Ali Sanjani', style: thick),
// ],
// ),
// ),
// rating: 4.1,
// isFavourite: true,
// isPopular: true,
// ),
// ];

View File

@ -0,0 +1,38 @@
class ProductProgram {
final int id;
final List<String> images;
ProductProgram({
required this.id,
required this.images,
});
}
// Our demo Products
List<ProductProgram> demoProducts = [
ProductProgram(
id: 1,
images: [
"assets/images/workshop.png",
],
),
ProductProgram(
id: 2,
images: [
"assets/images/prakerja.png",
],
),
ProductProgram(
id: 3,
images: [
"assets/images/workshop.png",
],
),
ProductProgram(
id: 4,
images: [
"assets/images/prakerja.png",
],
),
];

View File

@ -0,0 +1,338 @@
import 'package:initial_folder/models/reply_announcement_model.dart';
class AnnouncementModel {
AnnouncementModel({
this.status,
this.error,
required this.data,
});
final int? status;
final bool? error;
final List<List<AnnouncementDataModel>> data;
factory AnnouncementModel.fromJson(Map<String, dynamic> json) =>
AnnouncementModel(
status: json["status"],
error: json["error"],
data: List<List<AnnouncementDataModel>>.from(json["data"].map((x) =>
List<AnnouncementDataModel>.from(
x.map((x) => AnnouncementDataModel.fromJson(x))))),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": List<dynamic>.from(
data.map((x) => List<dynamic>.from(x.map((x) => x.toJson())))),
};
}
class AnnouncementDataModel {
AnnouncementDataModel({
this.idAnnouncement,
this.tokenAnnouncement,
this.instructorName,
this.fotoProfile,
this.bodyContent,
this.countLike,
this.likes,
this.isLike,
this.comment,
this.date,
required this.replies,
});
final String? idAnnouncement;
final String? tokenAnnouncement;
final String? instructorName;
final String? fotoProfile;
final String? bodyContent;
final String? countLike;
final bool? likes;
final int? isLike;
final int? comment;
final String? date;
final List<ReplyModel> replies;
factory AnnouncementDataModel.fromJson(Map<String, dynamic> json) =>
AnnouncementDataModel(
idAnnouncement: json["id_announcement"],
tokenAnnouncement: json["token_announcement"],
instructorName: json["instructor_name"],
bodyContent: json["body"],
fotoProfile: json["foto_profile"],
likes: json["likes"].length > 0,
isLike: json["is_like"],
countLike: json["count_likes"],
comment: json["comment"],
date: json["date"],
replies: List<ReplyModel>.from(
json["replies"].map((x) => ReplyModel.fromJson(x))).toList(),
);
Map<String, dynamic> toJson() => {
"id_announcement": idAnnouncement,
"token_announcement": tokenAnnouncement,
"instructor_name": instructorName,
"body": bodyContent,
"foto_profile": fotoProfile,
"likes": likes,
"is_like": isLike,
"comment": comment,
"date": date,
"replies": List<ReplyModel>.from(replies.map((x) => x)),
};
}
class AnnouncementPostModel {
AnnouncementPostModel({
this.status,
this.error,
required this.data,
});
final int? status;
final bool? error;
final DataPostAnnouncement data;
factory AnnouncementPostModel.fromJson(Map<String, dynamic> json) =>
AnnouncementPostModel(
status: json["status"],
error: json["error"],
data: DataPostAnnouncement.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": data.toJson(),
};
}
class DataPostAnnouncement {
DataPostAnnouncement({this.idUser, this.idCourse, this.body});
final String? idUser;
final String? idCourse;
final String? body;
factory DataPostAnnouncement.fromJson(Map<String, dynamic> json) =>
DataPostAnnouncement(
idUser: json["id_user"],
idCourse: json["course_id"],
body: json["body"],
);
Map<String, dynamic> toJson() => {
"id_user": idUser,
"id_course": idCourse,
"body": body,
};
}
class AnnouncementLikeModel {
AnnouncementLikeModel({
this.userLikes,
});
final String? userLikes;
factory AnnouncementLikeModel.fromJson(Map<String, dynamic> json) =>
AnnouncementLikeModel(
userLikes: json["user_likes"],
);
Map<String, dynamic> toJson() => {
"user_likes": userLikes,
};
}
class SectionModel {
SectionModel({
this.status,
this.error,
this.progress,
required this.data,
});
int? status;
bool? error;
int? progress;
List<Map<String, Datum>> data;
factory SectionModel.fromJson(Map<String, dynamic> json) => SectionModel(
status: json["status"],
error: json["error"],
progress: json["progress"],
data: List<Map<String, Datum>>.from(json["data"].map((x) => Map.from(x)
.map((k, v) => MapEntry<String, Datum>(k, Datum.fromJson(v))))),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"progress": progress,
"data": List<dynamic>.from(data.map((x) => Map.from(x)
.map((k, v) => MapEntry<String, dynamic>(k, v.toJson())))),
};
}
class Datum {
Datum({
this.sectionTitle,
this.dataLesson,
});
String? sectionTitle;
List<DataLesson>? dataLesson;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
sectionTitle: json["section_title"],
dataLesson: List<DataLesson>.from(
json["data_lesson"].map((x) => DataLesson.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"section_title": sectionTitle,
"data_lesson": List<dynamic>.from(dataLesson!.map((x) => x.toJson())),
};
}
class DataLesson {
DataLesson({
this.lessonId,
this.title,
this.duration,
this.attachmentType,
this.videoType,
this.videoUrl,
this.lessonType,
this.attachment,
this.isSkip,
this.isFinished,
this.summary,
});
String? lessonId;
String? title;
String? duration;
String? attachmentType;
String? videoType;
String? videoUrl;
String? lessonType;
dynamic attachment;
String? isSkip;
String? summary;
int? isFinished;
factory DataLesson.fromJson(Map<String, dynamic> json) => DataLesson(
lessonId: json["lesson_id"],
title: json["title"],
duration: json["duration"],
attachmentType: json["attachment_type"],
videoType: json["video_type"],
videoUrl: json["video_url"],
lessonType: json["lesson_type"],
attachment: json["attachment"],
isSkip: json["is_skip"],
isFinished: json["is_finished"],
summary: json["summary"],
);
get courseId => null;
Map<String, dynamic> toJson() => {
"lesson_id": lessonId,
"title": title,
"duration": duration,
"attachment_type": attachmentType,
"video_type": videoType,
"video_url": videoUrl,
"lesson_type": lessonType,
"attachment": attachment,
"is_skip": isSkip,
"is_finished": isFinished,
"summary": summary,
};
}
class NewMap {
NewMap({
required this.title,
});
final List<Title> title;
factory NewMap.fromMap(Map<String, dynamic> json) => NewMap(
title: List<Title>.from(json["Title"].map((x) => Title.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"Title": List<dynamic>.from(title.map((x) => x.toMap())),
};
}
class Title {
Title({
this.courseId,
this.lessonId,
this.sectionTitle,
this.lessonTitle,
this.duration,
this.attachmentType,
this.videoType,
this.videoUrl,
this.lessonType,
this.attachment,
this.isSkip,
this.isFinished,
this.summary,
});
final String? courseId;
final String? lessonId;
final String? sectionTitle;
final String? lessonTitle;
final String? duration;
final String? attachmentType;
final String? videoType;
final String? videoUrl;
final String? lessonType;
final dynamic attachment;
final String? isSkip;
final String? summary;
final int? isFinished;
factory Title.fromMap(Map<String, dynamic> json) => Title(
courseId: json["course_id"],
lessonId: json["lesson_id"],
sectionTitle: json["section_title"],
lessonTitle: json["lesson_title"],
duration: json["duration"],
attachmentType: json["attachment_type"],
videoType: json["video_type"],
videoUrl: json["video_url"] == '' ? 'a' : json["video_url"],
lessonType: json["lesson_type"],
attachment: json["attachment"],
isSkip: json["is_skip"],
isFinished: json["is_finished"],
summary: json["summary"],
);
Map<String, dynamic> toMap() => {
"course_id": courseId,
"lesson_id": lessonId,
"section_title": sectionTitle,
"lesson_title": lessonTitle,
"duration": duration,
"attachment_type": attachmentType,
"video_type": videoType,
"video_url": videoUrl,
"lesson_type": lessonType,
"attachment": attachment,
"is_skip": isSkip,
"is_finished": isFinished,
"summary": summary,
};
}

View File

@ -0,0 +1,30 @@
class BannersModel {
BannersModel({
this.id,
this.status,
this.img,
this.url,
this.courseId = '',
});
String? id;
String? status;
String? img;
String? url;
String courseId = '';
BannersModel.fromJson(Map<String, dynamic> json) {
id = json["id"];
status = json["status"];
img = json["img"];
url = json["url"];
courseId = json["course_id"] ?? '';
}
Map<String, dynamic> toJson() => {
'id': id,
'status': status,
'img': img,
'url': url,
'course_id': courseId,
};
}

View File

@ -0,0 +1,39 @@
class CartModel {
CartModel({
this.status,
this.error,
required this.data,
});
final int? status;
final bool? error;
final Data data;
factory CartModel.fromJson(Map<String, dynamic> json) => CartModel(
status: json["status"],
error: json["error"],
data: Data.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": data.toJson(),
};
}
class Data {
Data({
this.messages,
});
final String? messages;
factory Data.fromJson(Map<String, dynamic> json) => Data(
messages: json["messages"],
);
Map<String, dynamic> toJson() => {
"messages": messages,
};
}

165
lib/models/carts_model.dart Normal file
View File

@ -0,0 +1,165 @@
import 'package:equatable/equatable.dart';
class CartsModel extends Equatable {
CartsModel({
this.status,
this.error,
required this.data,
this.totalPayment,
this.potonganKupon,
});
final int? status;
final bool? error;
final List<DataCartsModel> data;
final int? potonganKupon;
final String? totalPayment;
factory CartsModel.fromJson(Map<String, dynamic> json) => CartsModel(
status: json["status"],
error: json["error"],
data: List<DataCartsModel>.from(
json["data"].map((x) => DataCartsModel.fromJson(x))),
potonganKupon: json["potongan_kupon"],
totalPayment: json["total_payment"],
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
"total_payment": totalPayment,
};
@override
// TODO: implement props
List<Object?> get props => [];
}
class DataCartsModel extends Equatable {
DataCartsModel({
this.cartId,
this.courseId,
this.title,
this.price,
this.instructor,
this.thumbnail,
this.discountPrice,
this.discountFlag,
this.totalDiscount,
this.student,
required this.review,
this.fotoProfile,
this.coupon,
this.finalPrice,
this.potonganKupon,
});
final String? cartId;
final String? courseId;
final String? title;
final String? price;
final String? instructor;
final String? thumbnail;
final String? discountPrice;
final String? discountFlag;
final int? totalDiscount;
final String? student;
final List<Review> review;
final dynamic fotoProfile;
final Coupon? coupon;
final String? finalPrice;
final String? potonganKupon;
factory DataCartsModel.fromJson(Map<String, dynamic> json) => DataCartsModel(
cartId: json["cart_id"],
courseId: json["course_id"],
title: json["title"],
price: json["price"],
instructor: json["instructor"],
thumbnail: json["thumbnail"],
discountPrice: json["discount_price"],
discountFlag: json["discount_flag"],
totalDiscount: json["total_discount"],
student: json["student"],
review:
List<Review>.from(json["review"].map((x) => Review.fromJson(x))),
fotoProfile: json["foto_profile"],
coupon: json["coupon"] == null ? null : Coupon.fromJson(json["coupon"]),
potonganKupon: json["potongan_kupon"],
finalPrice: json["final_price"],
);
Map<String, dynamic> toJson() => {
"cart_id": cartId,
"course_id": courseId,
"title": title,
"price": price,
"instructor": instructor,
"thumbnail": thumbnail,
"discount_price": discountPrice,
"discount_flag": discountFlag,
"total_discount": totalDiscount,
"student": student,
"review": List<dynamic>.from(review.map((x) => x.toJson())),
"foto_profile": fotoProfile,
"coupon": coupon,
"final_price": finalPrice
};
@override
// TODO: implement props
List<Object?> get props => [finalPrice];
}
class Coupon {
Coupon({
this.id,
this.typeCoupon,
this.codeCoupon,
this.value,
this.finalPrice,
});
final String? id;
final String? typeCoupon;
final String? codeCoupon;
final String? value;
final int? finalPrice;
factory Coupon.fromJson(Map<String, dynamic> json) => Coupon(
id: json["id"],
typeCoupon: json["type_coupon"],
codeCoupon: json["code_coupon"],
value: json["value"],
finalPrice: json["final_price"],
);
Map<String, dynamic> toJson() => {
"id": id,
"type_coupon": typeCoupon,
"code_coupon": codeCoupon,
"value": value,
"final_price": finalPrice,
};
}
class Review {
Review({
this.totalReview,
this.avgRating,
});
final String? totalReview;
final int? avgRating;
factory Review.fromJson(Map<String, dynamic> json) => Review(
totalReview: json["total_review"],
avgRating: json["avg_rating"] == null ? null : json["avg_rating"],
);
Map<String, dynamic> toJson() => {
"total_review": totalReview,
"avg_rating": avgRating == null ? null : avgRating,
};
}

View File

@ -0,0 +1,47 @@
import 'package:initial_folder/models/subcategories_model.dart';
class CategoriesModel {
CategoriesModel({
this.id,
this.nameCategory,
this.slugCategory,
this.parentCategory,
this.fontAwesomeClass,
this.subCategories,
this.subId,
});
final String? id;
final String? nameCategory;
final String? slugCategory;
final String? parentCategory;
final String? fontAwesomeClass;
final String? subId;
List<SubCategoryModel>? subCategories;
factory CategoriesModel.fromJson(Map<String, dynamic> json) {
List<dynamic> subCategoriesJson = json['subcategories'] ?? [];
List<SubCategoryModel> subCategories = subCategoriesJson
.map((subCategoryJson) => SubCategoryModel.fromJson(subCategoryJson))
.toList();
return CategoriesModel(
id: json["id"],
nameCategory: json["name_category"],
slugCategory: json["slug_category"],
parentCategory: json["parent_category"],
fontAwesomeClass: json["font_awesome_class"],
subId: json["sub_category_id"],
subCategories: subCategories,
);
}
Map<String, dynamic> toJson() => {
"id": id,
"name_category": nameCategory,
"slug_category": slugCategory,
"parent_category": parentCategory,
"font_awesome_class": fontAwesomeClass,
"sub_category_id": subId
};
}

View File

@ -0,0 +1,48 @@
class CertificateModel {
final String? idPayment;
final String? name;
final String? title;
final int? finishDate;
final String? certificateNo;
CertificateModel({
this.idPayment,
this.name,
this.title,
this.finishDate,
required this.certificateNo,
});
factory CertificateModel.fromJson(Map<String, dynamic> json) =>
CertificateModel(
name: json['name'],
title: json['title'],
finishDate: json['finish_date'],
certificateNo: json['certificate_no'],
idPayment: json['id_enrol'],
);
Map<String, dynamic> toJson() => {
'id_enrol': idPayment,
'name': name,
'title': title,
'finishDate': finishDate,
'certificate_no': certificateNo,
};
}
class CertificateNo {
CertificateNo({
this.idPayment,
});
String? idPayment;
factory CertificateNo.fromJson(Map<String, dynamic> json) => CertificateNo(
idPayment: json["id_payment"],
);
Map<String, dynamic> toJson() => {
"id_payment": idPayment,
};
}

View File

@ -0,0 +1,74 @@
class CheckCertificate {
int? status;
bool? error;
List<CheckCertificateData>? data;
CheckCertificate({this.status, this.error, this.data});
CheckCertificate.fromJson(Map<String, dynamic> json) {
status = json['status'];
error = json['error'];
if (json['data'] != null) {
data = <CheckCertificateData>[];
json['data'].forEach((v) {
data!.add(new CheckCertificateData.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
data['error'] = this.error;
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
return data;
}
}
class CheckCertificateData {
String? idPayment;
String? userId;
String? courseId;
String? name;
String? title;
dynamic finishDate;
String? certificateNo;
int? progress;
CheckCertificateData({
this.idPayment,
this.userId,
this.courseId,
this.name,
this.title,
this.finishDate,
this.certificateNo,
this.progress,
});
CheckCertificateData.fromJson(Map<String, dynamic> json) {
idPayment = json['id_enrol'];
userId = json['user_id'];
courseId = json['course_id'];
name = json['name'];
title = json['title'];
finishDate = json['finish_date'];
certificateNo = json['certificate_no'];
progress = json['progress'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id_enrol'] = this.idPayment;
data['user_id'] = this.userId;
data['course_id'] = this.courseId;
data['name'] = this.name;
data['title'] = this.title;
data['finish_date'] = this.finishDate;
data['certificate_no'] = this.certificateNo;
data['progress'] = this.progress;
return data;
}
}

View File

@ -0,0 +1,51 @@
class Comment {
Comment({
this.idRep,
this.sender,
this.username,
this.textRep,
this.fotoProfile,
this.createAt,
});
String? idRep;
String? sender;
String? username;
String? textRep;
String? fotoProfile;
String? createAt;
factory Comment.fromJson(Map<String, dynamic> json) => Comment(
idRep: json["id_rep"],
sender: json["sender"],
username: json["username"],
textRep: json["text_rep"],
fotoProfile: json["foto_profile"],
createAt: json["create_at"],
);
Map<String, dynamic> toJson() => {
"id_rep": idRep,
"sender": sender,
"username": username,
"text_rep": textRep,
"foto_profile": fotoProfile,
"create_at": createAt,
};
}
class LikeModels {
LikeModels({
this.userId,
});
bool? userId;
factory LikeModels.fromJson(Map<String, dynamic> json) => LikeModels(
userId: json["user_id"].length > 0,
);
Map<String, dynamic> toJson() => {
"id_rep": userId,
};
}

View File

@ -0,0 +1,40 @@
class CounterCommentModel {
CounterCommentModel({
this.status,
this.error,
required this.data,
});
final int? status;
final bool? error;
String? data;
factory CounterCommentModel.fromJson(Map<String, dynamic> json) =>
CounterCommentModel(
status: json["status"],
error: json["error"],
data: (json["data"]["count comment "]).toString(),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": data,
};
}
// class CounterComment {
// CounterComment({
// this.countCommentQna,
// });
// String? countCommentQna;
// factory CounterComment.fromJson(Map<String, dynamic> json) => CounterComment(
// countCommentQna: json["count comment"],
// );
// Map<String, dynamic> toJson() => {
// "count comment": countCommentQna,
// };
// }

View File

@ -0,0 +1,24 @@
class CounterLikeModel {
CounterLikeModel({
this.status,
this.error,
required this.data,
});
final int? status;
final bool? error;
String? data;
factory CounterLikeModel.fromJson(Map<String, dynamic> json) =>
CounterLikeModel(
status: json["status"],
error: json["error"],
data: (json["data"]["count like "]).toString(),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": data,
};
}

View File

@ -0,0 +1,80 @@
import 'package:initial_folder/models/rating_course_model.dart';
class CourseModel {
CourseModel({
this.idCourse = '',
this.instructorId = '',
this.title = '',
this.price = '',
this.instructorName = '',
this.discountFlag,
this.discountPrice = '',
this.promoPrice = '',
this.thumbnail,
this.students,
required this.rating,
this.totalDiscount,
this.fotoProfile,
this.topCourse,
this.isFreeCourse,
});
String idCourse;
String instructorId;
String title;
String price;
String instructorName;
String? discountFlag;
String discountPrice;
String promoPrice;
String? thumbnail;
String? students;
List<Rating?> rating;
int? totalDiscount;
String? fotoProfile;
String? topCourse;
String? isFreeCourse;
factory CourseModel.fromJson(Map<String, dynamic> json) => CourseModel(
idCourse: json["id_course"] ?? '',
instructorId: json["instructor_id"] ?? '',
title: json["title"] ?? '',
price: json["price"] ?? '',
instructorName: json["instructor_name"] ?? '',
discountFlag: json["discount_flag"] ?? '',
discountPrice: json["discount_price"].toString() != "0"
? (int.parse(json["price"]) - int.parse(json["discount_price"]))
.toString()
: json["price"] ?? '',
promoPrice: json["promo_price"].toString() != '0'
? json["promo_price"].toString()
: json["promo_price"].toString(),
thumbnail: json["thumbnail"],
students: json["students"] ?? '',
rating: List<Rating>.from(json["rating"].map((x) => Rating.fromJson(x)))
.toList() ??
[],
totalDiscount: json["total_discount"] ?? 0,
fotoProfile: json["foto_profile"] ?? '',
topCourse: json["top_course"] ?? '',
isFreeCourse: json["is_free_course"] ?? '',
);
Map<String, dynamic> toJson() => {
"id_course": idCourse,
"instructor_id": instructorId,
"title": title,
"price": price,
"instructor_name": instructorName,
"discount_flag": discountFlag,
"discount_price": discountPrice,
"promo_price": promoPrice,
"thumbnail": thumbnail,
"students": students,
"rating": List<dynamic>.from(rating.map((x) => x!.toJson())).toList(),
"total_discount": totalDiscount,
"foto_profile": fotoProfile,
"top_course": topCourse,
"is_free_course": isFreeCourse,
};
}

View File

@ -0,0 +1,105 @@
class DataDiriModel {
DataDiriModel({
this.status,
this.error,
required this.data,
});
int? status;
bool? error;
List<DataOfDataDiriModel> data;
factory DataDiriModel.fromJson(Map<String, dynamic> json) => DataDiriModel(
status: json["status"],
error: json["error"],
data: List<DataOfDataDiriModel>.from(
json["data"].map((x) => DataOfDataDiriModel.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class DataOfDataDiriModel {
DataOfDataDiriModel({
this.idUser,
this.fullname,
this.headline,
this.biography,
this.datebirth,
this.email,
this.phone,
this.gender,
this.socialLink,
});
String? idUser;
String? fullname;
String? headline;
String? biography;
String? datebirth;
String? email;
String? phone;
String? gender;
SocialLink? socialLink;
factory DataOfDataDiriModel.fromJson(Map<String, dynamic> json) =>
DataOfDataDiriModel(
idUser: json["id_user"],
fullname: json["full_name"],
headline: json["headline"],
biography: json["biography"],
datebirth: json["datebirth"],
email: json["email"],
phone: json["phone"],
gender: json["jenis_kelamin"] == null
? ''
: json["jenis_kelamin"],
socialLink: json["social_link"] == null
? null
: SocialLink.fromJson(json["social_link"]),
);
Map<String, dynamic> toJson() => {
"id_user": idUser,
"full_name": fullname,
"headline": headline,
"biography": biography,
"datebirth": datebirth,
"email": email,
"phone": phone,
"jenis_kelamin": gender,
"social_link": socialLink == null ? null : socialLink!.toJson(),
};
}
class SocialLink {
SocialLink({
this.facebook,
this.twitter,
this.instagram,
this.linkedin,
});
String? facebook;
String? twitter;
String? instagram;
String? linkedin;
factory SocialLink.fromJson(Map<String, dynamic> json) => SocialLink(
facebook: json["facebook"],
twitter: json["twitter"],
instagram: json["instagram"],
linkedin: json["linkedin"],
);
Map<String, dynamic> toJson() => {
"facebook": facebook,
"twitter": twitter,
"instagram": instagram,
"linkedin": linkedin,
};
}

View File

@ -0,0 +1,85 @@
class DetailCourseCoupon {
int? status;
bool? error;
List<DataDetailCourseCoupon>? data;
DetailCourseCoupon({this.status, this.error, this.data});
DetailCourseCoupon.fromJson(Map<String, dynamic> json) {
status = json['status'];
error = json['error'];
if (json['data'] != null) {
data = <DataDetailCourseCoupon>[];
json['data'].forEach((v) {
data!.add(new DataDetailCourseCoupon.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
data['error'] = this.error;
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
return data;
}
}
class DataDetailCourseCoupon {
String? idCourse;
String? typeCoupon;
String? value;
String? discountFlag;
String? courseName;
String? instructor;
String? fotoProfile;
String? thubmnail;
String? originalPrice;
int? discountPrice;
int? finalPrice;
DataDetailCourseCoupon(
{this.idCourse,
this.typeCoupon,
this.value,
this.discountFlag,
this.courseName,
this.instructor,
this.fotoProfile,
this.thubmnail,
this.originalPrice,
this.discountPrice,
this.finalPrice});
DataDetailCourseCoupon.fromJson(Map<String, dynamic> json) {
idCourse = json['id_course'];
typeCoupon = json['type_coupon'];
value = json['value'];
discountFlag = json['discount_flag'];
courseName = json['course_name'];
instructor = json['instructor'];
fotoProfile = json['foto_profile'];
thubmnail = json['thubmnail'];
originalPrice = json['original_price'];
discountPrice = json['discount_price'];
finalPrice = json['final_price'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id_course'] = this.idCourse;
data['type_coupon'] = this.typeCoupon;
data['value'] = this.value;
data['discount_flag'] = this.discountFlag;
data['course_name'] = this.courseName;
data['instructor'] = this.instructor;
data['foto_profile'] = this.fotoProfile;
data['thubmnail'] = this.thubmnail;
data['original_price'] = this.originalPrice;
data['discount_price'] = this.discountPrice;
data['final_price'] = this.finalPrice;
return data;
}
}

View File

@ -0,0 +1,219 @@
import 'package:initial_folder/models/rating_course_model.dart';
// To parse this JSON data, do
//
// final detailCourseModel = detailCourseModelFromJson(jsonString);
import 'dart:convert';
DetailCourseModel detailCourseModelFromJson(String str) =>
DetailCourseModel.fromJson(json.decode(str));
String detailCourseModelToJson(DetailCourseModel data) =>
json.encode(data.toJson());
class DetailCourseModel {
DetailCourseModel({
this.status,
this.error,
required this.data,
});
final int? status;
final bool? error;
final List<List<DataDetailCourseModel>> data;
factory DetailCourseModel.fromJson(Map<String, dynamic> json) =>
DetailCourseModel(
status: json["status"],
error: json["error"],
data: List<List<DataDetailCourseModel>>.from(json["data"].map((x) =>
List<DataDetailCourseModel>.from(
x.map((x) => DataDetailCourseModel.fromJson(x))))),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": List<dynamic>.from(
data.map((x) => List<dynamic>.from(x.map((x) => x.toJson())))),
};
}
class DataDetailCourseModel {
DataDetailCourseModel(
{required this.id,
this.title,
this.instructorId,
this.instructor,
this.shortDescription,
this.levelCourse,
this.totalLesson,
this.totalStudents,
this.description,
this.outcome,
this.requirement,
this.price,
this.discountPrice,
this.discountFlag,
this.videoUrl,
this.totalDuration,
this.bio,
required this.rating,
this.totalDiscount,
this.lastModified,
this.fotoProfile,
this.thumbnail,
this.isFreeCourse,
this.isMine,
required this.breadcrumbs,
this.headlineInstructor,
this.status_course,
this.checkoutPrice,
this.typeCoupon,
this.value,
this.courseName,
this.originalPrice,
this.finalPrice,
this.promoPrice});
final String id;
final String? title;
final String? instructorId;
final String? instructor;
final String? shortDescription;
final String? levelCourse;
final String? totalLesson;
final String? totalStudents;
final String? description;
final String? outcome;
final String? requirement;
final String? price;
final String? discountPrice;
final String? discountFlag;
final String? videoUrl;
final String? totalDuration;
final String? bio;
final List<Rating> rating;
final int? totalDiscount;
final String? lastModified;
final dynamic fotoProfile;
final String? thumbnail;
final String? isFreeCourse;
final dynamic isMine;
final Breadcrumbs breadcrumbs;
final String? status_course;
final String? headlineInstructor;
final String? typeCoupon;
final String? value;
final String? courseName;
final String? originalPrice;
final String? finalPrice;
final int? checkoutPrice;
final String? promoPrice;
factory DataDetailCourseModel.fromJson(Map<String, dynamic> json) =>
DataDetailCourseModel(
id: json["id"],
title: json["title"],
instructorId: json["instructor_id"],
instructor: json["instructor"],
shortDescription: json["short_description"],
levelCourse: json["level_course"],
totalLesson: json["total_lesson"],
totalStudents: json["total_students"],
description: json["description"] == null ? '' : json["description"],
outcome: json["outcome"] == "[]" ? '' : json["outcome"],
requirement: json["requirement"],
price: json["price"].toString(),
discountPrice: json["discount_price"].toString() != "0"
? json["discount_price"].toString()
: "0",
discountFlag: json["discount_flag"],
videoUrl: json["video_url"],
totalDuration: json["total_duration"],
bio: json["bio"],
rating:
List<Rating>.from(json["rating"].map((x) => Rating.fromJson(x))),
totalDiscount: json["total_discount"],
lastModified: json["last_modified"],
fotoProfile: json["foto_profile"],
thumbnail: json["thumbnail"],
isFreeCourse: json["is_free_course"],
isMine: json["is_mine"],
breadcrumbs: Breadcrumbs.fromJson(json["breadcrumbs"]),
headlineInstructor: json['headline'],
status_course: json["status_course"],
checkoutPrice: json["checkout_price"],
typeCoupon: json["type_coupon"],
value: json["value"],
courseName: json["course_name"],
originalPrice: json["original_price"],
finalPrice: json["final_price"],
promoPrice: json["promo_price"].toString() != '0'
? json["promo_price"].toString()
: json["promo_price"].toString(),
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"instructor_id": instructorId,
"instructor": instructor,
"short_description": shortDescription,
"level_course": levelCourse,
"total_lesson": totalLesson,
"total_students": totalStudents,
"description": description,
"outcome": outcome,
"requirement": requirement,
"price": price,
"discount_price": discountPrice,
"discount_flag": discountFlag,
"video_url": videoUrl,
"total_duration": totalDuration,
"bio": bio,
"rating": List<dynamic>.from(rating.map((x) => x.toJson())),
"total_discount": totalDiscount,
"last_modified": lastModified,
"foto_profile": fotoProfile,
"thumbnail": thumbnail,
"is_free_course": isFreeCourse,
"is_mine": isMine,
"breadcrumbs": breadcrumbs.toJson(),
"checkout_price": checkoutPrice,
"type_coupon": typeCoupon,
"value": value,
"course_name": courseName,
"original_price": originalPrice,
"final_price": finalPrice,
"promo_price": promoPrice,
};
}
class Breadcrumbs {
Breadcrumbs({
this.idCategory,
this.parentName,
this.subCategoryId,
this.subParentCategory,
});
final String? idCategory;
final String? parentName;
final String? subCategoryId;
final String? subParentCategory;
factory Breadcrumbs.fromJson(Map<String, dynamic> json) => Breadcrumbs(
idCategory: json["id_category"],
parentName: json["parent_name"],
subCategoryId: json["sub_category_id"],
subParentCategory: json["sub_parent_category"],
);
Map<String, dynamic> toJson() => {
"id_category": idCategory,
"parent_name": parentName,
"sub_category_id": subCategoryId,
"sub_parent_category": subParentCategory,
};
}

View File

@ -0,0 +1,168 @@
class DetailInvoiceModel {
int? status;
bool? error;
List<DataDetailInvoiceModel>? data;
DetailInvoiceModel({this.status, this.error, this.data});
DetailInvoiceModel.fromJson(Map<String, dynamic> json) {
status = json['status'];
error = json['error'];
if (json['data'] != null) {
data = <DataDetailInvoiceModel>[];
json['data'].forEach((v) {
data!.add(new DataDetailInvoiceModel.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
data['error'] = this.error;
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
return data;
}
}
class DataDetailInvoiceModel {
String? statusCode;
String? transactionId;
String? grossAmount;
String? currency;
String? orderId;
String? paymentType;
String? signatureKey;
String? transactionStatus;
String? fraudStatus;
String? statusMessage;
String? merchantId;
String? permataVaNumber;
String? transactionTime;
String? expiryTime;
String? billerCode;
String? billKey;
String? store;
String? paymentCode;
String? bank;
String? maskedCard;
List<VaNumbersModel>? vaNumbers;
DataDetailInvoiceModel({
this.statusCode,
this.transactionId,
this.grossAmount,
this.currency,
this.orderId,
this.paymentType,
this.signatureKey,
this.transactionStatus,
this.fraudStatus,
this.statusMessage,
this.merchantId,
this.permataVaNumber,
this.transactionTime,
this.expiryTime,
this.billerCode,
this.billKey,
this.vaNumbers,
this.store,
this.paymentCode,
this.bank,
this.maskedCard,
});
DataDetailInvoiceModel.fromJson(Map<String, dynamic> json) {
statusCode = json['status_code'];
transactionId = json['transaction_id'];
grossAmount = json['gross_amount'];
currency = json['currency'];
orderId = json['order_id'];
paymentType = json['payment_type'];
bank = json['bank'];
signatureKey = json['signature_key'];
transactionStatus = json['transaction_status'];
fraudStatus = json['fraud_status'];
statusMessage = json['status_message'];
merchantId = json['merchant_id'];
permataVaNumber = json['permata_va_number'];
transactionTime = json['transaction_time'];
expiryTime = json['expiry_time'];
billerCode = json['biller_code'];
billKey = json['bill_key'];
store = json['store'];
paymentCode = json['payment_code'];
maskedCard = json['masked_card'];
if (json['va_numbers'] != null) {
vaNumbers = <VaNumbersModel>[];
json['va_numbers'].forEach((v) {
vaNumbers!.add(new VaNumbersModel.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status_code'] = this.statusCode;
data['transaction_id'] = this.transactionId;
data['gross_amount'] = this.grossAmount;
data['currency'] = this.currency;
data['order_id'] = this.orderId;
data['payment_type'] = this.paymentType;
data['signature_key'] = this.signatureKey;
data['transaction_status'] = this.transactionStatus;
data['fraud_status'] = this.fraudStatus;
data['status_message'] = this.statusMessage;
data['merchant_id'] = this.merchantId;
data['permata_va_number'] = this.permataVaNumber;
data['transaction_time'] = this.transactionTime;
data['expiry_time'] = this.expiryTime;
data['biller_code'] = this.billerCode;
data['bill_key'] = this.billKey;
data['store'] = this.store;
data['payment_code'] = this.paymentCode;
data['bank'] = this.bank;
data['masked_card'] = this.maskedCard;
if (this.vaNumbers != null) {
data['va_numbers'] = this.vaNumbers!.map((v) => v.toJson()).toList();
}
return data;
}
}
class VaNumbersModel {
String? bank;
String? vaNumber;
VaNumbersModel({this.bank, this.vaNumber});
VaNumbersModel.fromJson(Map<String, dynamic> json) {
bank = json['bank'];
vaNumber = json['va_number'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['bank'] = this.bank;
data['va_number'] = this.vaNumber;
return data;
}
}
class StoreModel {
String? store;
StoreModel({this.store});
StoreModel.fromJson(Map<String, dynamic> json) {
store = json['store'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['store'] = this.store;
return data;
}
}

View File

@ -0,0 +1,172 @@
class DetailOrderModel {
String idOrder;
List<VirtualNumbers>? bankVa;
String? virtualNumber;
String? billerCode;
String? bankName;
String paymentType;
String? email;
String? name;
String? url;
// List<OrderModel>? orders;
String totalPayment;
DateTime transactionTime;
DateTime transactionTimeLimit;
String? qrCodeUrl;
String? urlGopay;
String? transactionStatus;
String? merchantId;
String? coupon;
DetailOrderModel({
required this.idOrder,
this.bankVa,
this.url,
this.bankName,
this.qrCodeUrl,
this.urlGopay,
this.email,
this.name,
this.virtualNumber,
this.billerCode,
this.transactionStatus,
this.merchantId,
this.coupon,
// this.orders,
required this.transactionTime,
required this.transactionTimeLimit,
required this.totalPayment,
required this.paymentType,
});
factory DetailOrderModel.fromJson(Map<String, dynamic> json) {
final pType = json['payment_type'] ?? '';
final permataCheck = json['status_message'] ?? '';
final total = json['gross_amount'] ?? '';
final statusTransaction = json['transaction_status'] ?? '';
final time = DateTime.parse(json['transaction_time'] ?? '');
if (pType == 'echannel') {
// Model for Payment Mandiri VA
return DetailOrderModel(
transactionTime: time,
idOrder: json["order_id"] ?? '',
virtualNumber: json["bill_key"] ?? '',
billerCode: json["biller_code"] ?? '',
bankName: 'mandiri',
paymentType: json['payment_type'] ?? '',
totalPayment: total,
transactionStatus: statusTransaction,
transactionTimeLimit: time.add(Duration(days: 1)));
} else if (pType == 'bank_transfer' &&
permataCheck == 'Success, PERMATA VA transaction is successful') {
// Model for Payment Permata VA
return DetailOrderModel(
transactionTime: time,
idOrder: json["order_id"] ?? '',
virtualNumber: json["permata_va_number"] ?? '',
bankName: 'permata',
paymentType: json['payment_type'] ?? '',
totalPayment: total,
transactionStatus: statusTransaction,
transactionTimeLimit: time.add(Duration(days: 1)));
} else if (pType == 'bank_transfer') {
// Model for Payment Bank Transfer (BCA & BNI)
final bankVAResponse = List<VirtualNumbers>.from(
json["va_numbers"].map((x) => VirtualNumbers.fromJson(x))).toList();
return DetailOrderModel(
transactionTime: time,
idOrder: json['order_id'] ?? '',
paymentType: pType,
bankVa: bankVAResponse,
virtualNumber: bankVAResponse[0].vaNumber,
totalPayment: total,
transactionStatus: statusTransaction,
transactionTimeLimit: time.add(Duration(days: 1)),
bankName: bankVAResponse[0].bank);
} else if (pType == 'credit_card') {
// Model for CC Payment
return DetailOrderModel(
transactionTime: time,
url: json['redirect_url'] ?? '',
idOrder: json['order_id'] ?? '',
paymentType: pType,
totalPayment: total,
transactionStatus: statusTransaction,
transactionTimeLimit: time.add(Duration(days: 1)),
bankName: json['bank'] ?? '');
} else if (pType == 'cstore') {
// Model for Store (Indomaret & Alfamart)
return DetailOrderModel(
transactionTime: time,
idOrder: json["order_id"] ?? '',
virtualNumber: json["payment_code"] ?? '',
merchantId: json["merchant_id"] ?? '',
paymentType: pType,
bankName: json['store'] ?? '',
totalPayment: total,
transactionStatus: statusTransaction,
transactionTimeLimit: time.add(Duration(days: 1)));
} else {
// Model for GoPay
final qrUrl = json['actions'][0]['url'];
final urlGop = json['actions'][1]['url'];
return DetailOrderModel(
idOrder: json['order_id'] ?? '',
transactionTime: time,
transactionTimeLimit: time.add(Duration(days: 1)),
totalPayment: total,
paymentType: pType,
transactionStatus: statusTransaction,
qrCodeUrl: qrUrl,
urlGopay: urlGop,
);
}
}
Map<String, dynamic> toJson() {
return paymentType == "echannel"
? {
"order_id": idOrder,
"payment_type": paymentType,
"bill_key": virtualNumber,
"biller_code": billerCode,
"transaction_status": transactionStatus,
}
: paymentType == 'permata'
? {
"order_id": idOrder,
"payment_type": paymentType,
"permata_va_number": bankVa,
"transaction_status": transactionStatus,
}
: {
"order_id": idOrder,
"va_numbers":
List<dynamic>.from(bankVa!.map((x) => x.toJson())).toList(),
"payment_type": paymentType,
"transaction_status": transactionStatus,
};
}
}
class VirtualNumbers {
VirtualNumbers({
this.bank,
this.vaNumber,
});
String? bank;
String? vaNumber;
factory VirtualNumbers.fromJson(Map<String, dynamic> json) => VirtualNumbers(
bank: json["bank"],
vaNumber: json["va_number"],
);
Map<String, dynamic> toJson() => {
"bank": bank,
"va_number": vaNumber,
};
}

View File

@ -0,0 +1,169 @@
class DetailOrderModelUnderscore {
String idOrder;
List<VirtualNumbers>? bankVa;
String? virtualNumber;
String? billerCode;
String? bankName;
String paymentType;
String? email;
String? name;
String? url;
// List<OrderModel>? orders;
String totalPayment;
DateTime transactionTime;
DateTime transactionTimeLimit;
String? qrCodeUrl;
String? urlGopay;
String? transactionStatus;
String? merchantId;
DetailOrderModelUnderscore({
required this.idOrder,
this.bankVa,
this.url,
this.bankName,
this.qrCodeUrl,
this.urlGopay,
this.email,
this.name,
this.virtualNumber,
this.billerCode,
this.transactionStatus,
this.merchantId,
// this.orders,
required this.transactionTime,
required this.transactionTimeLimit,
required this.totalPayment,
required this.paymentType,
});
factory DetailOrderModelUnderscore.fromJson(Map<String, dynamic> json) {
final pType = json['payment_type'] ?? '';
final permataCheck = json['status_message'] ?? '';
final total = json['gross_amount'] ?? '';
final statusTransaction = json['transaction_status'] ?? '';
final time = DateTime.parse(json['transaction_time'] ?? '');
if (pType == 'echannel') {
// Model for Payment Mandiri VA
return DetailOrderModelUnderscore(
transactionTime: time,
idOrder: json["order_id"] ?? '',
virtualNumber: json["bill_key"] ?? '',
billerCode: json["biller_code"] ?? '',
bankName: 'mandiri',
paymentType: json['payment_type'] ?? '',
totalPayment: total,
transactionStatus: statusTransaction,
transactionTimeLimit: time.add(Duration(days: 1)));
} else if (pType == 'bank_transfer' &&
permataCheck == 'Success, PERMATA VA transaction is successful') {
// Model for Payment Permata VA
return DetailOrderModelUnderscore(
transactionTime: time,
idOrder: json["order_id"] ?? '',
virtualNumber: json["permata_va_number"] ?? '',
bankName: 'permata',
paymentType: json['payment_type'] ?? '',
totalPayment: total,
transactionStatus: statusTransaction,
transactionTimeLimit: time.add(Duration(days: 1)));
} else if (pType == 'bank_transfer') {
// Model for Payment Bank Transfer (BCA & BNI)
final bankVAResponse = List<VirtualNumbers>.from(
json["va_numbers"].map((x) => VirtualNumbers.fromJson(x))).toList();
return DetailOrderModelUnderscore(
transactionTime: time,
idOrder: json['order_id'] ?? '',
paymentType: pType,
bankVa: bankVAResponse,
virtualNumber: bankVAResponse[0].vaNumber,
totalPayment: total,
transactionStatus: statusTransaction,
transactionTimeLimit: time.add(Duration(days: 1)),
bankName: bankVAResponse[0].bank);
} else if (pType == 'credit_card') {
// Model for CC Payment
return DetailOrderModelUnderscore(
transactionTime: time,
url: json['redirect_url'] ?? '',
idOrder: json['order_id'] ?? '',
paymentType: pType,
totalPayment: total,
transactionStatus: statusTransaction,
transactionTimeLimit: time.add(Duration(days: 1)),
bankName: json['bank'] ?? '');
} else if (pType == 'cstore') {
// Model for Store (Indomaret & Alfamart)
return DetailOrderModelUnderscore(
transactionTime: time,
idOrder: json["order_id"] ?? '',
virtualNumber: json["payment_code"] ?? '',
merchantId: json["merchant_id"] ?? '',
paymentType: pType,
bankName: json['store'] ?? '',
totalPayment: total,
transactionStatus: statusTransaction,
transactionTimeLimit: time.add(Duration(days: 1)));
} else {
// Model for GoPay
final qrUrl = json['actions'][0]['url'];
final urlGop = json['actions'][1]['url'];
return DetailOrderModelUnderscore(
idOrder: json['order_id'] ?? '',
transactionTime: time,
transactionTimeLimit: time.add(Duration(days: 1)),
totalPayment: total,
paymentType: pType,
transactionStatus: statusTransaction,
qrCodeUrl: qrUrl,
urlGopay: urlGop,
);
}
}
Map<String, dynamic> toJson() {
return paymentType == "echannel"
? {
"order_id": idOrder,
"payment_type": paymentType,
"bill_key": bankVa,
"transaction_status": transactionStatus,
}
: paymentType == 'permata'
? {
"order_id": idOrder,
"payment_type": paymentType,
"permata_va_number": bankVa,
"transaction_status": transactionStatus,
}
: {
"order_id": idOrder,
"va_numbers":
List<dynamic>.from(bankVa!.map((x) => x.toJson())).toList(),
"payment_type": paymentType,
"transaction_status": transactionStatus,
};
}
}
class VirtualNumbers {
VirtualNumbers({
this.bank,
this.vaNumber,
});
String? bank;
String? vaNumber;
factory VirtualNumbers.fromJson(Map<String, dynamic> json) => VirtualNumbers(
bank: json["bank"],
vaNumber: json["va_number"],
);
Map<String, dynamic> toJson() => {
"bank": bank,
"va_number": vaNumber,
};
}

View File

@ -0,0 +1,110 @@
class RatingCourseDetailModel {
RatingCourseDetailModel({
this.status,
this.error,
required this.data,
required this.dataReview,
});
final int? status;
final bool? error;
final Data data;
final List<DataReview> dataReview;
factory RatingCourseDetailModel.fromJson(Map<String, dynamic> json) =>
RatingCourseDetailModel(
status: json["status"],
error: json["error"],
data: Data.fromJson(json["data"]),
dataReview: List<DataReview>.from(
json["data_review"].map((x) => DataReview.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": data.toJson(),
"data_review": List<dynamic>.from(dataReview.map((x) => x.toJson())),
};
}
class Data {
Data({
this.avgRating,
required this.precentageRating,
});
final dynamic avgRating;
final PrecentageRating precentageRating;
factory Data.fromJson(Map<String, dynamic> json) => Data(
avgRating: json["avg_rating"],
precentageRating: PrecentageRating.fromJson(json["precentage_rating"]),
);
Map<String, dynamic> toJson() => {
"avg_rating": avgRating,
"precentage_rating": precentageRating.toJson(),
};
}
class PrecentageRating {
PrecentageRating({
this.rating1,
this.rating2,
this.rating3,
this.rating4,
this.rating5,
});
final dynamic rating1;
final dynamic rating2;
final dynamic rating3;
final dynamic rating4;
final dynamic rating5;
factory PrecentageRating.fromJson(Map<String, dynamic> json) =>
PrecentageRating(
rating1: json["rating_1"],
rating2: json["rating_2"],
rating3: json["rating_3"],
rating4: json["rating_4"],
rating5: json["rating_5"],
);
Map<String, dynamic> toJson() => {
"rating_1": rating1,
"rating_2": rating2,
"rating_3": rating3,
"rating_4": rating4,
"rating_5": rating5,
};
}
class DataReview {
DataReview({
this.name,
this.review,
this.rating,
this.date,
});
final String? name;
final String? review;
final String? rating;
final String? date;
factory DataReview.fromJson(Map<String, dynamic> json) => DataReview(
name: json["name"],
review: json["review"],
rating: json["rating"],
date: json["date"],
);
Map<String, dynamic> toJson() => {
"name": name,
"review": review,
"rating": rating,
"date": date,
};
}

View File

@ -0,0 +1,91 @@
import 'package:initial_folder/models/rating_course_model.dart';
class DiscountCourseModel {
DiscountCourseModel({
this.idCourse = '',
this.instructorId = '',
this.title = '',
this.price = '',
this.instructorName = '',
this.discountFlag,
this.discountPrice = '',
this.thumbnail,
this.students,
required this.rating,
this.finalPrice,
this.fotoProfile,
this.topCourse,
this.hargaTotalDiscount,
this.typeCoupon,
this.value,
});
String idCourse;
String instructorId;
String title;
String price;
String instructorName;
String? discountFlag;
String discountPrice;
String? thumbnail;
String? students;
List<Rating?> rating;
int? finalPrice;
int? hargaTotalDiscount;
String? fotoProfile;
String? topCourse;
String? typeCoupon;
String? value;
factory DiscountCourseModel.fromJson(Map<String, dynamic> json) {
int parseIntWithDotRemoval(dynamic value) {
if (value is int) return value;
return int.tryParse(value.toString().replaceAll('.', '')) ?? 0;
}
return DiscountCourseModel(
idCourse: json["id_course"].toString(),
instructorId: json["instructor_id"].toString(),
title: json["title"].toString(),
price: json["price"].toString(),
instructorName: json["instructor_name"].toString(),
discountFlag: json["discount_flag"]?.toString(),
discountPrice: json["discount_price"].toString(),
thumbnail: json["thumbnail"]?.toString(),
students: json["students"]?.toString(),
rating: List<Rating>.from(json["rating"].map((x) => Rating.fromJson(x)))
.toList(),
finalPrice: parseIntWithDotRemoval(json["final_price"]),
// finalPrice: json["final_price"] is int
// ? json["final_price"]
// : int.tryParse(json["final_price"].toString()),
fotoProfile: json["foto_profile"]?.toString(),
topCourse: json["top_course"]?.toString(),
typeCoupon: json["type_coupon"]?.toString(),
value: json["value"]?.toString(),
hargaTotalDiscount: parseIntWithDotRemoval(json["harga_total_discount"]),
// hargaTotalDiscount: json["harga_total_discount"] is int
// ? json["harga_total_discount"]
// : int.tryParse(json["harga_total_discount"].toString()),
);
}
Map<String, dynamic> toJson() => {
"id_course": idCourse,
"instructor_id": instructorId,
"title": title,
"price": price,
"instructor_name": instructorName,
"discount_flag": discountFlag,
"discount_price": discountPrice,
"thumbnail": thumbnail,
"students": students,
"rating": List<dynamic>.from(rating.map((x) => x!.toJson())).toList(),
"final_price": finalPrice,
"foto_profile": fotoProfile,
"top_course": topCourse,
"harga_total_discount": hargaTotalDiscount,
"type_coupon": typeCoupon,
"value": value,
};
}

View File

@ -0,0 +1,15 @@
class ForgotPasswordModel {
String? email;
ForgotPasswordModel({this.email});
ForgotPasswordModel.fromJson(Map<String, dynamic> json) {
email = json['email'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['email'] = this.email;
return data;
}
}

View File

@ -0,0 +1,100 @@
class HistoryTransactionModel {
HistoryTransactionModel({
this.orderId,
this.totalPrice,
this.date,
this.dateExpired,
this.paymentDetail,
this.statusPayment,
this.courses,
this.discountPrice,
this.token,
});
final String? orderId;
final DateTime? date;
final DateTime? dateExpired;
final List<DataCourses>? courses;
final int? totalPrice;
final int? discountPrice;
final PaymentDetail? paymentDetail;
final String? statusPayment;
final String? token;
factory HistoryTransactionModel.fromJson(Map<String, dynamic> json) {
int timestamp = int.parse(json["date"]);
int timestampExpired = int.parse(json["date_expired"]);
return HistoryTransactionModel(
orderId: json['order_id'] ?? '',
totalPrice: json["sub_total"] ?? 0,
discountPrice: json["discount_price"] ?? 0,
date: DateTime.fromMillisecondsSinceEpoch(timestamp * 1000),
dateExpired: DateTime.fromMillisecondsSinceEpoch(timestamp * 1000),
paymentDetail: PaymentDetail.fromJson(json["payment_detail"] ?? {}),
statusPayment: json["status"] ?? '',
token: json['token'] ?? '',
courses: json["course"] != null
? List<DataCourses>.from(
json["course"].map((x) => DataCourses.fromJson(x))).toList()
: []);
}
Map<dynamic, dynamic> toJson() => {
'order_id': orderId,
"sub_total": totalPrice,
"discountPrice": discountPrice,
"payment_type": paymentDetail,
"status": statusPayment,
"token": token,
'course': courses != null
? List<dynamic>.from(courses!.map((x) => x.toJson())).toList()
: []
};
}
class DataCourses {
final String? courseId, thumbnail, title, instructor, price;
DataCourses(
{this.courseId, this.title, this.price, this.instructor, this.thumbnail});
factory DataCourses.fromJson(Map<String, dynamic> json) => DataCourses(
courseId: json['id'] ?? '',
title: json['title'] ?? '',
price: json['price'] ?? '',
thumbnail: json['thumbnail'] ?? '',
instructor: json['instructor'] ?? '',
);
Map<String, dynamic> toJson() => {
'id': courseId,
'title': title,
'price': price,
'thumbnail': thumbnail,
'instructor': instructor
};
}
class PaymentDetail {
String? paymentType;
String? bank;
String? vaNumber;
String? store;
PaymentDetail({this.paymentType, this.bank, this.vaNumber, this.store});
PaymentDetail.fromJson(Map<String, dynamic> json) {
paymentType = json['payment_type'] ?? '';
bank = json['bank'] ?? '';
vaNumber = json['va_number'] ?? '';
store = json['store'] ?? '';
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['payment_type'] = this.paymentType;
data['bank'] = this.bank;
data['va_number'] = this.vaNumber;
return data;
}
}

View File

@ -0,0 +1,53 @@
class InstructorModel {
InstructorModel({
this.status,
this.error,
required this.data,
});
final int? status;
final bool? error;
final List<DataInstructor> data;
factory InstructorModel.fromJson(Map<String, dynamic> json) =>
InstructorModel(
status: json["status"],
error: json["error"],
data: List<DataInstructor>.from(
json["data"].map((x) => DataInstructor.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class DataInstructor {
DataInstructor({
this.instructorName,
this.totalReview,
this.totalCourse,
this.totalStudents,
});
final String? instructorName;
final String? totalReview;
final String? totalCourse;
final String? totalStudents;
factory DataInstructor.fromJson(Map<String, dynamic> json) => DataInstructor(
instructorName: json["instructor_name"],
totalReview: json["total_review"],
totalCourse: json["total_course"],
totalStudents: json["total_students"],
);
Map<String, dynamic> toJson() => {
"instructor_name": instructorName,
"total_review": totalReview,
"total_course": totalCourse,
"total_students": totalStudents,
};
}

View File

@ -0,0 +1,164 @@
class LessonCourseModel {
LessonCourseModel({
this.status,
this.error,
required this.data,
});
final int? status;
final bool? error;
final List<List<DataLessonCourseModel>> data;
factory LessonCourseModel.fromJson(Map<String, dynamic> json) =>
LessonCourseModel(
status: json["status"],
error: json["error"],
data: List<List<DataLessonCourseModel>>.from(json["data"].map((x) =>
List<DataLessonCourseModel>.from(
x.map((x) => DataLessonCourseModel.fromJson(x))))),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": List<dynamic>.from(
data.map((x) => List<dynamic>.from(x.map((x) => x.toJson())))),
};
}
class DataLessonCourseModel {
DataLessonCourseModel({
this.courseId,
this.lessonId,
this.sectionTitle,
this.lessonTitle,
this.duration,
this.attachmentType,
this.videoType,
this.videoUrl,
this.lessonType,
this.attachment,
this.isSkip,
this.isFinished,
});
final String? courseId;
final String? lessonId;
final String? sectionTitle;
final String? lessonTitle;
final String? duration;
final String? attachmentType;
final String? videoType;
final String? videoUrl;
final String? lessonType;
final dynamic attachment;
final String? isSkip;
late int? isFinished;
factory DataLessonCourseModel.fromJson(Map<String, dynamic> json) =>
DataLessonCourseModel(
courseId: json["course_id"],
lessonId: json["lesson_id"],
sectionTitle: json["section_title"],
lessonTitle: json["lesson_title"],
duration: json["duration"],
attachmentType: json["attachment_type"],
videoType: json["video_type"] == null ? null : json["video_type"],
videoUrl: json["video_url"] == null ? null : json["video_url"],
lessonType: json["lesson_type"],
attachment: json["attachment"],
isSkip: json["is_skip"],
isFinished: json["is_finished"],
);
Map<String, dynamic> toJson() => {
"course_id": courseId,
"lesson_id": lessonId,
"section_title": sectionTitle,
"lesson_title": lessonTitle,
"duration": duration,
"attachment_type": attachmentType,
"video_type": videoType == null ? null : videoType,
"video_url": videoUrl == null ? null : videoUrl,
"lesson_type": lessonType,
"attachment": attachment,
"is_skip": isSkip,
"is_finished": isFinished,
};
}
class NewMap {
NewMap({
required this.title,
});
final List<Title> title;
factory NewMap.fromMap(Map<String, dynamic> json) => NewMap(
title: List<Title>.from(json["Title"].map((x) => Title.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"Title": List<dynamic>.from(title.map((x) => x.toMap())),
};
}
class Title {
Title({
this.courseId,
this.lessonId,
this.sectionTitle,
this.lessonTitle,
this.duration,
this.attachmentType,
this.videoType,
this.videoUrl,
this.lessonType,
this.attachment,
this.isSkip,
this.isFinished,
});
final String? courseId;
final String? lessonId;
final String? sectionTitle;
final String? lessonTitle;
final String? duration;
final String? attachmentType;
final String? videoType;
final String? videoUrl;
final String? lessonType;
final dynamic attachment;
final String? isSkip;
final int? isFinished;
factory Title.fromMap(Map<String, dynamic> json) => Title(
courseId: json["course_id"],
lessonId: json["lesson_id"],
sectionTitle: json["section_title"],
lessonTitle: json["lesson_title"],
duration: json["duration"],
attachmentType: json["attachment_type"],
videoType: json["video_type"],
videoUrl: json["video_url"] == '' ? 'a' : json["video_url"],
lessonType: json["lesson_type"],
attachment: json["attachment"],
isSkip: json["is_skip"],
isFinished: json["is_finished"],
);
Map<String, dynamic> toMap() => {
"course_id": courseId,
"lesson_id": lessonId,
"section_title": sectionTitle,
"lesson_title": lessonTitle,
"duration": duration,
"attachment_type": attachmentType,
"video_type": videoType,
"video_url": videoUrl,
"lesson_type": lessonType,
"attachment": attachment,
"is_skip": isSkip,
"is_finished": isFinished,
};
}

View File

@ -0,0 +1,59 @@
class LessonModel {
LessonModel({
required this.lesssonId,
required this.title,
required this.duration,
this.videoType,
this.videoUrl,
this.attachmentType,
this.attachment,
required this.attachmentDownload,
required this.isSkip,
required this.progressVideo,
required this.isFinished,
required this.summary,
});
final String lesssonId;
final String title;
final String duration;
String? videoType;
String? videoUrl;
String? attachmentType;
String? attachment;
final bool attachmentDownload;
final String isSkip;
final String progressVideo;
final int isFinished;
final String summary;
factory LessonModel.fromJson(Map<String, dynamic> json) => LessonModel(
lesssonId: json["lesson_id"],
title: json["title"],
duration: json["duration"],
videoType: json["video_type"],
videoUrl: json["video_url"],
attachmentType: json["attachment_type"],
attachment: json["attachment"],
attachmentDownload: json["attachment_download"],
isSkip: json["is_skip"],
progressVideo: json["progress_video"],
isFinished: json["is_finished"],
summary: json["summary"],
);
Map<String, dynamic> toJson() => {
"lesson_id": lesssonId,
"title": title,
"duration": duration,
"video_type": videoType,
"video_url": videoUrl,
"attachment_type": attachmentType,
"attachment": attachment,
"attachment_download": attachmentDownload,
"is_skip": isSkip,
"progress_video": progressVideo,
"is_finished": isFinished,
"summary": summary,
};
}

1
lib/models/models.dart Normal file
View File

@ -0,0 +1 @@

View File

@ -0,0 +1,77 @@
class MyCertificateModel {
MyCertificateModel({
this.status,
this.error,
required this.data,
});
final int? status;
final bool? error;
final List<List<DataMyCertificateModel>> data;
factory MyCertificateModel.fromJson(Map<String, dynamic> json) =>
MyCertificateModel(
status: json["status"],
error: json["error"],
data: List<List<DataMyCertificateModel>>.from(json["data"].map((x) =>
List<DataMyCertificateModel>.from(
x.map((x) => DataMyCertificateModel.fromJson(x))))),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": List<dynamic>.from(
data.map((x) => List<dynamic>.from(x.map((x) => x.toJson())))),
};
}
class DataMyCertificateModel {
String? courseId;
String? instructorId;
String? name;
String? title;
String? instructor;
String? certificateNo;
int? progress;
String? fotoProfile;
String? idPayment;
DataMyCertificateModel({
this.courseId,
this.instructorId,
this.name,
this.title,
this.instructor,
this.certificateNo,
this.progress,
this.fotoProfile,
this.idPayment,
});
DataMyCertificateModel.fromJson(Map<String, dynamic> json) {
courseId = json['course_id'];
instructorId = json['instructor_id'];
name = json['name'];
title = json['title'];
instructor = json['instructor'];
certificateNo = json['certificate_no'];
progress = json['progress'];
fotoProfile = json['foto_profile'];
idPayment = json['id_payment'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['course_id'] = this.courseId;
data['instructor_id'] = this.instructorId;
data['name'] = this.name;
data['title'] = this.title;
data['instructor'] = this.instructor;
data['certificate_no'] = this.certificateNo;
data['progress'] = this.progress;
data['foto_profile'] = this.fotoProfile;
data['id_payment'] = this.idPayment;
return data;
}
}

View File

@ -0,0 +1,97 @@
class MyCourseModel {
MyCourseModel({
this.status,
this.error,
required this.data,
});
final int? status;
final bool? error;
final List<List<DataMyCourseModel>> data;
factory MyCourseModel.fromJson(Map<String, dynamic> json) => MyCourseModel(
status: json["status"],
error: json["error"],
data: List<List<DataMyCourseModel>>.from(json["data"].map((x) =>
List<DataMyCourseModel>.from(
x.map((x) => DataMyCourseModel.fromJson(x))))),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": List<dynamic>.from(
data.map((x) => List<dynamic>.from(x.map((x) => x.toJson())))),
};
}
class DataMyCourseModel {
DataMyCourseModel({
this.courseId,
this.instructorId,
this.instructor,
this.title,
this.thumbnail,
required this.rating,
this.fotoProfile,
this.totalProgress,
});
final String? courseId;
final String? instructorId;
final String? instructor;
final String? title;
final String? thumbnail;
final List<Rating> rating;
final dynamic fotoProfile;
final int? totalProgress;
factory DataMyCourseModel.fromJson(Map<String, dynamic> json) =>
DataMyCourseModel(
courseId: json["course_id"],
instructorId: json["instructor_id"],
instructor: json["instructor"],
title: json["title"],
thumbnail: json["thumbnail"],
rating: json['rating'] == []
? []
: List<Rating>.from(json["rating"].map((x) => Rating.fromJson(x))),
fotoProfile: json["foto_profile"],
totalProgress: json["total_progress"],
);
Map<String, dynamic> toJson() => {
"course_id": courseId,
"instructor_id": instructorId,
"instructor": instructor,
"title": title,
"thumbnail": thumbnail,
"rating": List<dynamic>.from(rating.map((x) => x.toJson())),
"foto_profile": fotoProfile,
"total_progress": totalProgress,
};
}
class Rating {
Rating({
this.ratableId,
this.rating,
this.review,
});
final String? ratableId;
final String? rating;
final String? review;
factory Rating.fromJson(Map<String, dynamic> json) => Rating(
ratableId: json["ratable_id"],
rating: json["rating"],
review: json["review"],
);
Map<String, dynamic> toJson() => {
"ratable_id": ratableId,
"rating": rating,
"review": review,
};
}

View File

@ -0,0 +1,385 @@
// Ini model buat notifikasi
class Notification {
int? status;
bool? error;
Data? data;
Notification({this.status, this.error, this.data});
Notification.fromJson(Map<String, dynamic> json) {
status = json['status'];
error = json['error'];
data = json['data'] != null ? new Data.fromJson(json['data']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
data['error'] = this.error;
if (this.data != null) {
data['data'] = this.data!.toJson();
}
return data;
}
}
class Data {
Users? users;
Instructur? instructur;
Data({this.users, this.instructur});
Data.fromJson(Map<String, dynamic> json) {
users = json['users'] != null ? new Users.fromJson(json['users']) : null;
instructur = json['instructur'] != null
? new Instructur.fromJson(json['instructur'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.users != null) {
data['users'] = this.users!.toJson();
}
if (this.instructur != null) {
data['instructur'] = this.instructur!.toJson();
}
return data;
}
}
class Users {
List<Qna>? qna;
List<Courses>? courses;
List<Announcement>? announcement;
Users({this.qna, this.courses, this.announcement});
Users.fromJson(Map<String, dynamic> json) {
if (json['qna'] != null) {
qna = <Qna>[];
json['qna'].forEach((v) {
qna!.add(new Qna.fromJson(v));
});
}
if (json['announcement'] != null) {
announcement = <Announcement>[];
json['announcement'].forEach((v) {
announcement!.add(new Announcement.fromJson(v));
});
}
if (json['courses'] != null) {
courses = <Courses>[];
json['courses'].forEach((v) {
courses!.add(new Courses.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.qna != null) {
data['qna'] = this.qna!.map((v) => v.toJson()).toList();
}
if (this.announcement != null) {
data['announcement'] = this.announcement!.map((v) => v.toJson()).toList();
}
if (this.courses != null) {
data['courses'] = this.courses!.map((v) => v.toJson()).toList();
}
return data;
}
}
class NotificationDataAnnouncementUser {
String? idCourse;
String? subject;
String? titleCourse;
String? messages;
String? date;
String? thumbnail;
String? timestamps;
String? instructor;
int? isRead;
String? idRead;
String? ket;
NotificationDataAnnouncementUser(
{this.idCourse,
this.subject,
this.titleCourse,
this.messages,
this.date,
this.thumbnail,
this.timestamps,
this.instructor,
this.isRead,
this.idRead,
this.ket});
NotificationDataAnnouncementUser.announcementFromJson(
Map<String, dynamic> json) {
idCourse = json['id_course'];
subject = json['subject'];
titleCourse = json['title_course'];
thumbnail = json['thumbnail'];
messages = json['messages'];
date = json['date'];
timestamps = json['timestamps'];
instructor = json['name_instructure'];
isRead = json['is_read'];
idRead = json['id_read'];
ket = json['ket'];
}
}
class NotificationData {
String? idCourse;
String? subject;
String? titleCourse;
String? messages;
String? date;
String? thumbnail;
String? timestamps;
String? instructor;
String? isRead;
String? idRead;
String? ket;
NotificationData(
{this.idCourse,
this.subject,
this.titleCourse,
this.messages,
this.date,
this.thumbnail,
this.timestamps,
this.instructor,
this.isRead,
this.idRead,
this.ket});
NotificationData.qnaFromJson(Map<String, dynamic> json) {
idCourse = json['id_course'];
subject = json['subject'];
titleCourse = json['title_course'];
thumbnail = json['thumbnail'];
messages = json['messages'];
date = json['date'];
timestamps = json['timestamps'].toString();
instructor = json['name_instructure'];
isRead = json['is_read'];
idRead = json['id_read'];
ket = json['ket'];
}
NotificationData.announcementFromJson(Map<String, dynamic> json) {
subject = json['subject'];
titleCourse = json['title_course'];
messages = json['messages'];
date = json['date'];
idCourse = json['id_course'];
timestamps = json['timestamps'];
isRead = json['is_read'].toString();
idRead = json['id_read'];
ket = json['ket'];
instructor = json['name_instructure'];
thumbnail = json['thumbnail'];
}
NotificationData.coursesFromJson(Map<String, dynamic> json) {
idCourse = json['id_course'];
subject = json['subject'];
titleCourse = json['title_course'];
thumbnail = json['thumbnail'];
messages = json['messages'];
date = json['date'];
timestamps = json['timestamps'];
instructor = json['instructur_name'];
isRead = json['is_read'];
idRead = json['id_read'];
ket = json['ket'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['subject'] = this.subject;
data['title_course'] = this.titleCourse;
data['messages'] = this.messages;
data['date'] = this.date;
return data;
}
}
class Qna {
String? subject;
String? titleCourse;
String? messages;
String? date;
Qna({this.subject, this.titleCourse, this.messages, this.date});
Qna.fromJson(Map<String, dynamic> json) {
subject = json['subject'];
titleCourse = json['title_course'];
messages = json['messages'];
date = json['date'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['subject'] = this.subject;
data['title_course'] = this.titleCourse;
data['messages'] = this.messages;
data['date'] = this.date;
return data;
}
}
class Announcement {
String? subject;
String? titleCourse;
String? messages;
String? date;
Announcement({this.subject, this.titleCourse, this.messages, this.date});
Announcement.fromJson(Map<String, dynamic> json) {
subject = json['subject'];
titleCourse = json['title_course'];
messages = json['messages'];
date = json['date'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['subject'] = this.subject;
data['title_course'] = this.titleCourse;
data['messages'] = this.messages;
data['date'] = this.date;
return data;
}
}
class Courses {
String? subject;
String? title;
String? thumbnail;
String? date;
Courses({this.subject, this.title, this.thumbnail, this.date});
Courses.fromJson(Map<String, dynamic> json) {
subject = json['subject'];
title = json['title'];
thumbnail = json['thumbnail'];
date = json['date'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['subject'] = this.subject;
data['title'] = this.title;
data['thumbnail'] = this.thumbnail;
data['date'] = this.date;
return data;
}
}
class Instructur {
List<Qna>? qna;
List<Announcement>? announcement;
List<CoursesAdded>? coursesAdded;
List<Payout>? payout;
Instructur({this.qna, this.coursesAdded, this.payout, this.announcement});
Instructur.fromJson(Map<String, dynamic> json) {
if (json['qna'] != null) {
qna = <Qna>[];
json['qna'].forEach((v) {
qna!.add(new Qna.fromJson(v));
});
}
if (json['announcement'] != null) {
announcement = <Announcement>[];
json['announcement'].forEach((v) {
announcement!.add(new Announcement.fromJson(v));
});
}
if (json['courses_added'] != null) {
coursesAdded = <CoursesAdded>[];
json['courses_added'].forEach((v) {
coursesAdded!.add(new CoursesAdded.fromJson(v));
});
}
if (json['payout'] != null) {
payout = <Payout>[];
json['payout'].forEach((v) {
payout!.add(new Payout.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.qna != null) {
data['qna'] = this.qna!.map((v) => v.toJson()).toList();
}
if (this.announcement != null) {
data['announcement'] = this.announcement!.map((v) => v.toJson()).toList();
}
if (this.coursesAdded != null) {
data['courses_added'] =
this.coursesAdded!.map((v) => v.toJson()).toList();
}
if (this.payout != null) {
data['payout'] = this.payout!.map((v) => v.toJson()).toList();
}
return data;
}
}
class CoursesAdded {
String? subject;
String? title;
String? time;
CoursesAdded({this.subject, this.title, this.time});
CoursesAdded.fromJson(Map<String, dynamic> json) {
subject = json['subject'];
title = json['title'];
time = json['time'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['subject'] = this.subject;
data['title'] = this.title;
data['time'] = this.time;
return data;
}
}
class Payout {
String? subject;
String? message;
String? date;
Payout({this.subject, this.message, this.date});
Payout.fromJson(Map<String, dynamic> json) {
subject = json['subject'];
message = json['message'];
date = json['date'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['subject'] = this.subject;
data['message'] = this.message;
data['date'] = this.date;
return data;
}
}

View File

@ -0,0 +1,16 @@
class OrderModel {
String idCourse;
String title;
String price;
String discountPrice;
String imageUrl;
String instructor;
OrderModel(
{required this.idCourse,
required this.title,
required this.price,
required this.imageUrl,
required this.discountPrice,
required this.instructor});
}

View File

@ -0,0 +1,50 @@
class PaymentHistoryModel {
PaymentHistoryModel({this.status, this.error, required this.data});
final int? status;
final bool? error;
final List<List<DataPaymentHistoryModel>> data;
}
class DataPaymentHistoryModel {
DataPaymentHistoryModel({
this.orderId,
this.title,
this.thumbnail,
this.instructor,
this.totalPrice,
this.date,
this.paymentType,
this.statusPayment,
});
final String? orderId;
final String? title;
final String? thumbnail;
final String? instructor;
final String? totalPrice;
final String? date;
final String? paymentType;
final String? statusPayment;
factory DataPaymentHistoryModel.fromJson(Map<String, dynamic> json) =>
DataPaymentHistoryModel(
orderId: json['order_id'],
title: json["title"],
thumbnail: json["thumbnail"] == null ? null : json["thumbnail"],
instructor: json["instructor"],
totalPrice: json["total"],
date: json["date"],
paymentType: json["payment_type"],
statusPayment: json["status"],
);
Map<String, dynamic> toJson() => {
"order_id": orderId,
"title": title,
"thumbnail": thumbnail == null ? null : thumbnail,
"instructor": instructor,
"total_price": totalPrice,
"date": date,
"payment_type": paymentType,
"status_payment": statusPayment,
};
}

View File

@ -0,0 +1,23 @@
class PaymentModel {
PaymentModel({
this.status,
this.error,
this.messages,
});
final int? status;
final bool? error;
final String? messages;
factory PaymentModel.fromJson(Map<String, dynamic> json) => PaymentModel(
status: json["status"],
error: json["error"],
messages: json["messages"],
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"messages": messages,
};
}

View File

@ -0,0 +1,40 @@
class ProfileImagePostModel {
ProfileImagePostModel({
this.status,
this.error,
required this.data,
});
final int? status;
final bool? error;
final DataPostImage data;
factory ProfileImagePostModel.fromJson(Map<String, dynamic> json) =>
ProfileImagePostModel(
status: json["status"],
error: json["error"],
data: DataPostImage.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": data.toJson(),
};
}
class DataPostImage {
DataPostImage({
this.messages,
});
final String? messages;
factory DataPostImage.fromJson(Map<String, dynamic> json) => DataPostImage(
messages: json["messages"],
);
Map<String, dynamic> toJson() => {
"messages": messages,
};
}

130
lib/models/qna_model.dart Normal file
View File

@ -0,0 +1,130 @@
import 'package:initial_folder/models/comment_qna_model.dart';
class QnaModel {
QnaModel({
this.status,
this.error,
required this.data,
});
final int? status;
final bool? error;
final List<List<QnaDataModel>> data;
factory QnaModel.fromJson(Map<String, dynamic> json) => QnaModel(
status: json["status"],
error: json["error"],
data: List<List<QnaDataModel>>.from(json["data"].map((x) =>
List<QnaDataModel>.from(x.map((x) => QnaDataModel.fromJson(x))))),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": List<dynamic>.from(
data.map((x) => List<dynamic>.from(x.map((x) => x.toJson())))),
};
}
class QnaDataModel {
QnaDataModel({
this.idQna,
this.idLesson,
this.sender,
this.username,
this.title,
this.quest,
this.fotoProfile,
this.countComment,
this.countLike,
this.selfLiked,
this.date,
required this.comment,
});
final String? idQna;
final String? idLesson;
final String? sender;
final String? username;
final String? title;
final String? quest;
final String? fotoProfile;
int? countComment;
String? countLike;
bool? selfLiked;
final String? date;
List<Comment> comment;
factory QnaDataModel.fromJson(Map<String, dynamic> json) => QnaDataModel(
idQna: json["id_qna"],
idLesson: json["id_lesson"],
sender: json["sender"],
username: json["username"],
title: json["title"],
quest: json["quest"],
fotoProfile: json["foto_profile"],
countComment: json["count_comment"],
countLike: json["count_up"],
selfLiked: json['status_up'],
date: json["date"],
comment:
List<Comment>.from(json["comment"].map((x) => Comment.fromJson(x)))
.toList(),
);
Map<String, dynamic> toJson() => {
"id_qna": idQna,
"id_lesson": idLesson,
"sender": sender,
"username": username,
"quest": quest,
"foto_profile": fotoProfile,
"date": date,
"comment": List<dynamic>.from(comment.map((x) => x)),
};
}
/// Class untuk response tambah
class QnaPostModel {
QnaPostModel({
this.status,
this.error,
required this.data,
});
final int? status;
final bool? error;
final DataPostQna data;
factory QnaPostModel.fromJson(Map<String, dynamic> json) => QnaPostModel(
status: json["status"],
error: json["error"],
data: DataPostQna.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": data.toJson(),
};
}
class DataPostQna {
DataPostQna({this.sender, this.quest, this.idCourse});
final String? sender;
final String? quest;
final String? idCourse;
factory DataPostQna.fromJson(Map<String, dynamic> json) => DataPostQna(
sender: json["sender"],
quest: json["quest"],
idCourse: json["id_course"],
);
Map<String, dynamic> toJson() => {
"messages": sender,
"quest": quest,
"id_course": idCourse,
};
}

View File

@ -0,0 +1,82 @@
// To parse this JSON data, do
//
// final quizModel = quizModelFromJson(jsonString);
import 'dart:convert';
QuizModel quizModelFromJson(String str) => QuizModel.fromJson(json.decode(str));
String quizModelToJson(QuizModel data) => json.encode(data.toJson());
class QuizModel {
int status;
bool error;
int total;
List<Datum> data;
QuizModel({
required this.status,
required this.error,
required this.total,
required this.data,
});
factory QuizModel.fromJson(Map<String, dynamic> json) => QuizModel(
status: json["status"],
error: json["error"],
total: json["total"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"total": total,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
String id;
String quizId;
String title;
String type;
String numberOption;
List<String> options;
List<String> correctAnswers;
String order;
Datum({
required this.id,
required this.quizId,
required this.title,
required this.type,
required this.numberOption,
required this.options,
required this.correctAnswers,
required this.order,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
quizId: json["quiz_id"],
title: json["title"],
type: json["type"],
numberOption: json["number_option"],
options: List<String>.from(json["options"].map((x) => x)),
correctAnswers:
List<String>.from(json["correct_answers"].map((x) => x)),
order: json["order"],
);
Map<String, dynamic> toJson() => {
"id": id,
"quiz_id": quizId,
"title": title,
"type": type,
"number_option": numberOption,
"options": List<dynamic>.from(options.map((x) => x)),
"correct_answers": List<dynamic>.from(correctAnswers.map((x) => x)),
"order": order,
};
}

View File

@ -0,0 +1,81 @@
// To parse this JSON data, do
//
// final quizPerQuestionResult = quizPerQuestionResultFromJson(jsonString);
import 'dart:convert';
QuizPerQuestionResult quizPerQuestionResultFromJson(String str) => QuizPerQuestionResult.fromJson(json.decode(str));
String quizPerQuestionResultToJson(QuizPerQuestionResult data) => json.encode(data.toJson());
class QuizPerQuestionResult {
int status;
bool error;
int total;
List<Datum> data;
QuizPerQuestionResult({
required this.status,
required this.error,
required this.total,
required this.data,
});
factory QuizPerQuestionResult.fromJson(Map<String, dynamic> json) => QuizPerQuestionResult(
status: json["status"],
error: json["error"],
total: json["total"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"total": total,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
String id;
String quizId;
String title;
String type;
String numberOption;
List<String> options;
List<String> correctAnswers;
String order;
Datum({
required this.id,
required this.quizId,
required this.title,
required this.type,
required this.numberOption,
required this.options,
required this.correctAnswers,
required this.order,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
quizId: json["quiz_id"],
title: json["title"],
type: json["type"],
numberOption: json["number_option"],
options: List<String>.from(json["options"].map((x) => x)),
correctAnswers: List<String>.from(json["correct_answers"].map((x) => x)),
order: json["order"],
);
Map<String, dynamic> toJson() => {
"id": id,
"quiz_id": quizId,
"title": title,
"type": type,
"number_option": numberOption,
"options": List<dynamic>.from(options.map((x) => x)),
"correct_answers": List<dynamic>.from(correctAnswers.map((x) => x)),
"order": order,
};
}

View File

@ -0,0 +1,71 @@
// To parse this JSON data, do
//
// final quizQuestion = quizQuestionFromJson(jsonString);
import 'dart:convert';
QuizQuestion quizQuestionFromJson(String str) =>
QuizQuestion.fromJson(json.decode(str));
String quizQuestionToJson(QuizQuestion data) => json.encode(data.toJson());
class QuizQuestion {
final List<Datum> data;
QuizQuestion({
required this.data,
});
factory QuizQuestion.fromJson(Map<String, dynamic> json) => QuizQuestion(
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
final String id;
final String quizId;
final String title;
final String type;
final String numberOption;
final List<String> options;
final List<String> correctAnswers;
final String order;
Datum({
required this.id,
required this.quizId,
required this.title,
required this.type,
required this.numberOption,
required this.options,
required this.correctAnswers,
required this.order,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
quizId: json["quiz_id"],
title: json["title"],
type: json["type"],
numberOption: json["number_option"],
options: List<String>.from(json["options"].map((x) => x)),
correctAnswers:
List<String>.from(json["correct_answers"].map((x) => x)),
order: json["order"],
);
Map<String, dynamic> toJson() => {
"id": id,
"quiz_id": quizId,
"title": title,
"type": type,
"number_option": numberOption,
"options": List<dynamic>.from(options.map((x) => x)),
"correct_answers": List<dynamic>.from(correctAnswers.map((x) => x)),
"order": order,
};
}

View File

@ -0,0 +1,69 @@
// To parse this JSON data, do
//
// final quizQuestionResult = quizQuestionResultFromJson(jsonString);
import 'dart:convert';
QuizQuestionResult quizQuestionResultFromJson(String str) =>
QuizQuestionResult.fromJson(json.decode(str));
String quizQuestionResultToJson(QuizQuestionResult data) =>
json.encode(data.toJson());
class QuizQuestionResult {
final int status;
final bool error;
final List<Datum> data;
QuizQuestionResult({
required this.status,
required this.error,
required this.data,
});
factory QuizQuestionResult.fromJson(Map<String, dynamic> json) =>
QuizQuestionResult(
status: json["status"],
error: json["error"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
final int questionId;
final List<String> answers;
final String question;
final bool isCorrect;
final List<String> correctAnswers;
Datum({
required this.questionId,
required this.answers,
required this.question,
required this.isCorrect,
required this.correctAnswers,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
questionId: json["question_id"],
answers: List<String>.from(json["answers"].map((x) => x)),
question: json["question"],
isCorrect: json["is_correct"],
correctAnswers:
List<String>.from(json["correct_answers"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"question_id": questionId,
"answers": List<dynamic>.from(answers.map((x) => x)),
"question": question,
"is_correct": isCorrect,
"correct_answers": List<dynamic>.from(correctAnswers.map((x) => x)),
};
}

View File

@ -0,0 +1,19 @@
class Rating {
Rating({
this.totalReview,
this.avgRating,
});
String? totalReview;
int? avgRating;
factory Rating.fromJson(Map<String, dynamic> json) => Rating(
totalReview: json["total_review"],
avgRating: json["avg_rating"],
);
Map<String, dynamic> toJson() => {
"total_review": totalReview,
"avg_rating": avgRating,
};
}

View File

@ -0,0 +1,55 @@
class ReplyModel {
ReplyModel({
this.idRep,
this.sender,
this.name,
this.body,
this.fotoProfile,
this.updateAt,
this.createAt,
});
String? idRep;
String? sender;
String? name;
String? body;
String? fotoProfile;
String? updateAt;
String? createAt;
factory ReplyModel.fromJson(Map<String, dynamic> json) => ReplyModel(
idRep: json["id_replies"],
sender: json["sender"],
name: json["name"],
body: json["body"],
fotoProfile: json["foto_profile"],
createAt: json["created_at"],
updateAt: json["update_at"],
);
Map<String, dynamic> toJson() => {
"id_replies": idRep,
"sender": sender,
"name": name,
"body": body,
"foto_profile": fotoProfile,
"update_at": updateAt,
"created_at": createAt,
};
}
class LikeModels {
LikeModels({
this.userId,
});
bool? userId;
factory LikeModels.fromJson(Map<String, dynamic> json) => LikeModels(
userId: json["user_id"].length > 0,
);
Map<String, dynamic> toJson() => {
"id_replies": userId,
};
}

View File

@ -0,0 +1,15 @@
class ResetModel{
String? token;
String? email;
ResetModel({this.email, this.token});
factory ResetModel.fromJson(Map<String, dynamic> json) => ResetModel(
token: json["token"],
email: json["email"],
);
Map<String, dynamic> toJson() => {
"token": token,
"email": email,
};
}

View File

@ -0,0 +1,78 @@
class SectionLessonModel {
SectionLessonModel({
this.status,
this.error,
this.data,
});
final int? status;
final bool? error;
final List<List<SectionLessonList>>? data;
factory SectionLessonModel.fromJson(Map<String, dynamic> json) =>
SectionLessonModel(
status: json["status"],
error: json["error"],
data: List<List<SectionLessonList>>.from(json["data"].map((x) =>
List<SectionLessonList>.from(
x.map((x) => SectionLessonList.fromJson(x))))),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": List<dynamic>.from(
data!.map((x) => List<dynamic>.from(x.map((x) => x.toJson())))),
};
}
class SectionLessonList {
SectionLessonList({
this.title,
this.duration,
this.dataLesson,
});
final String? title;
final String? duration;
final List<List<DataLesson>>? dataLesson;
factory SectionLessonList.fromJson(Map<String, dynamic> json) =>
SectionLessonList(
title: json["title"],
duration: json["duration"] == null ? null : json["duration"],
dataLesson: List<List<DataLesson>>.from(json["data_lesson"].map((x) =>
List<DataLesson>.from(x.map((x) => DataLesson.fromJson(x))))),
);
Map<String, dynamic> toJson() => {
"title": title,
"duration": duration == null ? null : duration,
"data_lesson": List<dynamic>.from(dataLesson!
.map((x) => List<dynamic>.from(x.map((x) => x.toJson())))),
};
}
class DataLesson {
DataLesson(
{this.titleLesson, this.duration, this.lessonType, this.attachment});
final String? titleLesson;
final String? duration;
final String? lessonType;
final String? attachment;
factory DataLesson.fromJson(Map<String, dynamic> json) => DataLesson(
titleLesson: json["title_lesson"],
duration: json["duration"],
lessonType: json["lesson_type"],
attachment: json["attachment"],
);
Map<String, dynamic> toJson() => {
"title_lesson": titleLesson,
"duration": duration,
"lesson_type": lessonType,
"attachment": attachment,
};
}

View File

@ -0,0 +1,187 @@
class SectionModel {
SectionModel({
this.status,
this.error,
this.progress,
required this.data,
});
int? status;
bool? error;
int? progress;
List<Map<String, Datum>> data;
factory SectionModel.fromJson(Map<String, dynamic> json) => SectionModel(
status: json["status"],
error: json["error"],
progress: json["progress"],
data: List<Map<String, Datum>>.from(json["data"].map((x) => Map.from(x)
.map((k, v) => MapEntry<String, Datum>(k, Datum.fromJson(v))))),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"progress": progress,
"data": List<dynamic>.from(data.map((x) => Map.from(x)
.map((k, v) => MapEntry<String, dynamic>(k, v.toJson())))),
};
}
class Datum {
Datum({
this.sectionTitle,
this.dataLesson,
});
String? sectionTitle;
List<DataLesson>? dataLesson;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
sectionTitle: json["section_title"],
dataLesson: List<DataLesson>.from(
json["data_lesson"].map((x) => DataLesson.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"section_title": sectionTitle,
"data_lesson": List<dynamic>.from(dataLesson!.map((x) => x.toJson())),
};
}
class DataLesson {
DataLesson(
{this.lessonId,
this.title,
this.duration,
this.progress,
this.attachmentType,
this.videoType,
this.videoUrl,
this.lessonType,
this.attachment,
this.isSkip,
this.isFinished,
this.summary});
String? progress;
String? lessonId;
String? title;
String? duration;
String? attachmentType;
String? videoType;
String? videoUrl;
String? lessonType;
dynamic attachment;
String? isSkip;
String? summary;
int? isFinished;
factory DataLesson.fromJson(Map<String, dynamic> json) => DataLesson(
lessonId: json["lesson_id"],
title: json["title"],
duration: json["duration"],
progress: json["progress_video"],
attachmentType: json["attachment_type"],
videoType: json["video_type"],
videoUrl: json["video_url"],
lessonType: json["lesson_type"],
attachment: json["attachment"],
isSkip: json["is_skip"],
isFinished: json["is_finished"],
summary: json["summary"],
);
get courseId => null;
Map<String, dynamic> toJson() => {
"lesson_id": lessonId,
"title": title,
"duration": duration,
"progress_video": progress,
"attachment_type": attachmentType,
"video_type": videoType,
"video_url": videoUrl,
"lesson_type": lessonType,
"attachment": attachment,
"is_skip": isSkip,
"is_finished": isFinished,
"summary": summary,
};
}
class NewMap {
NewMap({
required this.title,
});
final List<Title> title;
factory NewMap.fromMap(Map<String, dynamic> json) => NewMap(
title: List<Title>.from(json["Title"].map((x) => Title.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"Title": List<dynamic>.from(title.map((x) => x.toMap())),
};
}
class Title {
Title({
this.courseId,
this.lessonId,
this.sectionTitle,
this.lessonTitle,
this.duration,
this.attachmentType,
this.videoType,
this.videoUrl,
this.lessonType,
this.attachment,
this.isSkip,
this.isFinished,
});
final String? courseId;
final String? lessonId;
final String? sectionTitle;
final String? lessonTitle;
final String? duration;
final String? attachmentType;
final String? videoType;
final String? videoUrl;
final String? lessonType;
final dynamic attachment;
final String? isSkip;
final int? isFinished;
factory Title.fromMap(Map<String, dynamic> json) => Title(
courseId: json["course_id"],
lessonId: json["lesson_id"],
sectionTitle: json["section_title"],
lessonTitle: json["lesson_title"],
duration: json["duration"],
attachmentType: json["attachment_type"],
videoType: json["video_type"],
videoUrl: json["video_url"] == '' ? 'a' : json["video_url"],
lessonType: json["lesson_type"],
attachment: json["attachment"],
isSkip: json["is_skip"],
isFinished: json["is_finished"],
);
Map<String, dynamic> toMap() => {
"course_id": courseId,
"lesson_id": lessonId,
"section_title": sectionTitle,
"lesson_title": lessonTitle,
"duration": duration,
"attachment_type": attachmentType,
"video_type": videoType,
"video_url": videoUrl,
"lesson_type": lessonType,
"attachment": attachment,
"is_skip": isSkip,
"is_finished": isFinished,
};
}

View File

@ -0,0 +1,15 @@
class SocialLink {
SocialLink({
this.facebook,
});
String? facebook;
factory SocialLink.fromJson(Map<String, dynamic> json) => SocialLink(
facebook: json["facebook"],
);
Map<String, dynamic> toJson() => {
"facebook": facebook,
};
}

View File

@ -0,0 +1,23 @@
class SubCategoryModel {
final String subId;
final String nameSubCategory;
SubCategoryModel({
required this.subId,
required this.nameSubCategory,
});
factory SubCategoryModel.fromJson(Map<String, dynamic> json) {
return SubCategoryModel(
subId: json['id'],
nameSubCategory: json['name_subcategory'],
);
}
Map<String, dynamic> toJson() {
return {
'id': subId,
'name_subcategory': nameSubCategory,
};
}
}

View File

@ -0,0 +1,43 @@
class UpdateDataDiriModel {
UpdateDataDiriModel({
this.status,
this.error,
this.messages,
});
int? status;
bool? error;
dynamic messages;
factory UpdateDataDiriModel.fromJson(Map<String, dynamic> json) => UpdateDataDiriModel(
status: json["status"],
error: json["error"],
messages: json["status"] != 200
? MessagesOfUpdateDataDiriModel.fromJson(json["data"]["message"])
: json["data"]["messages"],
);
}
class MessagesOfUpdateDataDiriModel {
MessagesOfUpdateDataDiriModel({
this.fullname,
this.phone,
this.datebirth,
this.email,
this.gender,
});
String? fullname;
String? phone;
String? datebirth;
String? email;
String? gender;
factory MessagesOfUpdateDataDiriModel.fromJson(Map<String, dynamic> json) => MessagesOfUpdateDataDiriModel(
fullname: json["full_name"],
phone: json["phone"],
datebirth: json["datebirth"],
email: json["email"],
gender: json["jenis_kel"],
);
}

View File

@ -0,0 +1,57 @@
class UpdateIncompleteProfileModel {
UpdateIncompleteProfileModel({
this.status,
this.error,
this.messages,
});
int? status;
bool? error;
dynamic messages;
factory UpdateIncompleteProfileModel.fromJson(Map<String, dynamic> json) {
UpdateIncompleteProfileModel updateIncompleteProfileModel;
try {
updateIncompleteProfileModel = UpdateIncompleteProfileModel(
status: json["status"],
error: json["error"],
messages: json["status"] == 200
? json["data"]["messages"]
: json["status"] == 404
? json["message"]
: MessagesOfIncompleteProfileModel.fromJson(json["data"]["message"])
);
} catch(e) {
updateIncompleteProfileModel = UpdateIncompleteProfileModel(
status: json["status"],
error: json["error"],
messages: json["data"]["message"]
);
}
return updateIncompleteProfileModel;
}
}
class MessagesOfIncompleteProfileModel {
MessagesOfIncompleteProfileModel({
this.fullname,
this.phone,
this.datebirth,
this.email,
this.gender,
});
String? fullname;
String? phone;
String? datebirth;
String? email;
String? gender;
factory MessagesOfIncompleteProfileModel.fromJson(Map<String, dynamic> json) => MessagesOfIncompleteProfileModel(
fullname: json["full_name"],
phone: json["phone"],
datebirth: json["datebirth"],
email: json["email"],
gender: json["jenis_kel"],
);
}

View File

@ -0,0 +1,47 @@
class UpdatePasswordModel {
UpdatePasswordModel({
this.status,
this.error = false,
required this.data,
});
final int? status;
final bool error;
final List<Data> data;
factory UpdatePasswordModel.fromJson(Map<String, dynamic> json) =>
UpdatePasswordModel(
status: json["status"],
error: json["error"],
data: List<Data>.from(json["data"].map((x) => Data.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Data {
Data({
this.message,
//required this.social_link,
});
final String? message;
//final List<SocialLink?> social_link;
factory Data.fromJson(Map<String, dynamic> json) => Data(
message: json["message"],
//social_link: List<SocialLink>.from(
//json["social_link"].map((x) => SocialLink.fromJson(x))).toList(),
);
Map<String, dynamic> toJson() => {
"message": message,
//"social_link":
// List<dynamic>.from(social_link.map((x) => x!.toJson())).toList(),
};
}

View File

@ -0,0 +1,53 @@
class UserInfoIncompleteModel {
UserInfoIncompleteModel({
this.status,
this.error,
this.data,
});
final int? status;
final bool? error;
final Data? data;
factory UserInfoIncompleteModel.fromJson(Map<String, dynamic> json) => UserInfoIncompleteModel(
status: json["status"],
error: json["error"],
data: Data.fromJson(json["data"][0]),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": data == null
? null
: [data!.toJson()],
};
}
class Data {
Data({
this.idUser,
this.fullname,
this.email,
this.phone,
});
final String? idUser;
final String? fullname;
final String? email;
final String? phone;
factory Data.fromJson(Map<String, dynamic> json) => Data(
idUser: json["id_user"],
fullname: json["full_name"],
email: json["email"],
phone: json["phone"],
);
Map<String, dynamic> toJson() => {
"id_user": idUser,
"full_name": fullname,
"email": email,
"phone": phone,
};
}

View File

@ -0,0 +1,55 @@
class UserInfoModel {
UserInfoModel({
this.status,
this.error = false,
required this.data,
});
final int? status;
final bool error;
final List<Data> data;
factory UserInfoModel.fromJson(Map<String, dynamic> json) => UserInfoModel(
status: json["status"],
error: json["error"],
data: List<Data>.from(json["data"].map((x) => Data.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Data {
Data({
this.idUser,
this.fullname,
this.email,
this.fotoProfile,
this.isInstructor,
});
final String? idUser;
final String? fullname;
final String? email;
final String? fotoProfile;
final int? isInstructor;
factory Data.fromJson(Map<String, dynamic> json) => Data(
idUser: json["id_user"],
fullname: json["fullname"],
email: json["email"],
fotoProfile: json["foto_profile"],
isInstructor: json["is_instructor"],
);
Map<String, dynamic> toJson() => {
"id_user": idUser,
"fullname": fullname,
"email": email,
"foto_profile": fotoProfile,
"is_instructor": isInstructor,
};
}

View File

@ -0,0 +1,23 @@
class UserModel {
UserModel({
this.messages,
this.token,
this.expireAt,
});
final String? messages;
String? token;
final int? expireAt;
factory UserModel.fromJson(Map<String, dynamic> json) => UserModel(
messages: json["messages"],
token: json["token"],
expireAt: json["expire_at"],
);
Map<String, dynamic> toJson() => {
"messages": messages,
"token": token,
"expire_at": expireAt,
};
}

View File

@ -0,0 +1,90 @@
class VoucherModel {
int? status;
bool? error;
List<DataVoucher>? data;
VoucherModel({this.status, this.error, this.data});
VoucherModel.fromJson(Map<String, dynamic> json) {
status =
json['status'] is String ? int.parse(json['status']) : json['status'];
error = json['error'];
if (json['data'] != null) {
data = <DataVoucher>[];
json['data'].forEach((v) {
data!.add(new DataVoucher.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
data['error'] = this.error;
if (this.data != null) {
data['data'] = this.data!.map((v) => v.toJson()).toList();
}
return data;
}
}
class DataVoucher {
String? idCourse;
String? typeCoupon;
String? value;
String? discountFlag;
String? courseName;
String? instructor;
String? fotoProfile;
String? thubmnail;
String? originalPrice;
dynamic discountPrice;
dynamic finalPrice;
DataVoucher(
{this.idCourse,
this.typeCoupon,
this.value,
this.discountFlag,
this.courseName,
this.instructor,
this.fotoProfile,
this.thubmnail,
this.originalPrice,
this.discountPrice,
this.finalPrice});
DataVoucher.fromJson(Map<String, dynamic> json) {
idCourse = json['id_course'];
typeCoupon = json['type_coupon'];
value = json['value'];
discountFlag = json['discount_flag'];
courseName = json['course_name'];
instructor = json['instructor'];
fotoProfile = json['foto_profile'];
thubmnail = json['thubmnail'];
originalPrice = json['original_price'];
discountPrice = json['discount_price'] is String
? int.parse(json['discount_price'])
: json['discount_price'];
finalPrice = json['final_price'] is String
? int.parse(json['final_price'])
: json['final_price'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id_course'] = this.idCourse;
data['type_coupon'] = this.typeCoupon;
data['value'] = this.value;
data['discount_flag'] = this.discountFlag;
data['course_name'] = this.courseName;
data['instructor'] = this.instructor;
data['foto_profile'] = this.fotoProfile;
data['thubmnail'] = this.thubmnail;
data['original_price'] = this.originalPrice;
data['discount_price'] = this.discountPrice;
data['final_price'] = this.finalPrice;
return data;
}
}

View File

@ -0,0 +1,152 @@
/// Class untuk mengambil data wishlist
class WishlistModel {
WishlistModel({
this.status,
this.error,
required this.data,
});
final int? status;
final bool? error;
final List<List<DataWihslistModel>> data;
factory WishlistModel.fromJson(Map<String, dynamic> json) => WishlistModel(
status: json["status"],
error: json["error"],
data: List<List<DataWihslistModel>>.from(json["data"].map((x) =>
List<DataWihslistModel>.from(
x.map((x) => DataWihslistModel.fromJson(x))))),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": List<dynamic>.from(
data.map((x) => List<dynamic>.from(x.map((x) => x.toJson())))),
};
}
class DataWihslistModel {
DataWihslistModel({
this.wishlistId,
this.courseId,
this.title,
this.price,
this.instructor,
this.thumbnail,
this.discountPrice,
this.discountFlag,
this.totalDiscount,
this.student,
required this.review,
this.fotoProfile,
});
final String? wishlistId;
final String? courseId;
final String? title;
final String? price;
final String? instructor;
final String? thumbnail;
final String? discountPrice;
final String? discountFlag;
final int? totalDiscount;
final String? student;
final List<Review> review;
final dynamic fotoProfile;
factory DataWihslistModel.fromJson(Map<String, dynamic> json) =>
DataWihslistModel(
wishlistId: json["wishlist_id"],
courseId: json["course_id"],
title: json["title"],
price: json["price"],
instructor: json["instructor"],
thumbnail: json["thumbnail"] == null ? null : json["thumbnail"],
discountPrice: json["discount_price"],
discountFlag: json["discount_flag"],
totalDiscount: json["total_discount"],
student: json["student"],
review:
List<Review>.from(json["review"].map((x) => Review.fromJson(x))),
fotoProfile: json["foto_profile"],
);
Map<String, dynamic> toJson() => {
"wishlist_id": wishlistId,
"course_id": courseId,
"title": title,
"price": price,
"instructor": instructor,
"thumbnail": thumbnail == null ? null : thumbnail,
"discount_price": discountPrice,
"discount_flag": discountFlag,
"total_discount": totalDiscount,
"student": student,
"review": List<dynamic>.from(review.map((x) => x.toJson())),
"foto_profile": fotoProfile,
};
}
class Review {
Review({
this.totalReview,
this.avgRating,
});
final String? totalReview;
final int? avgRating;
factory Review.fromJson(Map<String, dynamic> json) => Review(
totalReview: json["total_review"],
avgRating: json["avg_rating"] == null ? null : json["avg_rating"],
);
Map<String, dynamic> toJson() => {
"total_review": totalReview,
"avg_rating": avgRating == null ? null : avgRating,
};
}
class WishlistPostModel {
WishlistPostModel({
this.status,
this.error,
required this.data,
});
final int? status;
final bool? error;
final DataPostWishlist data;
factory WishlistPostModel.fromJson(Map<String, dynamic> json) =>
WishlistPostModel(
status: json["status"],
error: json["error"],
data: DataPostWishlist.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": data.toJson(),
};
}
class DataPostWishlist {
DataPostWishlist({
this.messages,
});
final String? messages;
factory DataPostWishlist.fromJson(Map<String, dynamic> json) =>
DataPostWishlist(
messages: json["messages"],
);
Map<String, dynamic> toJson() => {
"messages": messages,
};
}

View File

@ -0,0 +1,54 @@
// To parse this JSON data, do
//
// final zeroPrice = zeroPriceFromJson(jsonString);
import 'dart:convert';
ZeroPrice zeroPriceFromJson(String str) => ZeroPrice.fromJson(json.decode(str));
String zeroPriceToJson(ZeroPrice data) => json.encode(data.toJson());
class ZeroPrice {
ZeroPrice({
this.status,
this.error,
this.data,
});
final int? status;
final bool? error;
List<Data>? data;
factory ZeroPrice.fromJson(Map<String, dynamic> json) => ZeroPrice(
status: json["status"],
error: json["error"],
data: List<Data>.from(json["data"]
.map((x) => List<Data>.from(x.map((x) => Data.fromJson(x))))),
);
Map<String, dynamic> toJson() => {
"status": status,
"error": error,
"data": List<dynamic>.from(data!.map((x) => x.toJson())),
};
}
class Data {
Data({
this.orderId,
this.grossAmount,
});
final String? orderId;
final String? grossAmount;
factory Data.fromJson(Map<String, dynamic> json) => Data(
orderId: json["order_id"],
grossAmount: json["gross_amount"],
);
Map<String, dynamic> toJson() => {
"order_id": orderId,
"gross_amount": grossAmount,
};
}

0
lib/providers/.gitkeep Normal file
View File

View File

@ -0,0 +1,98 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:initial_folder/models/announcement_model.dart';
import 'package:initial_folder/services/announcement_service.dart';
import 'package:rxdart/rxdart.dart';
enum ResultState { loading, noData, hasData, error }
enum ResultStateLike { loading, error }
class AnnouncementProvider with ChangeNotifier {
final _service = AnnouncementService();
StreamController<AnnouncementModel> streamController = BehaviorSubject();
String _message = '';
String get message => _message;
ResultState? _state;
ResultState? get state => _state;
AnnouncementModel? _announcementModel;
AnnouncementModel? get result => _announcementModel;
set annoucementModel(AnnouncementModel? announcementModel) {
_announcementModel = announcementModel;
notifyListeners();
}
Stream<AnnouncementModel> get announcementStream {
return streamController.stream;
}
Future<void> getAnnouncement(String id) async {
try {
AnnouncementModel announcementModel = await _service.getAnnouncement(id);
if (announcementModel.error == true && announcementModel.status == 404) {
// Jika respons adalah 404 (tidak ditemukan), tangani objek dummy di sini
// Misalnya, menampilkan pesan kepada pengguna bahwa tidak ada data yang ditemukan
// Atau menampilkan UI yang sesuai
print('masuk rerror dsiinii');
streamController.add(announcementModel);
} else {
// Jika respons adalah 200 (berhasil), tambahkan data ke dalam stream
streamController.add(announcementModel);
}
} catch (e) {
throw Error;
}
}
Future<bool> likeAnnouncement(String tokenAnnouncement) async {
try {
_state = ResultState.loading;
notifyListeners();
bool response =
await AnnouncementService().likeAnnouncement(tokenAnnouncement);
if (response) {
_state = ResultState.hasData;
notifyListeners();
return true;
} else {
_state = ResultState.noData;
notifyListeners();
return false;
}
} catch (e) {
_state = ResultState.error;
notifyListeners();
return false;
}
}
Future<bool> replyAnnouncement(String textBody, String idAnnouncmenet,
String tokenAnnouncement, String idAnnouncement) async {
try {
_state = ResultState.loading;
notifyListeners();
bool response = await AnnouncementService()
.replyAnnouncement(tokenAnnouncement, textBody, idAnnouncement);
if (response) {
_state = ResultState.hasData;
notifyListeners();
return true;
} else {
_state = ResultState.noData;
notifyListeners();
return false;
}
} catch (e) {
_state = ResultState.error;
notifyListeners();
return false;
}
}
}

View File

@ -0,0 +1,53 @@
import 'package:flutter/material.dart';
import 'package:initial_folder/models/user_model.dart';
import 'package:initial_folder/services/auth_service.dart';
class AuthProvider with ChangeNotifier {
UserModel? _user;
UserModel? get user => _user;
set user(UserModel? user) {
_user = user;
notifyListeners();
}
Future<bool> register({
required String name,
required String email,
required String password,
required String phoneNumber,
}) async {
try {
UserModel? user = await AuthService().register(
name: name,
email: email,
password: password,
phoneNumber: phoneNumber,
);
_user = user;
return true;
} catch (e) {
print("Exception: $e");
throw e;
}
}
Future<bool> login({
required String email,
required String password,
}) async {
try {
UserModel user = await AuthService().login(
email: email,
password: password,
);
_user = user;
return true;
} catch (e) {
print("EXception: $e");
return false;
}
}
}

View File

@ -0,0 +1,53 @@
import 'package:flutter/material.dart';
import 'package:initial_folder/models/banners_model.dart';
import 'package:initial_folder/services/banners_service.dart';
enum ResultState { Loading, NoData, HasData, Error }
class BannersProvider with ChangeNotifier {
final BannersService bannersService;
BannersProvider({required this.bannersService}) {
getAllBanners();
}
List<BannersModel> _banners = [];
ResultState? _state;
String _message = '';
String _status = '';
List<BannersModel> get result => _banners;
ResultState? get state => _state;
String get message => _message;
String get status => _status;
set banners(List<BannersModel> banners) {
_banners = banners;
notifyListeners();
}
Future<dynamic> getAllBanners() async {
try {
_state = ResultState.Loading;
notifyListeners();
var result = await bannersService.getAllBanners();
if (result['status'] == 404) {
_state = ResultState.NoData;
print("Harusnya ke sini");
notifyListeners();
return _message = 'Banner kosong';
} else {
_state = ResultState.HasData;
notifyListeners();
return _banners = result['data'];
}
} catch (e) {
_state = ResultState.Error;
print('Gagal banner provider $e');
notifyListeners();
return _message = 'Error --> $e';
}
}
}

View File

@ -0,0 +1,62 @@
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:initial_folder/models/cart_model.dart';
import 'package:initial_folder/services/cart_service.dart';
enum ResultState { loading, succes, failed }
class CartProvider with ChangeNotifier {
final CartService cartService;
CartProvider({required this.cartService});
CartModel? _cartModel;
CartModel? get cartModel => _cartModel;
ResultState? _state;
ResultState? get state => _state;
set cartModel(CartModel? cartModel) {
_cartModel = cartModel;
notifyListeners();
}
Future<bool> addCart(_idCourse) async {
try {
_state = ResultState.loading;
notifyListeners();
bool cart = await cartService.addCart(_idCourse);
if (cart) {
_state = ResultState.succes;
notifyListeners();
} else if (!cart) {
_state = ResultState.failed;
notifyListeners();
}
return true;
} on SocketException {
return false;
} catch (e) {
_state = ResultState.failed;
notifyListeners();
print("Exceptions: $e");
return false;
}
}
Future<bool> deleteCart(_idCart) async {
try {
bool cart = await cartService.deleteCart(_idCart);
if (cart) {
_state = ResultState.succes;
notifyListeners();
} else if (!cart) {
_state = ResultState.failed;
notifyListeners();
}
return true;
} on SocketException {
return false;
} catch (e) {
print("Exceptions: $e");
return false;
}
}
}

View File

@ -0,0 +1,78 @@
import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:initial_folder/models/carts_model.dart';
import 'package:initial_folder/services/cart_service.dart';
enum ResultState { Loading, NoData, HasData, Error }
class CartsProvider with ChangeNotifier {
final CartService cartService;
CartsProvider({required this.cartService}) {
getCarts();
}
CartsModel? _cartsModel;
CartsModel? get result => _cartsModel;
ResultState? _state;
ResultState? get state => _state;
String _message = '';
String _finalPrice = '';
String get message => _message;
String get finalPrice => _finalPrice;
int _length = 0;
int get lenght => _length;
set lengthCarts(int v) {
_length = v;
notifyListeners();
}
List _data = [];
List get data => _data;
// StreamController<List<DataCartsModel>> dataStream = StreamController.broadcast();
set carts(CartsModel carts) {
_cartsModel = carts;
notifyListeners();
}
void clear() {
_length = 0;
notifyListeners();
}
Future<dynamic> getCarts() async {
try {
_state = ResultState.Loading;
_data = [];
notifyListeners();
CartsModel carts = await cartService.getCarts();
_length = carts.data.length;
notifyListeners();
if (carts.data.isEmpty) {
_state = ResultState.NoData;
notifyListeners();
return _message = 'Empty Data';
} else {
_data = carts.data.map((e) => e.courseId).toList();
_state = ResultState.HasData;
print(_data);
print("ini dari getcatsrs");
notifyListeners();
return _cartsModel = carts;
}
} catch (e) {
_state = ResultState.Error;
log('$e');
notifyListeners();
return _message = 'Error --> $e';
}
}
}

View File

@ -0,0 +1,76 @@
import 'package:flutter/material.dart';
import 'package:initial_folder/models/catagories_model.dart';
import 'package:initial_folder/models/subcategories_model.dart';
import 'package:initial_folder/services/categories_service.dart';
enum ResultState { Loading, NoData, HasData, Error }
class CategoriesProvider with ChangeNotifier {
final CategoriesService categoriesService;
CategoriesProvider({required this.categoriesService}) {
getAllCategories();
}
List<CategoriesModel> _categories = [];
Map<String, List<SubCategoryModel>> _subCategoriesMap = {};
ResultState? _state;
String _message = '';
List<String?> get ids {
return _categories.map((category) => category.id).toList();
}
List<String?> get nameCategories {
return _categories.map((category) => category.nameCategory).toList();
}
List<CategoriesModel> get result => _categories;
ResultState? get state => _state;
String get message => _message;
String _selectedSubcategoryId = '';
set categories(List<CategoriesModel> categories) {
_categories = categories;
notifyListeners();
}
Map<String, List<SubCategoryModel>> get subCategoriesMap => _subCategoriesMap;
String get selectedSubcategoryId => _selectedSubcategoryId;
set selectedSubcategoryId(String value) {
_selectedSubcategoryId = value;
notifyListeners();
}
Future<dynamic> getAllCategories() async {
try {
_state = ResultState.Loading;
notifyListeners();
List<CategoriesModel> categories =
await categoriesService.getAllCategories();
if (categories.isEmpty) {
_state = ResultState.NoData;
notifyListeners();
return _message = 'Empty Data';
} else {
for (var category in categories) {
List<SubCategoryModel> subCategories =
await categoriesService.getSubCategories(category.id!);
category.subCategories = subCategories;
}
_categories = categories;
_state = ResultState.HasData;
notifyListeners();
}
} catch (e) {
_state = ResultState.Error;
notifyListeners();
return _message = 'Error --> $e';
}
}
}

View File

@ -0,0 +1,181 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:initial_folder/models/certificate_model.dart';
import 'package:initial_folder/models/check_certificate.model.dart';
import 'package:initial_folder/models/my_certificate.dart';
import 'package:initial_folder/services/all_certificate_service.dart';
enum ResultState { Loading, NoData, HasData, Error }
class CertificateProvider with ChangeNotifier {
final AllCertificateServices certificateServices;
CertificateProvider({required this.certificateServices}) {
getAllCertif();
}
bool _isChecked = true;
bool get isChecked => _isChecked;
ResultState? _state;
List<DataMyCertificateModel?>? _allCertificate;
String? _userId;
String? _idPayment;
String? _certificateNo;
String? _username;
String? _title;
String? _idCourse;
int? _progress;
dynamic _finishDate;
int _allCertificateCount = 0;
bool _isSearch = false;
List<DataMyCertificateModel?>? get allCertificate => _allCertificate;
int? get allCertificateCount => _allCertificateCount;
dynamic get finishDate => _finishDate;
String? get idPayment => _idPayment;
String? get certificateNo => _certificateNo;
String? get name => _username;
String? get title => _title;
String? get userId => _userId;
String? get idCourse => _idCourse;
int? get progress => _progress;
bool get isSearch => _isSearch;
ResultState? get state => _state;
Future uploadCertificate(String idPayment, File pdfFile) async {
try {
_state = ResultState.Loading;
notifyListeners();
await certificateServices.uploadCertificate(idPayment, pdfFile);
_state = ResultState.HasData;
notifyListeners();
} catch (e) {
_state = ResultState.Error;
notifyListeners();
print(
"Error download sertifikat $e",
);
}
}
Future getCertif(String idCourse) async {
try {
_state = ResultState.Loading;
notifyListeners();
List<CertificateModel> certif =
await certificateServices.getSertif(idCourse);
if (certif.isEmpty) {
print("Jangan loading terus");
_state = ResultState.NoData;
notifyListeners();
} else {
_state = ResultState.HasData;
notifyListeners();
_idPayment = certif[0].idPayment;
_certificateNo = certif[0].certificateNo;
_username = certif[0].name;
_title = certif[0].title;
_finishDate = certif[0].finishDate;
notifyListeners();
}
} catch (e) {
print("Ini gagal pas pindah ke certif cuy ${e}");
}
}
Future getAllCertif() async {
try {
_state = ResultState.Loading;
notifyListeners();
List<DataMyCertificateModel> allCertificate =
await AllCertificateServices().getAllCertificate();
allCertificate.sort((a, b) => b.progress!.compareTo(a.progress!));
_allCertificateCount = 0;
if (allCertificate.isEmpty) {
_state = ResultState.NoData;
notifyListeners();
} else {
_state = ResultState.HasData;
_isSearch = false;
notifyListeners();
_allCertificate = allCertificate;
for (var data in allCertificate) {
if (data.progress == 100) _allCertificateCount++;
}
notifyListeners();
}
} catch (e) {
print("Jangan loading terus ${e}");
}
}
Future checkSertif(String text) async {
try {
_state = ResultState.Loading;
notifyListeners();
CheckCertificateData certif = await certificateServices.checkSertif(text);
if (certif.certificateNo!.isEmpty) {
_state = ResultState.NoData;
notifyListeners();
} else {
_state = ResultState.HasData;
_idCourse = certif.courseId;
_idPayment = certif.idPayment;
_certificateNo = certif.certificateNo;
_username = certif.name;
_title = certif.title;
_finishDate = certif.finishDate;
_progress = certif.progress;
notifyListeners();
}
} catch (e) {
print("Ini error input no sertif${e}");
}
}
Future clearCheckSertif() async {
_idPayment = null;
}
Future searchCertif(String keyword) async {
try {
_state = ResultState.Loading;
notifyListeners();
List<DataMyCertificateModel> allCertificate =
await AllCertificateServices().searchCertif(keyword);
_allCertificateCount = 0;
if (allCertificate.isEmpty) {
_state = ResultState.NoData;
notifyListeners();
} else {
_state = ResultState.HasData;
_isSearch = true;
notifyListeners();
_allCertificate = allCertificate;
for (var data in allCertificate) {
if (data.progress == 100) {
_allCertificateCount++;
}
}
notifyListeners();
}
} catch (e) {
print(e);
}
}
bool toggleCheckbox([bool value = false]) {
_isChecked = !_isChecked;
notifyListeners();
return _isChecked;
}
}

View File

@ -0,0 +1,12 @@
import 'package:flutter/material.dart';
class CheckboxProvider with ChangeNotifier {
bool _isChecked = false;
bool get isChecked => _isChecked;
set isChecked(bool value) {
_isChecked = value;
notifyListeners();
}
}

View File

@ -0,0 +1,52 @@
import 'package:flutter/material.dart';
import 'package:initial_folder/models/counter_qna_comment_model.dart';
import 'package:initial_folder/services/qna_service.dart';
enum ResultState { loading, noData, hasData, error }
enum ResultStateLike { loading, error }
class CounterQnaCommentProvider with ChangeNotifier {
final String idQna;
CounterQnaCommentProvider({required this.idQna}) {
getCounterComment(idQna);
}
String _message = '';
String get message => _message;
ResultState? _state;
ResultState? get state => _state;
CounterCommentModel? _counterCommentModel;
CounterCommentModel? get result => _counterCommentModel;
set counterComment(CounterCommentModel? counterCommentModel) {
_counterCommentModel = counterCommentModel;
notifyListeners();
}
//Get Counter Comment QNA
Future<dynamic> getCounterComment(String idQna) async {
try {
_state = ResultState.loading;
notifyListeners();
CounterCommentModel counterCommentModel =
await QnaService().getCounterComment(idQna);
// print("Ini Cunter : ${counterCommentModel.data}");
// ignore: unnecessary_null_comparison
if (counterCommentModel.data != null) {
print("ADA DATA");
_state = ResultState.hasData;
notifyListeners();
return _counterCommentModel = counterCommentModel;
} else {
print("TIDAK ADA DATA");
_state = ResultState.noData;
notifyListeners();
return _message = 'Tidak ada Data';
}
} catch (e) {
_state = ResultState.error;
print(e);
notifyListeners();
return _message = 'Error --> $e';
}
}
}

View File

@ -0,0 +1,52 @@
import 'package:flutter/material.dart';
import 'package:initial_folder/models/counter_qna_like_model.dart';
import 'package:initial_folder/services/qna_service.dart';
enum ResultState { loading, noData, hasData, error }
enum ResultStateLike { loading, error }
class CounterQnaLikeProvider with ChangeNotifier {
final String idQna;
CounterQnaLikeProvider({required this.idQna}) {
getLikeComment(idQna);
}
String _message = '';
String get message => _message;
ResultState? _state;
ResultState? get state => _state;
CounterLikeModel? _counterLikeModel;
CounterLikeModel? get result => _counterLikeModel;
set counterComment(CounterLikeModel? counterLikeModel) {
_counterLikeModel = counterLikeModel;
notifyListeners();
}
//Get Counter Like QNA
Future<dynamic> getLikeComment(String idQna) async {
try {
_state = ResultState.loading;
notifyListeners();
CounterLikeModel counterLikeModel =
await QnaService().getCounterLike(idQna);
// print("Ini Cunter : ${counterLikeModel.data}");
// ignore: unnecessary_null_comparison
if (counterLikeModel.data != null) {
print("ADA DATA");
_state = ResultState.hasData;
notifyListeners();
return _counterLikeModel = counterLikeModel;
} else {
print("TIDAK ADA DATA");
_state = ResultState.noData;
notifyListeners();
return _message = 'Tidak ada Data';
}
} catch (e) {
_state = ResultState.error;
print(e);
notifyListeners();
return _message = 'Error --> $e';
}
}
}

View File

@ -0,0 +1,53 @@
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:initial_folder/services/coupon_service.dart';
enum ResultState { Loading, NoData, HasData, Error }
class CouponCourseProvider with ChangeNotifier {
final CouponService couponService;
String coupon;
CouponCourseProvider({required this.couponService, required this.coupon}) {
getDiscountCourse(coupon);
}
dynamic _data;
ResultState? _state;
String _message = '';
dynamic get result => _data;
ResultState? get state => _state;
String get message => _message;
set data(dynamic data) {
_data = data;
notifyListeners();
}
Future<dynamic> getDiscountCourse(coupon) async {
try {
_state = ResultState.Loading;
notifyListeners();
dynamic data = await couponService.getDiscountCourse(coupon);
if (data.isEmpty) {
_state = ResultState.NoData;
notifyListeners();
return _message = 'Empty Data';
} else {
_state = ResultState.HasData;
print("ini berhasil provider kupon ${_data}");
notifyListeners();
return _data = data;
}
} catch (e) {
_state = ResultState.Error;
print("Gagal kupon ${e}");
notifyListeners();
return _message = 'Error --> $e';
}
}
}

View File

@ -0,0 +1,85 @@
import 'package:flutter/material.dart';
import 'package:initial_folder/models/course_model.dart';
import 'package:initial_folder/services/course_by_category_service.dart';
enum ResultState { Loading, NoData, HasData, Error }
class CourseByCategoryProvider with ChangeNotifier {
final CourseByCategoryService courseByCategoryService;
final String id;
final String subId;
final bool fetchBySubcategory;
CourseByCategoryProvider({
required this.courseByCategoryService,
required this.id,
required this.subId,
this.fetchBySubcategory = false,
}) {
if (fetchBySubcategory) {
getCourseByCategory(id, subId);
} else {
getCourseOnlyCategory(id);
}
}
List<CourseModel> _courseByCategory = [];
ResultState? _state;
String _message = '';
List<CourseModel> get result => _courseByCategory;
ResultState? get state => _state;
String get message => _message;
set courseByCategory(List<CourseModel> courseByCategory) {
_courseByCategory = courseByCategory;
notifyListeners();
}
Future<dynamic> getCourseByCategory(_id, subId) async {
try {
_state = ResultState.Loading;
notifyListeners();
List<CourseModel> courseByCategory =
await courseByCategoryService.getCourseCategoryAndSub(_id, subId);
if (courseByCategory.isEmpty) {
_state = ResultState.NoData;
notifyListeners();
return _message = 'Empty Data';
} else {
_state = ResultState.HasData;
print(_courseByCategory);
notifyListeners();
return _courseByCategory = courseByCategory;
}
} catch (e) {
_state = ResultState.Error;
notifyListeners();
return _message = 'Error --> $e';
}
}
Future<dynamic> getCourseOnlyCategory(_id) async {
try {
_state = ResultState.Loading;
notifyListeners();
List<CourseModel> courseByCategory =
await courseByCategoryService.getCourseOnlyCategory(_id);
if (courseByCategory.isEmpty) {
_state = ResultState.NoData;
notifyListeners();
return _message = 'Empty Data';
} else {
_state = ResultState.HasData;
notifyListeners();
return _courseByCategory = courseByCategory;
}
} catch (e) {
_state = ResultState.Error;
notifyListeners();
return _message = 'Error --> $e';
}
}
}

View File

@ -0,0 +1,27 @@
import 'package:flutter/foundation.dart';
import 'package:initial_folder/models/lesson_model.dart';
import 'package:initial_folder/providers/lesson_course_provider.dart';
import 'package:initial_folder/services/current_lesson_service.dart';
class CurrentLessonProvider extends ChangeNotifier {
late LessonModel _currentLesson;
LessonModel get payload => _currentLesson;
ResultState _state = ResultState.loading;
ResultState get state => _state;
Future<dynamic> fetchCurrentLesson(String lessonId) async {
_state = ResultState.loading;
notifyListeners();
try {
final data = await CurrentLessonService().getCurrentLesson(lessonId);
_currentLesson = data;
_state = ResultState.hasData;
notifyListeners();
} catch (e) {
_state = ResultState.error;
notifyListeners();
}
}
}

View File

@ -0,0 +1,137 @@
import 'package:flutter/material.dart';
import 'package:initial_folder/models/data_diri_model.dart';
import 'package:initial_folder/services/user_info_service.dart';
enum ResultStateData { Loading, NoData, HasData, Error }
class DataDiriProvider with ChangeNotifier {
final UserInfoService userInfoService;
DataDiriProvider({
required this.userInfoService,
}) {
getDataDiri();
}
DataDiriModel? _dataDiriModel;
ResultStateData? _state;
String _message = '';
DataDiriModel? get result => _dataDiriModel;
ResultStateData? get state => _state;
String get message => _message;
bool _isNewBirthDate = false;
bool get isNewBirthDate => _isNewBirthDate;
bool _newName = false;
bool get newName => _newName;
bool _newHeadline = false;
bool get newHeadline => _newHeadline;
bool _newBiograpy = false;
bool get newBiograpy => _newBiograpy;
bool _newEmail = false;
bool get newEmail => _newEmail;
bool _newPhone = false;
bool get newPhone => _newPhone;
bool _newGender = false;
bool get newGender => _newGender;
bool _newInstagram = false;
bool get newInstagram => _newInstagram;
bool _newTwitter = false;
bool get newTwitter => _newTwitter;
bool _newFacebook = false;
bool get newFacebook => _newFacebook;
bool _newLinkedin = false;
bool get newLinkedin => _newLinkedin;
set isNewBirthDate(bool value) {
_isNewBirthDate = value;
notifyListeners();
}
set newName(bool value) {
_newName = value;
notifyListeners();
}
set newHeadline(bool value) {
_newHeadline = value;
notifyListeners();
}
set newBiograpy(bool value) {
_newBiograpy = value;
notifyListeners();
}
set newEmail(bool value) {
_newEmail = value;
notifyListeners();
}
set newPhone(bool value) {
_newPhone = value;
notifyListeners();
}
set newGender(bool value) {
_newGender = value;
notifyListeners();
}
set newInstagram(bool value) {
_newInstagram = value;
notifyListeners();
}
set newTwitter(bool value) {
_newTwitter = value;
notifyListeners();
}
set newFacebook(bool value) {
_newFacebook = value;
notifyListeners();
}
set newLinkedin(bool value) {
_newLinkedin = value;
notifyListeners();
}
set dataDiri(DataDiriModel dataDiri) {
_dataDiriModel = dataDiri;
notifyListeners();
}
Future<dynamic> getDataDiri() async {
try {
_state = ResultStateData.Loading;
notifyListeners();
DataDiriModel dataDiri = await userInfoService.getDataDiri();
_state = ResultStateData.HasData;
notifyListeners();
_dataDiriModel = dataDiri;
return _dataDiriModel;
} catch (e) {
_state = ResultStateData.Error;
notifyListeners();
return _message = 'Error --> $e';
}
}
}

View File

@ -0,0 +1,12 @@
import 'package:flutter/material.dart';
class DescriptionProvider with ChangeNotifier {
bool isExpanded;
DescriptionProvider({this.isExpanded = true});
void expanded() {
isExpanded = !isExpanded;
notifyListeners();
}
}

View File

@ -0,0 +1,87 @@
import 'dart:async';
import 'dart:developer';
import 'package:flutter/cupertino.dart';
import 'package:initial_folder/models/detail_course_model.dart';
import 'package:initial_folder/services/course_service.dart';
import 'package:rxdart/rxdart.dart';
enum ResultState { Loading, HasData, Error, NoData }
class DetailCourseCouponProvider with ChangeNotifier {
final CourseService courseService;
final String id;
final String coupon;
DetailCourseCouponProvider(
{required this.courseService, required this.id, required this.coupon}) {
getDetailCourseCoupon(id, coupon);
}
DataDetailCourseModel? _detailCourse;
DataDetailCourseModel? get result => _detailCourse;
ResultState? _state;
String _message = '';
ResultState? get state => _state;
String get message => _message;
set detailCourse(DataDetailCourseModel? detail) {
_detailCourse = detail;
notifyListeners();
}
Future<dynamic> getDetailCourseCoupon(_id, String coupon) async {
try {
_state = ResultState.Loading;
notifyListeners();
DataDetailCourseModel? detail =
await courseService.getDetailCourseCoupon(_id, coupon);
_state = ResultState.HasData;
print("Berhasil detail kupon di provider ${_detailCourse}");
notifyListeners();
return _detailCourse = detail;
} catch (e) {
print("Gagal detail kupon di provider ${e}");
_state = ResultState.Error;
notifyListeners();
return _message = 'Error --> $e';
}
}
}
class DetailCouponProvider with ChangeNotifier {
DataDetailCourseModel? _detailCourse;
DataDetailCourseModel? get result => _detailCourse;
StreamController<DataDetailCourseModel> streamController = BehaviorSubject();
String _message = '';
String get message => _message;
set detailCourse(DataDetailCourseModel? detail) {
_detailCourse = detail;
notifyListeners();
}
Stream<DataDetailCourseModel> get detailStream {
return streamController.stream;
}
Future<void> getDetail(id, coupon) async {
try {
print("Berhasil detail kupon di provider");
DataDetailCourseModel? detail =
await CourseService().getDetailCourseCoupon(id, coupon);
streamController.add(detail);
} catch (e) {
print("Gagal detail kupon di provider 2 ${e}");
}
}
}

View File

@ -0,0 +1,109 @@
import 'dart:async';
import 'dart:developer';
import 'package:flutter/cupertino.dart';
import 'package:initial_folder/models/detail_course_model.dart';
import 'package:initial_folder/screens/splash/splash_screen_login.dart';
import 'package:initial_folder/services/course_service.dart';
import 'package:rxdart/rxdart.dart';
enum ResultState { Loading, HasData, Error, NoData }
class DetailCourseProvider with ChangeNotifier {
final CourseService courseService;
final String id;
DetailCourseProvider({required this.courseService, required this.id}) {
Condition.loginEmail ? getDetailCourseLogin(id) : getDetailCourse(id);
}
DetailCourseModel? _detailCourse;
DetailCourseModel? get result => _detailCourse;
ResultState? _state;
ResultState? get state => _state;
String _message = '';
String get message => _message;
int? get checkoutPrice => _detailCourse?.data[0][0].checkoutPrice;
set detailCourse(DetailCourseModel? detail) {
_detailCourse = detail;
notifyListeners();
}
Future<dynamic> getDetailCourse(_id) async {
try {
_state = ResultState.Loading;
notifyListeners();
DetailCourseModel? detail = await courseService.getDetailCourse(_id);
if (detail.data[0].isEmpty) {
_state = ResultState.NoData;
notifyListeners();
return _message = 'Tidak ada data';
} else {
_state = ResultState.HasData;
notifyListeners();
return _detailCourse = detail;
}
} catch (e) {
_state = ResultState.Error;
print(e);
notifyListeners();
return _message = 'Error --> $e';
}
}
Future<dynamic> getDetailCourseLogin(id) async {
try {
_state = ResultState.Loading;
notifyListeners();
DetailCourseModel? detail = await courseService.getDetailCourseLogin(id);
if (detail.data[0].isEmpty) {
_state = ResultState.NoData;
notifyListeners();
return _message = 'Tidak ada data';
} else {
_state = ResultState.HasData;
notifyListeners();
return _detailCourse = detail;
}
} catch (e) {
_state = ResultState.Error;
print(e);
notifyListeners();
return _message = 'Error --> $e';
}
}
}
class DetailProvider with ChangeNotifier {
DetailCourseModel? _detailCourse;
DetailCourseModel? get result => _detailCourse;
StreamController<DetailCourseModel> streamController = BehaviorSubject();
String _message = '';
String get message => _message;
int? get checkoutPrice => _detailCourse?.data[0][0].checkoutPrice ?? 0;
set detailCourse(DetailCourseModel? detail) {
_detailCourse = detail;
notifyListeners();
}
Stream<DetailCourseModel> get detailStream {
return streamController.stream;
}
Future<void> getDetail(id) async {
try {
DetailCourseModel? detail =
await CourseService().getDetailCourseLogin(id);
streamController.add(detail);
} catch (e) {
log(e as String);
}
}
}

View File

@ -0,0 +1,44 @@
import 'package:flutter/material.dart';
import 'package:initial_folder/models/detail_invoice_model.dart';
import 'package:initial_folder/services/detail_invoice_service.dart';
import 'package:provider/provider.dart';
enum ResultState { loading, noData, hasData, error }
class DetailInvoiceProvider extends ChangeNotifier {
final DetailInvoiceService _detailInvoiceService = DetailInvoiceService();
List<DataDetailInvoiceModel>? _detailInvoice;
String? _message;
String? _thumbnail;
ResultState? _state;
String? get message => _message;
String? get thumbnail => _thumbnail;
List<DataDetailInvoiceModel>? get detailInvoice => _detailInvoice;
ResultState? get state => _state;
set selectedThumbnail(String? value) {
_thumbnail = value;
notifyListeners();
}
Future<dynamic> fetchDetailInvoice(String? orderId) async {
try {
_state = ResultState.loading;
notifyListeners();
final data = await _detailInvoiceService.detailInvoice(orderId);
if (data.isEmpty) {
_state = ResultState.noData;
_message = 'Invoice Detail is Empty';
} else {
_state = ResultState.hasData;
_detailInvoice = data;
}
} catch (e) {
_state = ResultState.error;
_message = 'Error -> $e';
}
notifyListeners();
}
}

View File

@ -0,0 +1,79 @@
import 'package:flutter/foundation.dart';
import 'package:initial_folder/models/detail_rating_course_model.dart';
import 'package:initial_folder/services/course_service.dart';
enum ResultState { Loading, HasData, Error, NoData }
class DetailRatingCourseProvider with ChangeNotifier {
final CourseService courseService;
final String id;
DetailRatingCourseProvider({required this.courseService, required this.id}) {
getDetailCourse(id);
}
RatingCourseDetailModel? _detailRatingCourse;
RatingCourseDetailModel? get result => _detailRatingCourse;
List<DataReview>? _review;
List<DataReview>? get review => _review;
ResultState? _state;
String _message = '';
ResultState? get state => _state;
String get message => _message;
set detailCourse(RatingCourseDetailModel detail) {
_detailRatingCourse = detail;
notifyListeners();
}
int _currentIndex = 0;
int get currentIndex => _currentIndex;
set currentIndex(int index) {
_currentIndex = index;
notifyListeners();
}
Future<dynamic> getDetailCourse([_id]) async {
try {
_state = ResultState.Loading;
notifyListeners();
RatingCourseDetailModel detail =
await courseService.getRatingDetailCourse((_id != null) ? _id : id );
_state = ResultState.HasData;
_review = detail.dataReview;
notifyListeners();
return _detailRatingCourse = detail;
} catch (e) {
_state = ResultState.Error;
notifyListeners();
return _message = 'Error --> $e';
}
}
Future<dynamic> filterCourse(int rating) async {
try {
_state = ResultState.Loading;
notifyListeners();
RatingCourseDetailModel detail =
await courseService.getRatingDetailCourse(id);
_state = ResultState.HasData;
_review = detail.dataReview.where((element) => element.rating == rating.toString()).toList();
notifyListeners();
return _detailRatingCourse = detail;
} catch (e) {
_state = ResultState.Error;
notifyListeners();
return _message = 'Error --> $e';
}
}
}

View File

@ -0,0 +1,19 @@
// import 'package:flutter/material.dart';
// class EmailProvider with ChangeNotifier {
// String? _currentEmail = '';
// String? _currentName = '';
// String? get currentEmail => _currentEmail;
// String? get currentName => _currentName;
// set currentEmail(String? email) {
// _currentEmail = email;
// notifyListeners();
// }
// set currentName(String? name) {
// _currentName = name;
// notifyListeners();
// }
// }

View File

@ -0,0 +1,133 @@
import 'package:flutter/cupertino.dart';
import 'package:initial_folder/models/course_model.dart';
import 'package:initial_folder/services/search_service.dart';
enum ResultState { loading, noData, hasData, error }
class FilterCourseProvider with ChangeNotifier {
final SearchService searchService;
FilterCourseProvider({required this.searchService});
List<CourseModel> _filteredCourse = [];
ResultState? _state;
String _message = '';
List<CourseModel> get filterResult => [..._filteredCourse];
ResultState? get state => _state;
String get message => _message;
List<String> _categories = [''];
List<String> get categories => [..._categories];
void addCategory(String id) {
_categories.add(id);
notifyListeners();
}
void removeCategory(String id) {
_categories.removeWhere((item) => item == id);
notifyListeners();
}
void allCategories() {
_categories = [];
notifyListeners();
}
List<String> _levels = [''];
List<String> get levels => [..._levels];
void addLevel(String level) {
_levels.add(level);
notifyListeners();
}
void removeLevel(String level) {
_levels.removeWhere((item) => item == level);
notifyListeners();
}
void allLevel() {
_levels = [];
}
String _currentIndexRating = '';
String get currentIndexRating => _currentIndexRating;
set currentIndexRating(String index) {
_currentIndexRating = index;
notifyListeners();
}
String _currentIndexPrice = '';
String get currentIndexPrice => _currentIndexPrice;
set currentIndexPrice(String index) {
_currentIndexPrice = index;
notifyListeners();
}
String _currentIndexLevelCheckBox = '';
String get currentIndexLevelCheckBox => _currentIndexLevelCheckBox;
set currentIndexLevelCheckBox(String index) {
_currentIndexLevelCheckBox = index;
notifyListeners();
}
void resetFilter() {
_currentIndexPrice = '';
_currentIndexRating = '';
_categories = [''];
_levels = [''];
_filteredCourse = [];
}
void resetState() {
_state = null;
}
bool _isSearch = false;
bool get isSearch => _isSearch;
void isSearchsTrue() {
_isSearch = true;
notifyListeners();
}
void isSearchsFalse() {
_isSearch = false;
notifyListeners();
}
Future<dynamic> filter({
String category = '',
String price = '',
String level = '',
String language = '',
String rating = '',
String keyword = '',
}) async {
try {
_state = ResultState.loading;
notifyListeners();
List<CourseModel> course = await searchService.filter(
price: price,
level: level,
language: language,
rating: rating,
keyword: keyword,
);
print("Ini keyword filter search ${keyword}");
if (course.isEmpty) {
_state = ResultState.noData;
notifyListeners();
return _message = 'No Data';
} else {
_state = ResultState.hasData;
notifyListeners();
return _filteredCourse = course;
}
} catch (e) {
_state = ResultState.error;
print(e);
notifyListeners();
return _message = 'Error --> $e';
}
}
}

View File

@ -0,0 +1,161 @@
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
// import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:initial_folder/helper/user_info.dart';
import 'package:initial_folder/models/user_model.dart';
import 'package:initial_folder/services/auth_service.dart';
class FirebaseAuthenticationProvider extends ChangeNotifier {
final googleSignIn = GoogleSignIn();
GoogleSignInAccount? _user;
GoogleSignInAccount get user => _user!;
UserModel? _userModel;
UserModel? get userModel => _userModel;
set userModel(UserModel? userModel) {
_userModel = userModel;
notifyListeners();
}
Future googleSignUp() async {
final googleUser = await googleSignIn.signIn();
if (googleUser == null) return;
_user = googleUser;
final googleAuth = await googleUser.authentication;
final credential =
GoogleAuthProvider.credential(accessToken: googleAuth.idToken);
await FirebaseAuth.instance.signInWithCredential(credential);
await AuthService().googleSignInAuth(
idToken: googleAuth.idToken ?? '',
// email: googleUser.email,
// password: '',
);
// _userModel = userModel;
await UsersInfo().setEmail(googleUser.email);
notifyListeners();
return true;
}
Future<bool> googleLogin() async {
try {
print('Preparing');
final googleUser = await googleSignIn.signIn();
print('Start');
if (googleUser == null) {
print('Failed');
await logout();
return false;
}
print('State 1');
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
print('State 2');
final userCredential =
await FirebaseAuth.instance.signInWithCredential(credential);
print("ID Token: ${googleAuth.idToken}");
await AuthService().googleSignInAuth(
idToken: googleAuth.idToken ?? '',
);
// _userModel = userModel;
print('State 3');
await UsersInfo().setEmail(googleUser.email);
print('Login sukses');
notifyListeners();
return true;
} catch (e) {
// print(e);
// return false;
if (e.toString() == 'Exception: Akun anda belum terdaftar') {
await logout();
throw Exception('Akun anda belum terdaftar');
} else {
print(e);
await logout();
return false;
}
}
}
// Future facebookLogin() async {
// try {
// final LoginResult facebookSignIn = await FacebookAuth.instance.login();
// if (facebookSignIn.accessToken == null) {
// await logout();
// return false;
// }
// switch (facebookSignIn.status) {
// case LoginStatus.success:
// try {
// final facebookAuthCredential = FacebookAuthProvider.credential(
// facebookSignIn.accessToken!.token);
// await FirebaseAuth.instance
// .signInWithCredential(facebookAuthCredential);
// String name = await FacebookAuth.instance
// .getUserData()
// .then((data) => data['name']);
// String email = await FacebookAuth.instance
// .getUserData()
// .then((data) => data['email']);
// String pictureUrl = await FacebookAuth.instance
// .getUserData()
// .then((data) => data['picture']['data']['url']);
// UserModel userModel = await AuthService().facebookSignInAuth(
// name: name,
// email: email,
// password: '',
// pictureUrl: pictureUrl,
// );
// _userModel = userModel;
// await UsersInfo().setEmail(email);
// notifyListeners();
// return true;
// } catch (e) {
// await logout();
// return false;
// }
// case LoginStatus.cancelled:
// await logout();
// return false;
// case LoginStatus.failed:
// await logout();
// return false;
// default:
// await logout();
// return false;
// }
// } catch (e) {
// await logout();
// return false;
// }
// }
Future logout() async {
try {
if (googleSignIn.currentUser != null) {
await googleSignIn.disconnect();
} // else if (await FacebookAuth.instance.accessToken != null) {
// await FacebookAuth.instance.logOut();
// }
} finally {
FirebaseAuth.instance.signOut();
notifyListeners();
}
}
}

View File

@ -0,0 +1,19 @@
import 'package:initial_folder/services/forgot_password_service.dart';
import '../models/forgot_password_model.dart';
import 'package:flutter/foundation.dart';
class ForgotPasswordProvider extends ChangeNotifier {
final ForgotService _apiService = ForgotService();
ForgotPasswordModel? _forgotPasswordModel;
ForgotPasswordModel? get forgotPasswordModel => _forgotPasswordModel;
Future<void> forgotPassword(String email) async {
try {
_forgotPasswordModel = await _apiService.forgotPassword(email: email);
notifyListeners();
} catch (e) {
rethrow;
}
}
}

View File

@ -0,0 +1,84 @@
import 'package:flutter/widgets.dart';
import 'package:initial_folder/models/history_transaction_model.dart';
import 'package:initial_folder/services/history_transactions_service.dart';
enum ResultState { loading, noData, hasData, error }
class HistoryTranscationsProvider with ChangeNotifier {
HistoryTranscationsProvider({required this.historyTransactionService}) {
getHistoryTransaction();
}
final HistoryTransactionService historyTransactionService;
ResultState? _state;
String _message = '';
List<HistoryTransactionModel>? _historyTransactionsModel;
List<HistoryTransactionModel>? get historyPayment {
return _historyTransactionsModel == null
? []
: _historyTransactionsModel!
.where((element) => element.statusPayment != '2')
.toList();
}
List<HistoryTransactionModel>? get paymentPending {
return _historyTransactionsModel == null
? []
: _historyTransactionsModel!
.where((element) => element.statusPayment == '2')
.toList();
}
// transaksi dengan status "-5"
List<HistoryTransactionModel>? get paymentAwaitingMethod {
return _historyTransactionsModel == null
? []
: _historyTransactionsModel!
.where((element) => element.statusPayment == '-5')
.toList();
}
ResultState? get state => _state;
String get message => _message;
set histtoryTranscation(List<HistoryTransactionModel> historyTr) {
_historyTransactionsModel = historyTr;
notifyListeners();
}
Stream<List<HistoryTransactionModel>> getHistoryTransactionStream() async* {
while (true) {
List<HistoryTransactionModel>? response =
await historyTransactionService.historyTransactions();
if (response.isNotEmpty) {
yield response
.where((transaction) => transaction.statusPayment == '2')
.toList();
}
}
}
Future<dynamic> getHistoryTransaction() async {
try {
_state = ResultState.loading;
notifyListeners();
List<HistoryTransactionModel>? response =
await historyTransactionService.historyTransactions();
if (response.isEmpty) {
_state = ResultState.noData;
notifyListeners();
return _message = 'Tidak Ada data';
} else {
_state = ResultState.hasData;
notifyListeners();
return _historyTransactionsModel = response;
}
} catch (e) {
_state = ResultState.error;
notifyListeners();
return _message = 'Data transaksi gagal diambil';
}
}
}

View File

@ -0,0 +1,93 @@
import 'package:flutter/material.dart';
import 'package:initial_folder/models/update_incomplete_profile_model.dart';
import 'package:initial_folder/models/user_info_incomplete_model.dart';
import 'package:initial_folder/services/user_info_service.dart';
enum ResultState { Loading, Success, NoData, HasData, Error }
class IncompleteProfileProvider with ChangeNotifier {
final UserInfoService userInfoService;
IncompleteProfileProvider({
required this.userInfoService,
});
UpdateIncompleteProfileModel? _updateIncompleteProfileModel;
UserInfoIncompleteModel? _userInfoIncompleteModel;
ResultState? _state;
bool? _isUserInfoComplete;
String _message = '';
UpdateIncompleteProfileModel? get updateIncompleteProfileModel =>
_updateIncompleteProfileModel;
UserInfoIncompleteModel? get userInfoIncompleteModel =>
_userInfoIncompleteModel;
ResultState? get state => _state;
bool? get isUserInfoComplete => _isUserInfoComplete;
String get message => _message;
Future<bool> getUserInfoIncomplete() async {
try {
_state = ResultState.Loading;
notifyListeners();
UserInfoIncompleteModel userInfoIncomplete =
await userInfoService.getUserInfoIncomplete();
if (userInfoIncomplete.data == null) {
_state = ResultState.NoData;
_isUserInfoComplete = null;
notifyListeners();
return false;
} else {
if (userInfoIncomplete.status == 202) {
_isUserInfoComplete = false;
} else if (userInfoIncomplete.status == 200) {
_isUserInfoComplete = true;
}
notifyListeners();
_userInfoIncompleteModel = userInfoIncomplete;
return true;
}
} catch (e) {
_state = ResultState.Error;
notifyListeners();
_message = 'Error --> $e';
_userInfoIncompleteModel = null;
return false;
}
}
Future<bool> updateIncompleteProfile({
String? fullname,
String? phone,
String? email,
String? newPassword,
String? newConfirmPassword,
}) async {
try {
_state = ResultState.Loading;
notifyListeners();
_updateIncompleteProfileModel =
await UserInfoService().updateIncompleteProfile(
fullname: fullname,
phone: phone,
email: email,
newPassword: newPassword,
newConfirmPassword: newConfirmPassword,
);
if (_updateIncompleteProfileModel != null) {
if (_updateIncompleteProfileModel!.status == 200) {
_state = ResultState.Success;
notifyListeners();
return true;
}
}
return false;
} catch (e) {
print("Exception: $e");
_updateIncompleteProfileModel = null;
return false;
}
}
}

View File

@ -0,0 +1,45 @@
import 'package:flutter/cupertino.dart';
import 'package:initial_folder/models/instructor_model.dart';
import 'package:initial_folder/services/instructor_service.dart';
enum ResultState { Loading, HasData, NoData, Error }
class InstructorProvider with ChangeNotifier {
final InstructorService instructorService;
final int id;
InstructorProvider({required this.instructorService, required this.id}) {
getProfileInstructor(id);
}
InstructorModel? _instructorModel;
ResultState? _state;
String _message = '';
InstructorModel? get result => _instructorModel;
ResultState? get state => _state;
String get message => _message;
set instruktur(InstructorModel instruktur) {
_instructorModel = instruktur;
notifyListeners();
}
Future<dynamic> getProfileInstructor(_id) async {
try {
_state = ResultState.Loading;
notifyListeners();
InstructorModel instruktur =
await instructorService.getInstructorProfile(_id);
if (instruktur.data.isEmpty) {
_state = ResultState.NoData;
notifyListeners();
return _message = 'Tidak Ada Data';
} else {
_state = ResultState.HasData;
notifyListeners();
return _instructorModel = instruktur;
}
} catch (e) {
_state = ResultState.Error;
notifyListeners();
return _message = 'Error --> $e';
}
}
}

View File

@ -0,0 +1,50 @@
import 'package:flutter/material.dart';
import 'package:initial_folder/models/course_model.dart';
import 'package:initial_folder/services/course_service.dart';
enum ResultState { Loading, NoData, HasData, Error }
class LatestCourseProvider with ChangeNotifier {
final CourseService courseService;
LatestCourseProvider({required this.courseService}) {
getLatestCourse();
}
List<CourseModel> _course = [];
ResultState? _state;
String _message = '';
List<CourseModel> get result => _course;
ResultState? get state => _state;
String get message => _message;
set course(List<CourseModel> course) {
_course = course;
notifyListeners();
}
Future<dynamic> getLatestCourse() async {
try {
_state = ResultState.Loading;
notifyListeners();
List<CourseModel> course = await courseService.getLatestCourse();
if (course.isEmpty) {
_state = ResultState.NoData;
notifyListeners();
return _message = 'Empty Data';
} else {
_state = ResultState.HasData;
notifyListeners();
return _course = course;
}
} catch (e) {
_state = ResultState.Error;
notifyListeners();
return _message = 'Error --> $e';
}
}
}

View File

@ -0,0 +1,109 @@
import 'dart:developer';
import 'package:flutter/cupertino.dart';
import 'package:initial_folder/models/lesson_course_model.dart';
import 'package:initial_folder/models/section_model.dart';
import 'package:initial_folder/services/lesson_course_service.dart';
enum ResultState { loading, hasData, noData, error }
// enum ResultStateUpdate { uninitialized, loading, success, eror }
class LessonCourseProvider with ChangeNotifier {
final LessonCourseService lessonCourseService;
final int id;
LessonCourseProvider({required this.lessonCourseService, required this.id}) {
getLessonCourse(id);
}
bool switchbutton = false;
LessonCourseModel? _lessonCourseModel;
SectionModel? _sectionModel;
ResultState? _state;
// ResultStateUpdate _stateUpdate = ResultStateUpdate.uninitialized;
String _message = '';
LessonCourseModel? get result => _lessonCourseModel;
SectionModel? get sectionResult => _sectionModel;
ResultState? get state => _state;
// ResultStateUpdate get stateUpdate => _stateUpdate;
String get message => _message;
String _url = '';
String get url => _url;
set uri(String urlVideo) {
_url = urlVideo;
notifyListeners();
}
indexUri(String indexUri) {
_url = indexUri;
notifyListeners();
}
set lessonCourse(LessonCourseModel lesson) {
_lessonCourseModel = lesson;
notifyListeners();
}
set sectionCourse(SectionModel section) {
_sectionModel = section;
notifyListeners();
}
// set newMap(NewMap lesson) {
// _newMap = lesson;
// notifyListeners();
// }
void autoplay() {
switchbutton = !switchbutton;
notifyListeners();
}
Future<dynamic> getLessonCourse(int _id) async {
try {
_state = ResultState.loading;
notifyListeners();
LessonCourseModel lesson = await lessonCourseService.getLessonCourse(_id);
SectionModel section = await lessonCourseService.getSectionCourse(_id);
if (lesson.data[0].isEmpty && section.data[0].isEmpty) {
_state = ResultState.noData;
notifyListeners();
return _message = 'Empty Data';
} else {
_state = ResultState.hasData;
notifyListeners();
_sectionModel = section;
return _lessonCourseModel = lesson;
}
} catch (e) {
_state = ResultState.error;
notifyListeners();
print('masuk sini');
return _message = 'Error --> $e';
}
}
Future<bool> updateLessonCourse(String _courseId, String _lessonId) async {
try {
// _stateUpdate = ResultStateUpdate.loading;
// notifyListeners();
bool update = await lessonCourseService.updateLessonCourse(_lessonId);
if (update) {
// _stateUpdate = ResultStateUpdate.success;
// notifyListeners();
return true;
}
return false;
} catch (e) {
// _stateUpdate = ResultStateUpdate.eror;
return false;
}
}
}

View File

@ -0,0 +1,33 @@
import 'package:flutter/material.dart';
import 'package:initial_folder/services/announcement_service.dart';
enum ResultState { uninitilized, loading, failed, success }
class LikeOrAnnouncementProvider with ChangeNotifier {
ResultState _state = ResultState.uninitilized;
ResultState get state => _state;
Future<bool> likeOrAnnouncement(String tokenAnnouncement) async {
try {
_state = ResultState.loading;
notifyListeners();
bool response =
await AnnouncementService().likeAnnouncement(tokenAnnouncement);
if (response) {
_state = ResultState.success;
notifyListeners();
return true;
} else {
_state = ResultState.failed;
notifyListeners();
return false;
}
} catch (e) {
_state = ResultState.failed;
notifyListeners();
return false;
}
}
}

View File

@ -0,0 +1,32 @@
import 'package:flutter/material.dart';
import 'package:initial_folder/services/qna_service.dart';
enum ResultState { uninitilized, loading, failed, success }
class LikeOrUnlikeProvider with ChangeNotifier {
ResultState _state = ResultState.uninitilized;
ResultState get state => _state;
//Posting QNA
Future<bool> likeOrUnlike(int idQna) async {
try {
_state = ResultState.loading;
notifyListeners();
bool response = await QnaService().likeOrLike(idQna);
if (response) {
_state = ResultState.success;
notifyListeners();
return true;
} else {
_state = ResultState.failed;
notifyListeners();
return false;
}
} catch (e) {
_state = ResultState.failed;
notifyListeners();
return false;
}
}
}

View File

@ -0,0 +1,18 @@
import 'package:flutter/material.dart';
class LoginProvider with ChangeNotifier {
bool _loadGoogle = false;
bool _loadFacebook = false;
bool get loadGoogle => _loadGoogle;
bool get loadFacebook => _loadFacebook;
loadGoogleActive(bool value) {
_loadGoogle = value;
notifyListeners();
}
loadFacebookActive(bool value) {
_loadFacebook= value;
notifyListeners();
}
}

View File

@ -0,0 +1,14 @@
import 'package:flutter/material.dart';
enum MetodePembayaran { kreditdebit, mandiri, bni, permata, lainnya, gopay }
class MetodeProvider with ChangeNotifier {
MetodePembayaran? _character = MetodePembayaran.kreditdebit;
MetodePembayaran? get character => _character;
set character(MetodePembayaran? value) {
_character = value;
notifyListeners();
}
}

View File

@ -0,0 +1,87 @@
import 'package:flutter/material.dart';
import 'package:initial_folder/models/my_course_model.dart';
import 'package:initial_folder/services/course_service.dart';
enum ResultState { Loading, NoData, HasData, Error }
enum SearchResultState { Loading, NoData, HasData, Error }
class MyCourseProvider with ChangeNotifier {
final CourseService courseService;
MyCourseProvider({required this.courseService}) {
getMyCourse();
}
MyCourseModel? _myCourseModel;
MyCourseModel? _searchCourseModel;
ResultState? _state;
SearchResultState? _searchResultState;
String _message = '';
MyCourseModel? get result => _myCourseModel;
MyCourseModel? get searchResult => _searchCourseModel;
ResultState? get state => _state;
SearchResultState? get searchResultState => _searchResultState;
String get message => _message;
set myCourse(MyCourseModel myCourse) {
_myCourseModel = myCourse;
notifyListeners();
}
Future<dynamic> getMyCourse() async {
try {
_state = ResultState.Loading;
notifyListeners();
MyCourseModel myCourse = await courseService.getMyCourse();
if (myCourse.data[0].isEmpty) {
_state = ResultState.NoData;
notifyListeners();
return _message = 'Empty Data';
} else {
_state = ResultState.HasData;
notifyListeners();
return _myCourseModel = myCourse;
}
} catch (e) {
_state = ResultState.Error;
notifyListeners();
print('resultstate mycourse eror');
return _message = 'Error --> $e';
}
}
Future<dynamic> getSearchMyCourse(String courseName) async {
try {
_searchResultState = SearchResultState.Loading;
notifyListeners();
MyCourseModel myCourse =
await courseService.getSearchMyCourse(courseName);
if (myCourse.data[0].isEmpty) {
_searchResultState = SearchResultState.NoData;
notifyListeners();
return _message = 'Empty Data';
} else {
_searchResultState = SearchResultState.HasData;
notifyListeners();
return _searchCourseModel = myCourse;
}
} catch (e) {
_searchResultState = SearchResultState.Error;
notifyListeners();
return _message = 'Error --> $e';
}
}
clearSearch() {
_searchResultState = null;
Future.delayed(Duration(seconds: 2), () {
if (_searchCourseModel != null && _searchCourseModel!.data.isNotEmpty) {
_searchCourseModel!.data[0].clear();
}
});
}
}

View File

@ -0,0 +1,127 @@
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:initial_folder/models/notification.dart';
import 'package:initial_folder/services/notification_service.dart';
enum resultState { Loading, NoData, HasData, Error }
enum countState { Loading, NoData, HasData, Error }
class NotificationProvider with ChangeNotifier {
final NotificationServices notificationServices;
NotificationProvider({required this.notificationServices}) {
getMyNotification();
}
List<NotificationData> _notificationData = [];
List<NotificationDataAnnouncementUser> _notificationDataAnnouncementUser = [];
resultState? _state;
countState? _cState;
int _notificationCount = 0;
String _message = '';
List<NotificationData> get result => _notificationData;
List<NotificationDataAnnouncementUser> get resultAnnouncement =>
_notificationDataAnnouncementUser;
int get notificationCount => _notificationCount;
String get message => _message;
resultState? get state => _state;
countState? get cState => _cState;
changeIsRead(List<NotificationData> list, int index) {
list[index].isRead = "1";
if (_notificationCount > 0) {
_notificationCount--;
}
notifyListeners();
}
changeAllRead() {
if (_state == resultState.HasData) {
for (final notif in _notificationData) {
notif.isRead = "1";
}
_notificationCount = 0;
notifyListeners();
}
}
Future<dynamic> getMyNotification() async {
try {
_state = resultState.Loading;
notifyListeners();
var notifications = await notificationServices.getNotification();
List<NotificationData> myNotification = notifications[0];
List<NotificationDataAnnouncementUser> myNotificationAnnouncement =
notifications[1];
if (myNotification.isEmpty && myNotificationAnnouncement.isEmpty) {
_state = resultState.NoData;
notifyListeners();
return _message = 'Empty Data';
} else {
_state = resultState.HasData;
_notificationData = myNotification;
_notificationDataAnnouncementUser = myNotificationAnnouncement;
_notificationData
.sort((a, b) => b.timestamps!.compareTo(a.timestamps!));
_notificationDataAnnouncementUser
.sort((a, b) => b.timestamps!.compareTo(a.timestamps!));
_notificationCount =
_notificationData.where((notif) => notif.isRead == "0").length;
notifyListeners();
return [_notificationData, _notificationDataAnnouncementUser];
}
} catch (e, stacktrace) {
print(stacktrace.toString());
_state = resultState.Error;
notifyListeners();
return _message = 'Error --> $e';
}
}
Future markAsRead() async {
try {
await notificationServices.readAllNotification();
notifyListeners();
} catch (e) {
if (kDebugMode) {
print("Error: --> $e");
}
}
}
Future getNotificationCount() async {
try {
_cState = countState.Loading;
notifyListeners();
int notificationCount =
_notificationData.where((notif) => notif.isRead == "0").length;
if (notificationCount == 0) {
_cState = countState.NoData;
_notificationCount = 0;
notifyListeners();
} else {
_cState = countState.HasData;
_notificationCount = notificationCount;
notifyListeners();
}
} catch (e) {
_cState = countState.Error;
notifyListeners();
return _message = 'Error --> $e';
}
}
decreaseNotificationCount() {
if (_notificationCount > 0) {
_notificationCount--;
}
notifyListeners();
}
}

View File

@ -0,0 +1,118 @@
import 'package:flutter/cupertino.dart';
import 'package:initial_folder/models/order_model.dart';
enum ResultState { loading, succes, failed }
class OrderProvider with ChangeNotifier {
ResultState? _state;
ResultState? get state => _state;
String? _totalPrice;
String? _discountPrice;
String? _idCourse;
String? _thumbnail;
String? _title;
String? _instructor;
String? get totalPrice => _totalPrice;
String? get discountPrice => _discountPrice;
String? get idCourse => _idCourse;
String? get thumbnail => _thumbnail;
String? get title => _title;
String? get instructor => _instructor;
set selectedThumbnail(String value) {
_thumbnail = value;
}
set selectedTitle(String value) {
_title = value;
}
set selectedInstructor(String value) {
_instructor = value;
}
void getTotalPrice(String total) {
_totalPrice = total;
}
void getdiscountPrice(String discountPrice) {
_discountPrice = discountPrice;
}
void getIdCourse(String idCourse) {
_idCourse = idCourse;
}
List<OrderModel> _orders = [];
List<OrderModel> get orders => _orders;
List<Map<String, String>> _invoice = [];
List<Map<String, String>> get invoice => _invoice;
void addOrder({
String? id,
String? title,
String? price,
String? imageUrl,
String? discountPrice,
String? instructor,
}) {
_orders.add(
OrderModel(
idCourse: id as String,
title: title as String,
price: price as String,
instructor: instructor as String,
imageUrl: imageUrl!,
discountPrice: discountPrice as String,
),
);
_invoice.add({
"id_kursus": id,
"title_kursus": title,
"qty": "1",
"harga": discountPrice == "0" ? price : discountPrice
});
}
void removeOrder(
{String? id,
String? title,
String? price,
String? imageUrl,
String? discountPrice,
String? instructor}) {
_orders.remove(OrderModel(
idCourse: id ?? '',
title: title ?? '',
price: price ?? '',
instructor: instructor ?? '',
imageUrl: imageUrl ?? '',
discountPrice: discountPrice ?? '',
));
_invoice.remove({
"id_kursus": id ?? '',
"title_kursus": title ?? '',
"qty": "1",
"harga": (discountPrice == "0" || discountPrice == null)
? price
: discountPrice
});
}
void clear() {
_orders = [];
_invoice = [];
}
// void addInvoice({
// required String id,
// required String title,
// required String price,
// }) {
// _invoice.add(
// {"id_kursus": id, "title_kursus": title, "qty": "1", "harga": price});
// }
}

View File

@ -0,0 +1,75 @@
import 'package:flutter/material.dart';
import 'package:initial_folder/models/course_model.dart';
import 'package:initial_folder/services/course_service.dart';
enum ResultState { Loading, NoData, HasData, Error }
class OthersCourseProvider with ChangeNotifier {
final CourseService otherCourseService;
OthersCourseProvider({required this.otherCourseService}) {
getOthersCourse();
}
List<CourseModel> _othersCourse = [];
ResultState? _state;
String _message = '';
List<CourseModel> get result => _othersCourse;
ResultState? get state => _state;
String get message => _message;
int _page = 1;
int get page => _page;
bool _loading = true;
bool get loading => _loading;
set course(List<CourseModel> course) {
_othersCourse = course;
notifyListeners();
}
Future<dynamic> getOthersCourse() async {
try {
_state = ResultState.Loading;
notifyListeners();
List<CourseModel> course =
await otherCourseService.getOthersCourse(_page);
if (course.isEmpty) {
_state = ResultState.NoData;
notifyListeners();
return _message = 'Empty Data';
} else {
course.shuffle();
_state = ResultState.HasData;
notifyListeners();
return _othersCourse = course;
}
} catch (e) {
_state = ResultState.Error;
notifyListeners();
return _message = 'Error --> $e';
}
}
Future<dynamic> getOthersCourses() async {
try {
List<CourseModel> res =
await otherCourseService.getOthersCourse(_page + 1);
if (res.isNotEmpty) {
res.shuffle();
_page += 1;
notifyListeners();
return _othersCourse.addAll(res);
} else {
_loading = false;
notifyListeners();
}
} catch (e) {
_state = ResultState.Error;
notifyListeners();
return _message = 'Error --> $e';
}
}
}

Some files were not shown because too many files have changed in this diff Show More