repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
mirrored_repositories/rupiah/lib/view/components
|
mirrored_repositories/rupiah/lib/view/components/color_picker/colors.dart
|
import 'package:flutter/material.dart';
const List<ColorSwatch> materialColors = <ColorSwatch>[
Colors.red,
Colors.pink,
Colors.purple,
Colors.deepPurple,
Colors.indigo,
Colors.blue,
Colors.lightBlue,
Colors.cyan,
Colors.teal,
Colors.green,
Colors.lightGreen,
Colors.lime,
Colors.yellow,
Colors.amber,
Colors.orange,
Colors.deepOrange,
Colors.brown,
Colors.grey,
Colors.blueGrey
];
const List<ColorSwatch> accentColors = <ColorSwatch>[
Colors.redAccent,
Colors.pinkAccent,
Colors.purpleAccent,
Colors.deepPurpleAccent,
Colors.indigoAccent,
Colors.blueAccent,
Colors.lightBlueAccent,
Colors.cyanAccent,
Colors.tealAccent,
Colors.greenAccent,
Colors.lightGreenAccent,
Colors.limeAccent,
Colors.yellowAccent,
Colors.amberAccent,
Colors.orangeAccent,
Colors.deepOrangeAccent,
];
const List<ColorSwatch> fullMaterialColors = <ColorSwatch>[
Colors.red,
Colors.redAccent,
Colors.pink,
Colors.pinkAccent,
Colors.purple,
Colors.purpleAccent,
Colors.deepPurple,
Colors.deepPurpleAccent,
Colors.indigo,
Colors.indigoAccent,
Colors.blue,
Colors.blueAccent,
Colors.lightBlue,
Colors.lightBlueAccent,
Colors.cyan,
Colors.cyanAccent,
Colors.teal,
Colors.tealAccent,
Colors.green,
Colors.greenAccent,
Colors.lightGreen,
Colors.lightGreenAccent,
Colors.lime,
Colors.limeAccent,
Colors.yellow,
Colors.yellowAccent,
Colors.amber,
Colors.amberAccent,
Colors.orange,
Colors.orangeAccent,
Colors.deepOrange,
Colors.deepOrangeAccent,
Colors.brown,
Colors.grey,
Colors.blueGrey
];
| 0
|
mirrored_repositories/rupiah/lib/view
|
mirrored_repositories/rupiah/lib/view/dashboard/dashboard.dart
|
import 'package:expense_kit/utils/ui_extensions.dart';
import 'package:expense_kit/view/emi/loan_card.dart';
import 'package:expense_kit/view/expense/balance_card.dart';
import 'package:expense_kit/view/savings/savings_details.dart';
import 'package:expense_kit/view_model/dashboard/dashboard_cubit.dart';
import 'package:expense_kit/view_model/mutual_fund/mf_login/mf_login_cubit.dart';
import 'package:expense_kit/view_model/emi/emi_list_state.dart';
import 'package:expense_kit/view_model/state_vm.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class Dashboard extends StatefulWidget {
const Dashboard({super.key});
@override
StateModel<Dashboard, DashboardCubit> createState() => _DashboardState();
}
class _DashboardState extends StateModel<Dashboard, DashboardCubit> {
@override
void initView(DashboardCubit cubit) {
cubit.expense();
// init mf login cubit
context.read<MfLoginCubit>().init();
super.initView(cubit);
}
@override
Widget buildMobile(BuildContext context, DashboardCubit cubit) {
return Scaffold(
body: ListView(
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16.0,
vertical: 8,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text("MY ASSETS"),
const SizedBox(
height: 8,
),
Consumer(
// 2. specify the builder and obtain a WidgetRef
builder: (_, WidgetRef ref, __) {
// 3. use ref.watch() to get the value of the provider
final provider = ref.read(emiListProvider.notifier);
return Text(
(cubit.balance - provider.pending()).toCurrency(),
style: const TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
),
);
},
),
],
),
),
const BalanceCard(),
const LoanCard(),
const SavingsDetails(),
],
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view
|
mirrored_repositories/rupiah/lib/view/expense/add_expense.dart
|
import 'package:currency_text_input_formatter/currency_text_input_formatter.dart';
import 'package:expense_kit/model/entity/expense_entity.dart';
import 'package:expense_kit/utils/currency_utils.dart';
import 'package:expense_kit/utils/ui_extensions.dart';
import 'package:expense_kit/view/account/add_account.dart';
import 'package:expense_kit/view/category/add_category.dart';
import 'package:expense_kit/view/components/add_button.dart';
import 'package:expense_kit/view/components/custom_icon.dart';
import 'package:expense_kit/view/decorations.dart';
import 'package:expense_kit/view_model/account/account_list_state.dart';
import 'package:expense_kit/view_model/category/category_cubit.dart';
import 'package:expense_kit/view_model/create_expense.dart';
import 'package:expense_kit/view_model/expense_viewmodel.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
class AddExpense extends ConsumerStatefulWidget {
static const route = '/add-expense';
final ExpenseEntity? expenseEntity;
const AddExpense({super.key, this.expenseEntity});
@override
ConsumerState<AddExpense> createState() => _AddExpenseState();
}
class _AddExpenseState extends ConsumerState<AddExpense> {
TextEditingController dateController = TextEditingController();
TextEditingController descriptionController = TextEditingController();
TextEditingController amountController = TextEditingController();
final CurrencyTextInputFormatter formatter = CurrencyTextInputFormatter(
symbol: '${CurrencyUtils.currencySymbol} ',
locale: 'en_IN',
);
DateFormat dateFormat = DateFormat('dd MMM, yy h:mm aa');
@override
void initState() {
super.initState();
ref.read(accountListState.notifier).getAll();
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
if (widget.expenseEntity != null) {
ref.invalidate(createExpense);
ref.read(createExpense.notifier).updateExpense(widget.expenseEntity!);
dateController.text = dateFormat.format(
widget.expenseEntity!.dateTime!,
);
descriptionController.text = widget.expenseEntity!.description ?? '';
amountController.text = formatter.formatDouble(
widget.expenseEntity!.amount * 100,
);
}
});
}
@override
Widget build(BuildContext context) {
ExpenseEntity expense = ref.watch(createExpense);
return Scaffold(
appBar: AppBar(
title: const Text('Add Expense'),
),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
child: SafeArea(
child: ListView(
children: [
DropdownButtonFormField(
decoration: textDecoration.copyWith(
labelText: 'Expense Type',
labelStyle: context.titleLarge(),
),
style: context.body(),
isExpanded: true,
value: expense.type,
onChanged: (value) {
ref.read(createExpense.notifier).updateExpense(
expense.copyWith(
type: value as ExpenseType,
),
);
},
items: ExpenseType.values
.map(
(e) => DropdownMenuItem(
value: e,
child: Text(
e.name.toUpperCase(),
style: context.body(),
),
),
)
.toList(),
),
const SizedBox(height: 32),
TextField(
controller: amountController,
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
style: context.titleMedium(),
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
formatter,
],
decoration: textDecoration.copyWith(
labelText: 'Amount',
hintText: '$currencySymbol 0.00',
labelStyle: context.titleLarge(),
),
onChanged: (value) {
ref.read(createExpense.notifier).amount(
formatter.getUnformattedValue().toDouble(),
);
},
),
const SizedBox(height: 32),
TextField(
controller: dateController,
onTap: () => _showDialog(
CupertinoDatePicker(
initialDateTime: DateTime.now(),
mode: CupertinoDatePickerMode.dateAndTime,
use24hFormat: true,
// This shows day of week alongside day of month
showDayOfWeek: true,
// This is called when the user changes the date.
onDateTimeChanged: (DateTime newDate) {
dateController.text = dateFormat.format(
newDate,
);
ref.read(createExpense.notifier).updateExpense(
expense.copyWith(dateTime: newDate),
);
},
),
),
style: context.titleMedium(),
readOnly: true,
decoration: textDecoration.copyWith(
labelText: 'Date & Time',
hintText: DateFormat('dd MMM, yy h:mm aa').format(
DateTime.now(),
),
labelStyle: context.titleLarge(),
),
),
const SizedBox(height: 32),
TextField(
controller: descriptionController,
style: context.body(),
decoration: textDecoration.copyWith(
labelText: 'Description',
hintText: 'Optional',
labelStyle: context.titleLarge(),
),
onChanged: (value) {
ref.read(createExpense.notifier).updateExpense(
expense.copyWith(
description: value,
),
);
}),
const SizedBox(height: 16),
Text(
'Account',
style: context.body(),
),
SizedBox(
height: 75,
child: ListView(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
children: [
AddButton(
onTap: () => context.push(AddAccount.route),
width: 75,
height: 75,
),
...ref.watch(accountListState).map((entity) {
return InkWell(
onTap: () {
ref
.read(createExpense.notifier)
.updateExpense(expense.copyWith(
accountId: entity.id,
));
},
child: Container(
constraints: const BoxConstraints(
minWidth: 125,
maxWidth: 200,
),
height: 75,
child: Card(
shape: RoundedRectangleBorder(
side: BorderSide(
color: expense.accountId == entity.id
? Theme.of(context).colorScheme.primary
: Theme.of(context)
.colorScheme
.surfaceVariant,
),
borderRadius: const BorderRadius.all(
Radius.circular(4),
),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(entity.accountName ?? ''),
Row(
children: [
Expanded(
child: Text(
entity.description ?? '',
style: context.boldBody(),
),
),
Container(
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(
2,
),
),
padding: const EdgeInsets.symmetric(
vertical: 1,
horizontal: 4,
),
child: Text(
entity.accountType.name.capitalize(),
style: context.smaller()?.copyWith(
color: Colors.white,
),
),
)
],
),
],
),
),
),
),
);
})
],
),
),
const SizedBox(height: 16),
Text(
'Category',
style: context.body(),
),
BlocBuilder<CategoryCubit, CategoryState>(
builder: (context, state) {
return Wrap(
children: [
AddButton(
horizontal: true,
onTap: () {
showModalBottomSheet(
isScrollControlled: true,
context: context,
builder: (context) => const AddCategory(),
);
},
width: 75,
height: null,
),
...context
.read<CategoryCubit>()
.list
.map(
(e) => Padding(
padding:
const EdgeInsets.symmetric(horizontal: 4),
child: InkWell(
onTap: () {
ref
.read(createExpense.notifier)
.updateExpense(expense.copyWith(
categoryId: e.id,
));
},
child: Chip(
side: BorderSide(
color: expense.categoryId == e.id
? Theme.of(context).colorScheme.primary
: Theme.of(context)
.colorScheme
.surfaceVariant,
),
avatar: CustomIcon(
iconCode: e.iconCode,
),
label: Text(e.name),
elevation: 4,
),
),
),
)
.toList()
],
);
},
),
],
),
),
),
bottomNavigationBar: BottomAppBar(
child: SafeArea(
child: Row(
children: [
Expanded(
child: TextButton(
onPressed: () {
ref.invalidate(createExpense);
context.pop();
},
child: const Text('Cancel'),
),
),
Expanded(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
elevation: 4,
),
onPressed: expense.amount > 0 && expense.accountId != null
? () {
if (widget.expenseEntity == null) {
ref
..read(expenseProvider.notifier).add(expense)
..invalidate(createExpense);
} else {
ref
..read(expenseProvider.notifier).update(expense)
..invalidate(createExpense);
}
context.pop();
}
: null,
child: widget.expenseEntity == null
? const Text('Add Expense')
: const Text('Update Expense'),
),
),
],
),
),
),
);
}
void _showDialog(Widget child) {
showCupertinoModalPopup<void>(
context: context,
builder: (BuildContext context) => Container(
height: 216,
padding: const EdgeInsets.only(top: 6.0),
// The Bottom margin is provided to align the popup above the system
// navigation bar.
margin: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
),
// Provide a background color for the popup.
color: CupertinoColors.systemBackground.resolveFrom(context),
// Use a SafeArea widget to avoid system overlaps.
child: SafeArea(
top: false,
child: child,
),
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view
|
mirrored_repositories/rupiah/lib/view/expense/expense_list.dart
|
import 'package:collection/collection.dart';
import 'package:currency_text_input_formatter/currency_text_input_formatter.dart';
import 'package:expense_kit/model/entity/category_entiry.dart';
import 'package:expense_kit/model/entity/expense_entity.dart';
import 'package:expense_kit/utils/currency_utils.dart';
import 'package:expense_kit/utils/ui_extensions.dart';
import 'package:expense_kit/view/components/custom_icon.dart';
import 'package:expense_kit/view/expense/add_expense.dart';
import 'package:expense_kit/view_model/category/category_cubit.dart';
import 'package:expense_kit/view_model/expense_viewmodel.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
class ExpenseList extends ConsumerStatefulWidget {
const ExpenseList({super.key});
@override
ConsumerState<ExpenseList> createState() => _ExpenseListState();
}
class _ExpenseListState extends ConsumerState<ExpenseList> {
String format = 'MMM, yyyy';
final CurrencyTextInputFormatter formatter = CurrencyTextInputFormatter(
symbol: '$currencySymbol ',
locale: 'en_IN',
decimalDigits: 2,
);
@override
void initState() {
super.initState();
ref.read(expenseProvider.notifier).getAll();
}
@override
Widget build(BuildContext context) {
Set dates = ref
.watch(expenseProvider)
.map((e) => DateFormat(format).format(e.dateTime!))
.toSet();
if (kDebugMode) {
print(dates);
}
Map<String, List<ExpenseEntity>> dateMap = {};
for (var element in dates) {
dateMap[element] = ref
.watch(expenseProvider)
.where((e) => DateFormat(format).format(e.dateTime!) == element)
.toList()
.reversed
.toList();
}
var items = dateMap.entries.toList().reversed;
List<CategoryEntity> categories = context.read<CategoryCubit>().list;
return ListView.builder(
padding: EdgeInsets.zero,
itemCount: dateMap.length,
itemBuilder: (context, index) {
MapEntry<String, List<ExpenseEntity>> expenseMap = items.elementAt(
index,
);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
decoration: const BoxDecoration(
color: Colors.black12,
borderRadius: BorderRadius.only(
topRight: Radius.circular(4),
bottomRight: Radius.circular(4),
),
),
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 4,
),
child: Text(
expenseMap.key,
style: context.titleMedium(),
),
),
ListView.builder(
padding: EdgeInsets.zero,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: expenseMap.value.length,
itemBuilder: (context, index) {
final expense = expenseMap.value[index];
CategoryEntity? category = categories.firstWhereOrNull(
(element) => element.id == expense.categoryId,
);
return ListTile(
dense: true,
onTap: () {},
onLongPress: () {
showCupertinoModalPopup(
context: context,
builder: (context) => CupertinoActionSheet(
actions: [
CupertinoActionSheet(
title: Text(
formatter.formatDouble(expense.amount),
),
message: const Text(
'Deletion is a permanent action.',
),
),
CupertinoActionSheetAction(
onPressed: () {
HapticFeedback.lightImpact();
context
..push(AddExpense.route, extra: expense)
..pop();
},
child: const Text('Edit'),
),
CupertinoActionSheetAction(
onPressed: () {
ref.read(expenseProvider.notifier).removeExpense(
expense,
);
Navigator.pop(context);
HapticFeedback.heavyImpact();
},
isDestructiveAction: true,
child: const Text('Delete'),
),
],
cancelButton: CupertinoActionSheetAction(
onPressed: () {
HapticFeedback.lightImpact();
Navigator.pop(context);
},
child: const Text('Cancel'),
),
),
);
HapticFeedback.mediumImpact();
},
title: Row(
children: [
Expanded(
child: Text(
expense.description?.toString() ?? expense.type.name,
style: context.titleSmall(),
),
),
Expanded(
child: Text(
formatter.formatDouble(expense.amount),
textAlign: TextAlign.end,
style: context.titleMedium(),
),
),
],
),
subtitle: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
expense.formattedDate(),
style: context.small(),
),
const SizedBox(width: 8),
if (category != null)
Container(
padding: const EdgeInsets.only(
right: 8,
top: 2,
bottom: 2,
left: 4,
),
decoration: BoxDecoration(
color: category.colorCode == null
? Colors.white24
: Color(int.parse(category.colorCode!)),
borderRadius: BorderRadius.circular(4),
),
child: Row(
children: [
CustomIcon(
iconCode: category.iconCode,
size: 14,
),
const SizedBox(width: 8),
Text(
category.name,
style: context.small(),
),
],
),
),
],
),
leading: Container(
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: expense.type == ExpenseType.income
? Colors.green
: Colors.red,
),
child: const Icon(
Icons.currency_rupee,
color: Colors.white,
size: 14,
),
),
);
},
),
],
);
},
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view
|
mirrored_repositories/rupiah/lib/view/expense/expense_view.dart
|
import 'package:drift_db_viewer/drift_db_viewer.dart';
import 'package:expense_kit/model/database/database.dart';
import 'package:expense_kit/utils/currency_utils.dart';
import 'package:expense_kit/view/expense/add_expense.dart';
import 'package:expense_kit/view/expense/balance_card.dart';
import 'package:expense_kit/view/expense/expense_list.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class ExpenseView extends StatelessWidget {
const ExpenseView({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('$currencySymbol Rupiah'),
actions: [
IconButton(
onPressed: () {},
icon: const Icon(Icons.feedback_outlined),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
context.push(AddExpense.route);
},
child: const Icon(Icons.add),
),
body: Column(
children: [
InkWell(
child: const BalanceCard(),
onTap: () {
//This should be a singleton
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => DriftDbViewer(database),
),
);
},
),
const Expanded(
child: ExpenseList(),
),
],
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view
|
mirrored_repositories/rupiah/lib/view/expense/balance_card.dart
|
import 'package:currency_text_input_formatter/currency_text_input_formatter.dart';
import 'package:expense_kit/model/entity/expense_card_entity.dart';
import 'package:expense_kit/utils/currency_utils.dart';
import 'package:expense_kit/utils/ui_extensions.dart';
import 'package:expense_kit/view_model/expense_card_state.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final CurrencyTextInputFormatter formatter = CurrencyTextInputFormatter(
symbol: '$currencySymbol ',
locale: 'en_IN',
decimalDigits: 2,
);
class BalanceCard extends ConsumerWidget {
const BalanceCard({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final ExpenseCardEntity value = ref.watch(expenseCardState);
return Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
child: Container(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'ACCOUNTS BALANCE',
),
const SizedBox(height: 4),
Text(
formatter.formatDouble(value.totalBalance),
style: context.titleLarge(),
),
],
),
const SizedBox(height: 16),
const Row(
children: [
Expanded(
child: Row(
children: [
Text(
'Income',
),
SizedBox(width: 16),
Icon(
Icons.trending_up,
color: Colors.green,
)
],
),
),
Expanded(
child: Row(
children: [
Text(
'Expense',
),
SizedBox(width: 16),
Icon(
Icons.trending_down,
color: Colors.red,
)
],
),
),
],
),
Row(
children: [
Expanded(
child: Text(
'+ ${formatter.formatDouble(value.income)}',
style: context.titleMedium(),
),
),
Expanded(
child: Text(
'- ${formatter.formatDouble(value.expense)}',
style: context.titleMedium(),
),
),
],
),
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view
|
mirrored_repositories/rupiah/lib/view/account/add_account.dart
|
import 'package:expense_kit/model/database/tables/account.dart';
import 'package:expense_kit/model/entity/account_entity.dart';
import 'package:expense_kit/utils/currency_utils.dart';
import 'package:expense_kit/utils/ui_extensions.dart';
import 'package:expense_kit/view/decorations.dart';
import 'package:expense_kit/view_model/account/create_account_state.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
class AddAccount extends ConsumerStatefulWidget {
static const route = '/add-account';
const AddAccount({super.key});
@override
ConsumerState<AddAccount> createState() => _AddAccountState();
}
class _AddAccountState extends ConsumerState<AddAccount> {
@override
Widget build(BuildContext context) {
var uiState = ref.read(createAccountState.notifier);
AccountEntity entity = ref.watch(createAccountState);
return Scaffold(
appBar: AppBar(
title: const Text('Add Account'),
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: SegmentedButton<AccountType>(
showSelectedIcon: false,
style: ButtonStyle(
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(32),
),
),
),
segments: const [
ButtonSegment<AccountType>(
value: AccountType.savings,
label: Text('Savings '),
),
ButtonSegment<AccountType>(
value: AccountType.credit,
label: Text('Credit Card'),
),
ButtonSegment<AccountType>(
value: AccountType.loan,
label: Text('Loan '),
),
],
selected: <AccountType>{entity.accountType},
onSelectionChanged: (Set<AccountType> newSelection) {
uiState.updateAccount(entity.copyWith(
accountType: newSelection.first,
));
},
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
child: SafeArea(
child: ListView(
shrinkWrap: true,
children: [
const SizedBox(height: 32),
TextField(
textCapitalization: TextCapitalization.words,
style: context.titleMedium(),
decoration: textDecoration.copyWith(
labelText: 'Account Holder Name',
labelStyle: context.titleLarge(),
),
onChanged: (value) {
uiState.updateAccount(entity.copyWith(
description: value,
));
},
),
const SizedBox(height: 32),
TextField(
textCapitalization: TextCapitalization.words,
style: context.titleMedium(),
decoration: textDecoration.copyWith(
labelText: 'Account Name',
labelStyle: context.titleLarge(),
),
onChanged: (value) {
uiState.updateAccount(entity.copyWith(
accountName: value,
));
},
),
const SizedBox(height: 32),
TextField(
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
style: context.titleMedium(),
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
formatter,
],
decoration: textDecoration.copyWith(
labelText: 'Account Balance',
hintText: '$currencySymbol 0.00',
labelStyle: context.titleLarge(),
),
onChanged: (value) {
uiState.updateAccount(entity.copyWith(
balance: formatter.getUnformattedValue().toDouble(),
));
},
),
],
),
),
),
],
),
bottomNavigationBar: BottomAppBar(
child: SafeArea(
child: Row(
children: [
Expanded(
child: TextButton(
onPressed: () {
ref.invalidate(createAccountState);
context.pop();
},
child: const Text('Cancel'),
),
),
Expanded(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
elevation: 4,
),
onPressed:
entity.accountName != null && entity.description != null
? () {
ref
..read(createAccountState.notifier)
.addAccount(entity)
..invalidate(createAccountState);
context.pop();
}
: null,
child: const Text('Add Account'),
),
),
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view
|
mirrored_repositories/rupiah/lib/view/account/account_list.dart
|
import 'package:expense_kit/model/entity/account_entity.dart';
import 'package:expense_kit/view/account/add_account.dart';
import 'package:expense_kit/view/account/components/account_card.dart';
import 'package:expense_kit/view_model/account/account_list_state.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
class AccountsList extends ConsumerStatefulWidget {
static const route = '/accounts';
const AccountsList({super.key});
@override
ConsumerState<AccountsList> createState() => _AccountsListState();
}
class _AccountsListState extends ConsumerState<AccountsList> {
@override
void initState() {
super.initState();
ref.read(accountListState.notifier).getAll();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Accounts'),
),
floatingActionButton: FloatingActionButton(
onPressed: () => context.push(AddAccount.route),
child: const Icon(Icons.add),
),
body: ListView.builder(
itemCount: ref.watch(accountListState).length,
itemBuilder: (context, index) {
AccountEntity entity = ref.watch(accountListState)[index];
return InkWell(
onLongPress: () {
ref.read(accountListState.notifier).delete(entity);
},
child: AccountCard(
entity: entity,
),
);
},
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view
|
mirrored_repositories/rupiah/lib/view/account/account_view.dart
|
import 'package:expense_kit/model/database/database.dart';
import 'package:expense_kit/view/account/account_list.dart';
import 'package:expense_kit/view/category/category_list.dart';
import 'package:expense_kit/view_model/settings/settings_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
class AccountView extends StatefulWidget {
const AccountView({super.key});
@override
State<AccountView> createState() => _AccountViewState();
}
class _AccountViewState extends State<AccountView> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Account'),
),
body: ListView(
children: [
// ListTile(
// leading: Container(
// padding: const EdgeInsets.all(8),
// decoration: const BoxDecoration(
// shape: BoxShape.circle,
// color: Colors.deepOrange,
// ),
// child: const Icon(
// Icons.login_outlined,
// color: Colors.white,
// size: 16,
// ),
// ),
// title: const Text('Login/SignUp'),
// subtitle: const Text(
// 'Login or Sign up to keep the data sync between devices',
// ),
// onTap: () => showModalBottomSheet(
// isDismissible: false,
// enableDrag: false,
// isScrollControlled: true,
// context: context,
// builder: (context) => const AuthSheet(),
// ),
// ),
ListTile(
leading: Container(
padding: const EdgeInsets.all(8),
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.green,
),
child: const Icon(
Icons.account_balance_wallet_outlined,
color: Colors.white,
size: 16,
),
),
title: const Text('Bank Accounts'),
subtitle: const Text('add or remove bank account'),
onTap: () => context.push(AccountsList.route),
),
ListTile(
title: const Text('Credit Cards'),
leading: Container(
padding: const EdgeInsets.all(8),
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.red,
),
child: const Icon(
Icons.credit_card_outlined,
color: Colors.white,
size: 16,
),
),
subtitle: const Text('add or remove Credit Card'),
onTap: () {},
),
ListTile(
title: const Text('Loan Accounts'),
leading: Container(
padding: const EdgeInsets.all(8),
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.blue,
),
child: const Icon(
Icons.real_estate_agent_outlined,
color: Colors.white,
size: 16,
),
),
subtitle: const Text('add or remove Loan account'),
onTap: () {},
),
ListTile(
title: const Text('Categories'),
leading: Container(
padding: const EdgeInsets.all(8),
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.purple,
),
child: const Icon(
Icons.category_outlined,
color: Colors.white,
size: 16,
),
),
subtitle: const Text('add or remove categories'),
onTap: () => context.push(CategoryList.route),
),
const Padding(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Text('Others'),
),
ListTile(
title: const Text('Settings'),
leading: Container(
padding: const EdgeInsets.all(8),
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.brown,
),
child: const Icon(
Icons.settings_outlined,
color: Colors.white,
size: 16,
),
),
onTap: () {},
),
BlocBuilder<SettingsCubit, SettingsState>(
builder: (context, state) {
var cubit = context.read<SettingsCubit>();
bool dark = cubit.brightness == Brightness.dark;
return ListTile(
title: const Text('Dark Theme'),
subtitle: const Text('Switch between light and dark theme'),
leading: Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: dark ? Colors.white : Colors.black,
),
child: Icon(
dark ? Icons.dark_mode : Icons.light_mode,
color: !dark ? Colors.white : Colors.black,
size: 16,
),
),
trailing: Switch(
value: dark,
onChanged: (value) {
cubit.changeBrightness();
},
),
);
},
),
ListTile(
title: const Text('Export Data'),
leading: Container(
padding: const EdgeInsets.all(8),
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.black,
),
child: const Icon(
Icons.import_export_outlined,
color: Colors.white,
size: 16,
),
),
onTap: () {},
),
ListTile(
title: const Text('Reset Expense Table'),
leading: Container(
padding: const EdgeInsets.all(8),
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.black,
),
child: const Icon(
Icons.lock_reset_outlined,
color: Colors.deepOrange,
size: 16,
),
),
onLongPress: () {
database.delete(database.expense).go();
},
),
],
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view/account
|
mirrored_repositories/rupiah/lib/view/account/components/account_card.dart
|
import 'package:expense_kit/model/database/tables/account.dart';
import 'package:expense_kit/model/entity/account_entity.dart';
import 'package:expense_kit/utils/currency_utils.dart';
import 'package:expense_kit/utils/ui_extensions.dart';
import 'package:flutter/material.dart';
class AccountCard extends StatefulWidget {
final AccountEntity entity;
const AccountCard({super.key, required this.entity});
@override
State<AccountCard> createState() => _AccountCardState();
}
class _AccountCardState extends State<AccountCard> {
bool selected = false;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.entity.description ?? '',
style: context.boldBody(),
),
Text(
widget.entity.accountName ?? '',
style: context.body(),
),
],
),
const Icon(
Icons.savings_outlined,
)
],
),
],
),
),
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: widget.entity.accountType == AccountType.savings
? Colors.blue.withOpacity(0.50)
: Colors.grey.withOpacity(0.25),
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(8),
bottomRight: Radius.circular(8),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(
height: 4,
),
Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Balance',
style: context.small(),
),
Text(
widget.entity.balance?.toCurrency() ?? 'NA',
style: context.boldBody(),
),
],
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Expense',
style: context.small(),
),
Text(
formatter.formatDouble(0),
style: context.boldBody(),
),
],
),
),
],
)
],
),
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view
|
mirrored_repositories/rupiah/lib/view/category/add_category.dart
|
import 'package:expense_kit/utils/ui_extensions.dart';
import 'package:expense_kit/view/components/color_picker/color_picker.dart';
import 'package:expense_kit/view/components/custom_icon.dart';
import 'package:expense_kit/view/components/icon_picker.dart';
import 'package:expense_kit/view/decorations.dart';
import 'package:expense_kit/view_model/category/category_cubit.dart';
import 'package:expense_kit/view_model/state_vm.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class AddCategory extends StatefulWidget {
static const route = '/add_category';
const AddCategory({super.key});
@override
StateModel<AddCategory, CategoryCubit> createState() => _AddCategoryState();
}
class _AddCategoryState extends StateModel<AddCategory, CategoryCubit> {
@override
void initView(CategoryCubit cubit) {
super.initView(cubit);
cubit.reset();
}
@override
Widget buildMobile(BuildContext context, CategoryCubit cubit) {
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 16,
),
child: SafeArea(
child: ListView(
shrinkWrap: true,
children: [
Text(
'Create Category',
style: context.titleMedium(),
),
const SizedBox(height: 8),
const Divider(),
const SizedBox(height: 32),
TextField(
style: context.titleMedium(),
decoration: textDecoration.copyWith(
labelText: 'Category Name',
hintText: 'Enter Category Name',
labelStyle: context.titleLarge(),
),
onChanged: cubit.nameUpdate,
),
const SizedBox(height: 32),
TextField(
style: context.titleMedium(),
decoration: textDecoration.copyWith(
labelText: 'Description',
hintText: 'Description here',
labelStyle: context.titleLarge(),
),
onChanged: cubit.descriptionUpdate,
),
const SizedBox(height: 32),
Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Category Icon'),
const SizedBox(height: 8),
Align(
alignment: Alignment.centerLeft,
child: IconButton.filledTonal(
onPressed: () => showModalBottomSheet(
context: context,
builder: (context) => IconPicker(
onSelect: (String value) {
cubit.iconUpdate(value);
},
),
),
icon: CustomIcon(
iconCode: cubit.companion.iconCode.value != null
? cubit.companion.iconCode.value!
: '983323',
),
),
),
],
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Category Color'),
const SizedBox(height: 8),
Align(
alignment: Alignment.centerLeft,
child: IconButton.filledTonal(
onPressed: () => showModalBottomSheet(
context: context,
builder: (context) => ColorPicker(
onSelect: (String value) {
cubit.colorUpdate(value);
},
),
),
icon: Container(
decoration: BoxDecoration(
color: cubit.companion.colorCode.value == null
? Colors.green
: Color(
int.parse(
cubit.companion.colorCode.value!),
),
borderRadius: BorderRadius.circular(32),
),
width: 24,
height: 24,
),
),
),
],
),
),
],
),
const SizedBox(height: 32),
Row(
children: [
Expanded(
child: TextButton(
onPressed: () {
context.pop();
cubit.reset();
},
child: const Text('Cancel'),
),
),
Expanded(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
elevation: 4,
),
onPressed: cubit.valid
? () {
context.pop();
cubit.create();
}
: null,
child: const Text('Create Category'),
),
),
],
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view
|
mirrored_repositories/rupiah/lib/view/category/category_list.dart
|
import 'package:expense_kit/model/entity/category_entiry.dart';
import 'package:expense_kit/view/category/add_category.dart';
import 'package:expense_kit/view/components/custom_icon.dart';
import 'package:expense_kit/view_model/category/category_cubit.dart';
import 'package:expense_kit/view_model/state_vm.dart';
import 'package:flutter/material.dart';
class CategoryList extends StatefulWidget {
static const route = '/category-list';
const CategoryList({super.key});
@override
StateModel<CategoryList, CategoryCubit> createState() => _CategoryListState();
}
class _CategoryListState extends StateModel<CategoryList, CategoryCubit> {
@override
void initView(CategoryCubit cubit) {
super.initView(cubit);
cubit.get();
}
@override
Widget buildMobile(BuildContext context, CategoryCubit cubit) {
return Scaffold(
appBar: AppBar(
title: const Text('Categories'),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
showModalBottomSheet(
isScrollControlled: true,
context: context,
builder: (context) => const AddCategory(),
);
},
child: const Icon(Icons.add),
),
body: ListView.builder(
itemCount: cubit.list.length,
itemBuilder: (BuildContext context, int index) {
CategoryEntity entity = cubit.list[index];
return ListTile(
title: Text(entity.name),
leading: Container(
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: Color(int.parse(entity.colorCode ?? '0xFF000000')),
borderRadius: BorderRadius.circular(32),
),
child: CustomIcon(
iconCode: entity.iconCode ?? '983323',
),
),
subtitle: Text(entity.description ?? 'NA'),
);
},
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view
|
mirrored_repositories/rupiah/lib/view/auth/auth_sheet.dart
|
import 'package:expense_kit/utils/ui_extensions.dart';
import 'package:expense_kit/view/components/circular_indicator.dart';
import 'package:expense_kit/view/decorations.dart';
import 'package:expense_kit/view_model/auth/auth_cubit.dart';
import 'package:expense_kit/view_model/state_vm.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:go_router/go_router.dart';
class AuthSheet extends StatefulWidget {
const AuthSheet({super.key});
@override
StateModel<AuthSheet, AuthCubit> createState() => _AuthSheetState();
}
class _AuthSheetState extends StateModel<AuthSheet, AuthCubit> {
@override
void listener(state) {
if (state is AuthSuccess) {
context.pop();
}
super.listener(state);
}
@override
Widget buildMobile(BuildContext context, AuthCubit cubit) {
return Material(
child: SafeArea(
child: Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
left: 16,
right: 16,
top: 16,
),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Login with Phone'),
const SizedBox(
height: 32,
),
if (cubit.otpSent)
TextField(
enabled: cubit.state is! FetchingOTP,
keyboardType: const TextInputType.numberWithOptions(
decimal: false,
),
style: context.titleMedium(),
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
],
decoration: textDecoration.copyWith(
labelText: 'OTP',
labelStyle: context.titleLarge(),
counterText: '',
),
maxLength: 6,
onChanged: (value) {
if (value.length == 6) {
cubit.validateOTP(value);
}
},
)
else
TextField(
enabled: cubit.state is! FetchingOTP,
keyboardType: const TextInputType.numberWithOptions(
decimal: false,
),
style: context.titleMedium(),
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
],
decoration: textDecoration.copyWith(
labelText: 'Phone Number',
labelStyle: context.titleLarge(),
prefixText: '+ 91 ',
counterText: '',
),
maxLength: 10,
onChanged: (value) {
cubit.phone = value;
},
),
const SizedBox(
height: 32,
),
Row(
children: [
Expanded(
child: TextButton(
onPressed: () {
context.pop();
},
child: const Text('Cancel'),
),
),
if (!cubit.otpSent)
Expanded(
child: cubit.state is FetchingOTP
? const CircularIndicator()
: ElevatedButton(
style: ElevatedButton.styleFrom(
elevation: 4,
),
onPressed: cubit.validNumber()
? () {
context.hideKeyboard();
cubit.fetchOTP();
}
: null,
child: const Text('Get OTP'),
),
)
else
Expanded(
child: cubit.state is ValidatingOTP
? const CircularIndicator()
: ElevatedButton(
style: ElevatedButton.styleFrom(
elevation: 4,
),
onPressed: () {
context.hideKeyboard();
// cubit.validateOTP(otp);
},
child: const Text('Verify OTP'),
),
),
],
),
const SizedBox(
height: 16,
),
],
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view
|
mirrored_repositories/rupiah/lib/view/home/home.dart
|
import 'package:expense_kit/view/account/account_view.dart';
import 'package:expense_kit/view/dashboard/dashboard.dart';
import 'package:expense_kit/view/emi/emi_view.dart';
import 'package:expense_kit/view/expense/expense_view.dart';
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
const Home({super.key});
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
int currentIndex = 0;
Widget view = const Dashboard();
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: view,
bottomNavigationBar: NavigationBar(
selectedIndex: currentIndex,
onDestinationSelected: (index) {
if (index == 0) {
view = const Dashboard();
} else if (index == 1) {
view = const ExpenseView();
} else if (index == 2) {
view = const EMIView();
} else if (index == 3) {
view = const AccountView();
}
setState(() {
currentIndex = index;
});
},
destinations: const [
NavigationDestination(
icon: Icon(Icons.dashboard_outlined),
selectedIcon: Icon(Icons.dashboard),
label: 'Dashboard',
),
NavigationDestination(
icon: Icon(Icons.currency_rupee),
selectedIcon: Icon(Icons.currency_rupee_outlined),
label: 'Expense',
),
NavigationDestination(
icon: Icon(Icons.payments_outlined),
selectedIcon: Icon(Icons.payments),
label: 'Loans',
),
// NavigationDestination(
// icon: Icon(Icons.savings_outlined),
// selectedIcon: Icon(Icons.savings),
// label: 'Savings',
// ),
NavigationDestination(
icon: Icon(Icons.account_box_outlined),
selectedIcon: Icon(Icons.account_box),
label: 'Account',
),
],
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view
|
mirrored_repositories/rupiah/lib/view/savings/savings_details.dart
|
import 'package:expense_kit/utils/currency_utils.dart';
import 'package:expense_kit/utils/ui_extensions.dart';
import 'package:expense_kit/view/savings/savings_list.dart';
import 'package:expense_kit/view_model/savings/savings_cubit.dart';
import 'package:expense_kit/view_model/state_vm.dart';
import 'package:flutter/material.dart';
class SavingsDetails extends StatefulWidget {
const SavingsDetails({super.key});
@override
StateModel<SavingsDetails, SavingsCubit> createState() =>
_SavingsDetailsState();
}
class _SavingsDetailsState extends StateModel<SavingsDetails, SavingsCubit> {
@override
Widget buildMobile(BuildContext context, SavingsCubit cubit) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
child: Container(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'INVESTMENTS',
),
const SizedBox(height: 4),
Text(
cubit.total.toCurrency(),
style: context.titleLarge(),
),
],
),
const SizedBox(height: 16),
const Row(
children: [
Expanded(
child: Row(
children: [
Text(
'Invested',
),
],
),
),
Expanded(
child: Row(
children: [
Expanded(
flex: 2,
child: Text(
'Gain/Loss',
),
),
SizedBox(width: 8),
Expanded(
child: Align(
alignment: Alignment.centerLeft,
child: RotatedBox(
quarterTurns: 3,
child: Icon(
Icons.play_arrow_sharp,
color: Colors.green,
size: 18,
),
),
),
),
],
),
),
],
),
Row(
children: [
Expanded(
child: Text(
formatter.formatDouble(cubit.invested),
style: context.titleMedium(),
),
),
Expanded(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
flex: 2,
child: Text(
formatter.formatDouble(cubit.profit),
style: context.titleMedium(),
),
),
const SizedBox(
width: 8,
),
Expanded(
child: Text(
'${cubit.profitPercentage.toStringAsFixed(1)}%',
style: context.smallBold()?.copyWith(
color: Colors.green,
),
),
),
],
),
),
],
),
const SavingList(),
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view
|
mirrored_repositories/rupiah/lib/view/savings/savings_list.dart
|
import 'package:expense_kit/features/investment/view/add_investment.dart';
import 'package:expense_kit/utils/ui_extensions.dart';
import 'package:expense_kit/view/savings/mf_login/mf_login.dart';
import 'package:expense_kit/view/savings/mutual_fund/mutual_funds_page.dart';
import 'package:expense_kit/view_model/savings/savings_cubit.dart';
import 'package:expense_kit/view_model/state_vm.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class SavingList extends StatefulWidget {
const SavingList({super.key});
@override
StateModel<SavingList, SavingsCubit> createState() => _SavingListState();
}
class _SavingListState extends StateModel<SavingList, SavingsCubit> {
@override
Widget buildMobile(BuildContext context, SavingsCubit cubit) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Divider(),
GridView(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
),
children: [
InkWell(
onTap: () => context.push(MutualFundPage.route),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Image.asset(
'assets/icons/rupee.png',
width: 32,
height: 32,
),
const SizedBox(height: 4),
Text(
'Mutual Funds',
style: context.smaller(),
),
const SizedBox(height: 4),
Text(
cubit.mutualFundBalance.toCurrency(),
style: context.smallBold(),
)
],
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Image.asset(
'assets/icons/trend.png',
width: 32,
height: 32,
),
const SizedBox(height: 4),
Text(
'Stocks',
style: context.smaller(),
),
const SizedBox(height: 4),
Text(
cubit.stockBalance.toCurrency(),
style: context.smallBold(),
)
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Image.asset(
'assets/icons/gold-ingot.png',
width: 32,
height: 32,
),
const SizedBox(height: 4),
Text(
'Gold',
style: context.smaller(),
),
const SizedBox(height: 4),
Text(
cubit.goldBalance.toCurrency(),
style: context.smallBold(),
)
],
),
),
InkWell(
onTap: () {
context.push(MFLogin.route).then((value) => print(value));
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Image.asset(
'assets/icons/epf.png',
width: 32,
height: 32,
),
const SizedBox(height: 4),
Text(
'EPF',
style: context.smaller(),
),
const SizedBox(height: 4),
Text(
cubit.epfBalance.toCurrency(),
style: context.smallBold(),
)
],
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: () => showModalBottomSheet(
isScrollControlled: true,
context: context,
builder: (context) => const AddInvestment(),
),
child: Column(
children: [
Image.asset(
'assets/icons/market.png',
width: 32,
height: 32,
),
const SizedBox(height: 4),
Text(
'Real Estate',
style: context.smaller(),
),
const SizedBox(height: 4),
Text(
cubit.realEstateBalance.toCurrency(),
style: context.smallBold(),
)
],
),
),
),
],
),
],
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view
|
mirrored_repositories/rupiah/lib/view/savings/savings_view.dart
|
import 'package:expense_kit/view/savings/savings_details.dart';
import 'package:expense_kit/view_model/savings/savings_cubit.dart';
import 'package:expense_kit/view_model/state_vm.dart';
import 'package:flutter/material.dart';
class SavingView extends StatefulWidget {
const SavingView({super.key});
@override
StateModel<SavingView, SavingsCubit> createState() => _SavingViewState();
}
class _SavingViewState extends StateModel<SavingView, SavingsCubit> {
@override
Widget buildMobile(BuildContext context, SavingsCubit cubit) {
return Scaffold(
appBar: AppBar(
title: const Text('Savings'),
),
floatingActionButton: FloatingActionButton(
onPressed: () {},
child: const Icon(Icons.add),
),
body: const SingleChildScrollView(
child: Column(
children: [
SavingsDetails(),
],
),
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view/savings
|
mirrored_repositories/rupiah/lib/view/savings/mf_login/mf_login.dart
|
import 'dart:convert';
import 'dart:developer';
import 'package:expense_kit/model/entity/mf_central_login_entiry.dart';
import 'package:expense_kit/view_model/mutual_fund/mf_login/mf_login_cubit.dart';
import 'package:expense_kit/view_model/state_vm.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:go_router/go_router.dart';
class MFLogin extends StatefulWidget {
static const route = '/mf-login';
const MFLogin({super.key});
@override
StateModel<MFLogin, MfLoginCubit> createState() => _MFLoginState();
}
class _MFLoginState extends StateModel<MFLogin, MfLoginCubit> {
InAppWebViewController? webViewController;
@override
Widget buildMobile(BuildContext context, MfLoginCubit cubit) {
return Scaffold(
appBar: AppBar(),
body: InAppWebView(
initialUrlRequest: URLRequest(
url: WebUri("https://app.mfcentral.com/investor/signin"),
),
onWebViewCreated: (controller) {
webViewController = controller;
},
onLoadStop: (controller, url) async {
if (url
.toString()
.contains('https://app.mfcentral.com/portal/home')) {
context.pop();
dynamic data = await webViewController?.webStorage.localStorage
.getItem(key: 'persist:mf-central');
log(data['authReducer']);
cubit.setupCredentials(
MFCentralEntity.fromJson(
jsonDecode(
data['authReducer'],
),
),
);
}
},
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view/savings
|
mirrored_repositories/rupiah/lib/view/savings/mutual_fund/mutual_fund_item.dart
|
import 'package:expense_kit/model/database/database.dart';
import 'package:expense_kit/utils/ui_extensions.dart';
import 'package:flutter/material.dart';
class MutualFundItem extends StatelessWidget {
final MutualFundData fund;
final VoidCallback onTap;
const MutualFundItem({
super.key,
required this.fund,
required this.onTap,
});
@override
Widget build(BuildContext context) {
return InkWell(
onLongPress: onTap,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surface,
borderRadius: BorderRadius.circular(4),
),
child: Column(
children: [
Row(
children: [
// if (fund.logoPath != '')
// ClipRRect(
// borderRadius: BorderRadius.circular(45),
// child: Image.network(
// fund.logoPath,
// width: 24,
// ),
// )
// else
// const SizedBox(
// width: 24,
// height: 24,
// ),
const SizedBox(
width: 16,
),
Expanded(
child: Text(
fund.name ?? '',
style: context.smaller(),
),
)
],
),
const SizedBox(
height: 8,
),
Row(
children: [
Expanded(
child: Text(
'Invested',
style: context.smaller()?.copyWith(
color: Colors.grey,
),
),
),
Expanded(
child: Text(
'Current Value',
style: context.smaller()?.copyWith(
color: Colors.grey,
),
),
),
Expanded(
flex: 2,
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
const SizedBox(
width: 16,
),
Text(
'Gain/Loss',
style: context.smaller()?.copyWith(
color: Colors.grey,
),
),
const SizedBox(
width: 8,
),
const RotatedBox(
quarterTurns: 3,
child: Icon(
Icons.play_arrow_sharp,
size: 14,
color: Colors.green,
),
),
],
),
),
],
),
Row(
children: [
Expanded(
child: Text(
fund.amount.toCurrency(),
style: context.mediumBold(),
),
),
Expanded(
child: Text(
fund.currentValue?.toCurrency() ?? '',
style: context.mediumBold(),
),
),
Expanded(
flex: 2,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(width: 16),
Text(
fund.gainPercentage.toString(),
style: context.mediumBold(),
),
// Text(
// ' ${fund.profitPercent.toStringAsFixed(2)}%',
// style: context.smallerBold()?.copyWith(
// color: Colors.green,
// ),
// ),
],
),
),
],
)
],
),
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view/savings
|
mirrored_repositories/rupiah/lib/view/savings/mutual_fund/create_fund.dart
|
import 'package:expense_kit/model/database/tables/mutual_fund.dart';
import 'package:expense_kit/model/entity/scheme_entity.dart';
import 'package:expense_kit/utils/currency_utils.dart';
import 'package:expense_kit/utils/ui_extensions.dart';
import 'package:expense_kit/view/decorations.dart';
import 'package:expense_kit/view/savings/mutual_fund/fund_search.dart';
import 'package:expense_kit/view_model/mutual_fund/create/create_mf_cubit.dart';
import 'package:expense_kit/view_model/state_vm.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:go_router/go_router.dart';
class CreateFund extends StatefulWidget {
static const route = '/create-fund';
const CreateFund({super.key});
@override
StateModel<CreateFund, CreateMfCubit> createState() => _CreateFundState();
}
class _CreateFundState extends StateModel<CreateFund, CreateMfCubit> {
TextEditingController fundController = TextEditingController();
@override
Widget buildMobile(BuildContext context, CreateMfCubit cubit) {
return Scaffold(
appBar: AppBar(
title: const Text('Create Fund'),
),
body: SafeArea(
child: GestureDetector(
onTap: () {
FocusScope.of(context).unfocus();
},
child: Padding(
padding: const EdgeInsets.all(16.0),
child: ListView(
children: [
TextField(
controller: fundController,
onTap: () {
showModalBottomSheet(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
backgroundColor: Colors.white,
context: context,
builder: (BuildContext context) {
return FundSearch(
onSelect: (Scheme value) {
cubit.scheme = value;
fundController.text = value.schemeName;
cubit.fundDetails();
},
);
},
);
},
readOnly: true,
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
style: context.titleMedium(),
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
formatter,
],
decoration: textDecoration.copyWith(
labelText: 'Fund',
hintText: 'Search Fund',
labelStyle: context.titleLarge(),
),
onChanged: (value) {},
),
const SizedBox(height: 16),
if (cubit.fund != null)
Column(
children: [
Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
const Text('Fund Details'),
const Divider(),
const SizedBox(
height: 8,
),
// Row(
// children: [
// const Expanded(child: Text('Month/Year')),
// Expanded(
// child: Text(
// DateFormat('MMM, yyyy').format(
// date!,
// ),
// style: context.boldBody(),
// ),
// ),
// ],
// ),
const SizedBox(
height: 8,
),
Row(
children: [
const Expanded(child: Text('NAV')),
Expanded(
child: Text(
cubit.fund?.currentNav.toCurrency() ??
'NA',
style: context.boldBody(),
),
),
],
),
const SizedBox(
height: 16,
),
Row(
children: [
const Expanded(child: Text('Fund House')),
Expanded(
child: Text(
cubit.fund?.meta.fundHouse ?? 'NA',
style: context.boldBody(),
),
),
],
),
],
),
),
),
const SizedBox(height: 16),
],
),
SegmentedButton<MFType>(
showSelectedIcon: false,
style: ButtonStyle(
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4),
),
),
),
segments: const [
ButtonSegment<MFType>(
value: MFType.sip,
label: Text('SIP'),
),
ButtonSegment<MFType>(
value: MFType.lumpSum,
label: Text('Lump sum'),
),
],
selected: <MFType>{cubit.type},
onSelectionChanged: (Set<MFType> newSelection) {
cubit.type = newSelection.first;
},
),
const SizedBox(height: 32),
TextField(
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
style: context.titleMedium(),
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
formatter,
],
decoration: textDecoration.copyWith(
labelText: 'Invested Amount',
hintText: '$currencySymbol 0.00',
labelStyle: context.titleLarge(),
),
onChanged: (value) {
cubit.amount = formatter.getUnformattedValue();
},
),
const SizedBox(height: 32),
TextField(
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
style: context.titleMedium(),
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
formatter,
],
decoration: textDecoration.copyWith(
labelText: 'Current Value',
hintText: '$currencySymbol 0.00',
labelStyle: context.titleLarge(),
),
onChanged: (value) {
cubit.currentValue = formatter.getUnformattedValue();
},
),
],
),
),
),
),
bottomNavigationBar: BottomAppBar(
child: SafeArea(
child: Row(
children: [
Expanded(
child: TextButton(
onPressed: () {
context.pop();
},
child: const Text('Cancel'),
),
),
Expanded(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
elevation: 4,
),
onPressed: cubit.isValid
? () {
context.pop();
cubit.insert();
}
: null,
child: const Text('Add Fund'),
),
),
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view/savings
|
mirrored_repositories/rupiah/lib/view/savings/mutual_fund/mutual_funds_page.dart
|
import 'package:expense_kit/view/savings/mutual_fund/create_fund.dart';
import 'package:expense_kit/view/savings/mutual_fund/mutual_fund_item.dart';
import 'package:expense_kit/view_model/savings/savings_cubit.dart';
import 'package:expense_kit/view_model/state_vm.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class MutualFundPage extends StatefulWidget {
static const route = '/mutual-fund';
const MutualFundPage({super.key});
@override
StateModel<MutualFundPage, SavingsCubit> createState() =>
_MutualFundPageState();
}
class _MutualFundPageState extends StateModel<MutualFundPage, SavingsCubit> {
@override
Widget buildMobile(BuildContext context, SavingsCubit cubit) {
return Scaffold(
appBar: AppBar(
title: const Text('Mutual Funds'),
),
floatingActionButton: FloatingActionButton(
onPressed: () => context.push(CreateFund.route),
child: const Icon(Icons.add),
),
body: ListView.separated(
itemCount: cubit.funds.length,
itemBuilder: (BuildContext context, int index) {
return MutualFundItem(
fund: cubit.funds[index],
onTap: () {
cubit.deleteFund(cubit.funds[index]);
},
);
},
separatorBuilder: (BuildContext context, int index) {
return const Divider(
thickness: 0.5,
);
},
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/view/savings
|
mirrored_repositories/rupiah/lib/view/savings/mutual_fund/fund_search.dart
|
import 'package:expense_kit/model/entity/scheme_entity.dart';
import 'package:expense_kit/view_model/mutual_fund/mutual_fund_cubit.dart';
import 'package:expense_kit/view_model/state_vm.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class FundSearch extends StatefulWidget {
final ValueChanged<Scheme> onSelect;
const FundSearch({super.key, required this.onSelect});
@override
StateModel<FundSearch, MutualFundCubit> createState() => _FundSearchState();
}
class _FundSearchState extends StateModel<FundSearch, MutualFundCubit> {
@override
void initView(MutualFundCubit cubit) {
cubit.clear();
super.initView(cubit);
}
@override
Widget buildMobile(BuildContext context, MutualFundCubit cubit) {
return Material(
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
autofocus: true,
decoration: InputDecoration(
hintText: 'Search',
prefixIcon: const Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
suffix: cubit.state is MutualFundLoading
? const SizedBox(
height: 16,
width: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
),
)
: const Offstage(),
),
onChanged: (value) => cubit.searchFund(value),
),
const SizedBox(height: 16),
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: cubit.funds.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
cubit.funds[index].schemeName,
),
onTap: () {
widget.onSelect(cubit.funds[index]);
context.pop();
},
);
},
),
),
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/features/investment
|
mirrored_repositories/rupiah/lib/features/investment/view/add_investment.dart
|
import 'dart:io';
import 'package:expense_kit/features/investment/view_model/investments_cubit.dart';
import 'package:expense_kit/utils/ui_extensions.dart';
import 'package:expense_kit/view/decorations.dart';
import 'package:expense_kit/view_model/state_vm.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class AddInvestment extends StatefulWidget {
static const route = '/add-investment';
const AddInvestment({super.key});
@override
StateModel<AddInvestment, InvestmentsCubit> createState() => _AddInvestmentState();
}
class _AddInvestmentState extends StateModel<AddInvestment, InvestmentsCubit> {
TextEditingController fileController = TextEditingController();
File? file;
String? password;
String stocks = '0.0';
String mf = '0.0';
DateTime? date;
@override
Widget buildMobile(BuildContext context, InvestmentsCubit cubit) {
return Material(
child: GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
child: SafeArea(
child: Padding(
padding: EdgeInsets.only(
left: 16,
right: 16,
top: 16,
bottom: MediaQuery.of(context).viewInsets.bottom,
),
child: ListView(
shrinkWrap: true,
children: [
const Text('Real Estate Details'),
const SizedBox(height: 8),
const Divider(),
const SizedBox(height: 16),
TextField(
keyboardType: TextInputType.name,
decoration: textDecoration.copyWith(
labelText: 'Investment Name',
hintText: 'Farm House, Apartment, etc.',
hintStyle: context.hintText(),
),
onChanged: (value) {
cubit.investmentModel.copyWith(description: value);
},
),
const SizedBox(height: 16),
TextField(
keyboardType: TextInputType.name,
decoration: textDecoration.copyWith(
labelText: 'Invested Value',
hintText: '$currency 0.00',
),
inputFormatters: [
currencyFormatter,
],
onChanged: (value) {
password = value;
},
),
const SizedBox(height: 16),
TextField(
readOnly: true,
keyboardType: TextInputType.number,
decoration: textDecoration.copyWith(
labelText: 'Date of Investment',
hintText: 'DD/MM/YYYY',
hintStyle: context.hintText(),
),
onChanged: (value) {
password = value;
},
),
const SizedBox(height: 16),
TextField(
keyboardType: TextInputType.number,
decoration: textDecoration.copyWith(
labelText: 'Current Value',
hintText: '$currency 0.00',
),
inputFormatters: [
currencyFormatter,
],
onChanged: (value) {
password = value;
},
),
const SizedBox(height: 8),
Row(
children: [
const Icon(
Icons.info_outline,
size: 16,
),
const SizedBox(width: 8),
Text(
'Your data will stay safe and secure in your device.',
style: context.smaller(),
),
],
),
const SizedBox(height: 32),
SafeArea(
child: Row(
children: [
Expanded(
child: TextButton(
onPressed: () {
context.pop();
},
child: const Text('Cancel'),
),
),
Expanded(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
elevation: 4,
),
onPressed: cubit.investmentModel.isValid ? () {} : null,
child: Text(
date == null ? 'Process PDF' : 'Update Investment',
),
),
),
],
),
),
],
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/features/investment
|
mirrored_repositories/rupiah/lib/features/investment/model/investment_service.dart
|
import 'package:expense_kit/features/investment/model/investment_model.dart';
import 'package:expense_kit/model/database/database.dart';
class InvestmentService {
final database = Database();
Future<List<InvestmentModel>> getInvestments() async {
List<InvestmentData> data = await database.select(database.investment).get();
return data
.map((e) => InvestmentModel(
id: e.id,
description: e.description,
amount: e.amount,
endDate: e.endDate,
type: e.type,
))
.toList();
}
// Future<Investment> getInvestment(int id) async {
// // Fetch investment from the server
// }
//
// Future<Investment> addInvestment(Investment investment) async {
// // Add investment to the server
// }
//
// Future<Investment> updateInvestment(Investment investment) async {
// // Update investment on the server
// }
//
// Future<void> deleteInvestment(int id) async {
// // Delete investment from the server
// }
}
| 0
|
mirrored_repositories/rupiah/lib/features/investment
|
mirrored_repositories/rupiah/lib/features/investment/model/investment_model.dart
|
enum InvestmentType {
mutualFund,
stocks,
gold,
realEstate,
epf,
ppf,
}
class InvestmentModel {
int? id;
final String? description;
double? amount;
DateTime? endDate;
InvestmentType? type;
InvestmentModel({
this.id,
this.description,
this.amount,
this.endDate,
this.type,
});
bool get isValid => description != null && amount != null && endDate != null && type != null;
// toString method
@override
String toString() {
return 'InvestmentModel{id: $id, '
'description: $description, '
'amount: $amount, '
'endDate: $endDate, '
'type: $type}';
}
// toJson
Map<String, dynamic> toJson() {
return {
'id': id,
'description': description,
'amount': amount,
'endDate': endDate,
'type': type,
};
}
// copyWith
InvestmentModel copyWith({
int? id,
String? description,
double? amount,
DateTime? endDate,
InvestmentType? type,
}) {
return InvestmentModel(
id: id ?? this.id,
description: description ?? this.description,
amount: amount ?? this.amount,
endDate: endDate ?? this.endDate,
type: type ?? this.type,
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/features/investment
|
mirrored_repositories/rupiah/lib/features/investment/model/investment_repo_impl.dart
|
import 'package:expense_kit/features/investment/model/investment_model.dart';
import 'package:expense_kit/features/investment/model/investment_repository.dart';
import 'package:expense_kit/features/investment/model/investment_service.dart';
class InvestmentRepoImpl extends InvestmentRepository {
final InvestmentService service;
InvestmentRepoImpl({required this.service});
@override
Future<void> createInvestment(
int id,
String? description,
double amount,
DateTime? endDate,
InvestmentType type,
) {
throw UnimplementedError();
}
@override
Future<void> deleteInvestment(String id) {
throw UnimplementedError();
}
@override
Future<List<InvestmentModel>> getInvestments() async {
return await service.getInvestments();
}
@override
Future<void> updateInvestment(String id, String name, double value) {
throw UnimplementedError();
}
}
| 0
|
mirrored_repositories/rupiah/lib/features/investment
|
mirrored_repositories/rupiah/lib/features/investment/model/investment_repository.dart
|
import 'package:expense_kit/features/investment/model/investment_model.dart';
abstract class InvestmentRepository {
Future<void> createInvestment(
int id,
String? description,
double amount,
DateTime? endDate,
InvestmentType type,
);
Future<void> deleteInvestment(String id);
Future<void> updateInvestment(String id, String name, double value);
Future<List<InvestmentModel>> getInvestments();
}
| 0
|
mirrored_repositories/rupiah/lib/features/investment
|
mirrored_repositories/rupiah/lib/features/investment/view_model/investments_cubit.dart
|
import 'package:expense_kit/features/investment/model/investment_model.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
part 'investments_state.dart';
class InvestmentsCubit extends Cubit<InvestmentsState> {
InvestmentsCubit() : super(InvestmentsInitial());
InvestmentModel investmentModel = InvestmentModel();
set investmentType(InvestmentType value) {
investmentModel.copyWith(type: value);
emit(InvestmentUpdated());
}
set investmentAmount(double value) {
investmentModel.copyWith(amount: value);
emit(InvestmentUpdated());
}
set investmentEndDate(DateTime value) {
investmentModel.copyWith(endDate: value);
emit(InvestmentUpdated());
}
set investmentDescription(String value) {
investmentModel.copyWith(description: value);
emit(InvestmentUpdated());
}
List<InvestmentType> get investmentTypes => InvestmentType.values;
}
| 0
|
mirrored_repositories/rupiah/lib/features/investment
|
mirrored_repositories/rupiah/lib/features/investment/view_model/investments_state.dart
|
part of 'investments_cubit.dart';
@immutable
abstract class InvestmentsState {}
class InvestmentsInitial extends InvestmentsState {}
class InvestmentUpdated extends InvestmentsState {}
| 0
|
mirrored_repositories/rupiah/lib/model
|
mirrored_repositories/rupiah/lib/model/database/database.dart
|
import 'dart:io';
import 'package:drift/drift.dart';
import 'package:drift/native.dart';
import 'package:expense_kit/features/investment/model/investment_model.dart';
import 'package:expense_kit/model/database/tables/account.dart';
import 'package:expense_kit/model/database/tables/category_table.dart';
import 'package:expense_kit/model/database/tables/emi.dart';
import 'package:expense_kit/model/database/tables/expense.dart';
import 'package:expense_kit/model/database/tables/investment.dart';
import 'package:expense_kit/model/database/tables/mutual_fund.dart';
import 'package:expense_kit/model/entity/expense_entity.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
part 'database.g.dart';
final database = Database();
@DriftDatabase(tables: [
Expense,
Emi,
CategoryDb,
Account,
Investment,
MutualFund,
])
class Database extends _$Database {
Database() : super(_openConnection());
@override
int get schemaVersion => 10;
@override
MigrationStrategy get migration {
return MigrationStrategy(
onCreate: (Migrator m) async {
await m.createAll();
},
onUpgrade: (Migrator m, int from, int to) async {
if (from < 2) {
// we added the dueDate property in the change from version 1 to
// version 2
await m.addColumn(expense, expense.isEMI);
await m.addColumn(expense, expense.emiId);
}
if (from < 4) {
await m.createTable(database.mutualFund);
}
if (from < 6) {
await m.addColumn(mutualFund, mutualFund.currentValue);
await m.addColumn(mutualFund, mutualFund.gainPercentage);
}
if (from < 9) {
await m.addColumn(mutualFund, mutualFund.nav);
}
if (from < 10) {
await m.addColumn(account, account.accountType);
}
},
);
}
}
LazyDatabase _openConnection() {
// the LazyDatabase util lets us find the right location for the file async.
return LazyDatabase(() async {
// put the database file, called db.sqlite here, into the documents folder
// for your app.
final dbFolder = await getApplicationDocumentsDirectory();
final file = File(p.join(dbFolder.path, 'db.sqlite'));
return NativeDatabase.createInBackground(file);
});
}
| 0
|
mirrored_repositories/rupiah/lib/model/database
|
mirrored_repositories/rupiah/lib/model/database/tables/account.dart
|
import 'package:drift/drift.dart';
import 'package:expense_kit/model/database/database.dart';
import 'package:expense_kit/model/database/tables/expense.dart';
import 'package:expense_kit/model/entity/account_entity.dart';
enum AccountType { savings, credit, loan }
class Account extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get accountName => text()();
TextColumn get description => text().nullable()();
TextColumn get colorCode => text().nullable()();
TextColumn get iconCode => text().nullable()();
RealColumn get balance => real()();
IntColumn get accountType => intEnum<AccountType>().withDefault(const Constant(0))();
}
class AccountTable {
Future insert(AccountEntity entity) async {
var companion = AccountCompanion.insert(
description: Value(entity.description),
accountName: entity.accountName ?? '',
colorCode: Value(entity.colorCode),
iconCode: Value(entity.iconCode),
balance: entity.balance ?? 0.0,
accountType: const Value(AccountType.savings),
);
return database.into(database.account).insert(companion);
}
Future remove(AccountEntity entity) async {
return database.account.deleteWhere(
(tbl) => tbl.id.isValue(entity.id!),
);
}
Future<List<AccountEntity>> get() async {
final emiList = await database.select(database.account).get();
final expenseList = await ExpenseTable().allExpensesBeforeToday();
List<AccountEntity> accountList = [];
for (var e in emiList) {
double balance = expenseList.fold(0.0, (previousValue, element) {
if (element.accountId == e.id) {
return previousValue + element.amount;
}
return previousValue;
});
accountList.add(AccountEntity(
id: e.id,
description: e.description ?? '',
accountName: e.accountName,
colorCode: e.colorCode ?? '',
iconCode: e.iconCode ?? '',
balance: balance,
));
}
return accountList;
}
}
| 0
|
mirrored_repositories/rupiah/lib/model/database
|
mirrored_repositories/rupiah/lib/model/database/tables/investment.dart
|
import 'package:drift/drift.dart';
import 'package:expense_kit/features/investment/model/investment_model.dart';
import 'package:expense_kit/model/database/database.dart';
class Investment extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get description => text().nullable()();
RealColumn get amount => real()();
DateTimeColumn get endDate => dateTime().nullable()();
IntColumn get type => intEnum<InvestmentType>()();
}
class InvestmentQuery {
Future insert(InvestmentCompanion companion) async {
return await database.into(database.investment).insert(companion);
}
// Future remove(InvestmentCompanion companion) async {
// return database.into(database.investment).wh;
// }
Future<List<InvestmentData>> allInvestments() async {
final investments = await database.select(database.investment).get();
return investments
.map((e) => InvestmentData(
id: e.id,
description: e.description,
amount: e.amount,
endDate: e.endDate,
type: e.type,
))
.toList();
}
}
| 0
|
mirrored_repositories/rupiah/lib/model/database
|
mirrored_repositories/rupiah/lib/model/database/tables/emi.dart
|
import 'package:drift/drift.dart';
import 'package:expense_kit/model/database/database.dart';
import 'package:expense_kit/model/entity/emi_entity.dart';
class Emi extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get description => text().nullable()();
RealColumn get amount => real()();
DateTimeColumn get endDate => dateTime().nullable()();
}
class EMITable {
Future<EmiData> insert(EMIEntity entity) async {
var companion = EmiCompanion.insert(
description: Value(entity.description),
amount: entity.amount,
endDate: Value(
entity.endDate ?? DateTime.now(),
),
);
return database.into(database.emi).insertReturning(companion);
}
Future remove(EMIEntity entity) async {
return database.emi.deleteWhere((tbl) => tbl.id.isValue(entity.id!));
}
Future<List<EMIEntity>> get() async {
final emiList = await database.select(database.emi).get();
return emiList
.map((e) => EMIEntity(
id: e.id,
description: e.description,
amount: e.amount,
endDate: e.endDate,
))
.toList();
}
}
| 0
|
mirrored_repositories/rupiah/lib/model/database
|
mirrored_repositories/rupiah/lib/model/database/tables/category_table.dart
|
import 'package:drift/drift.dart';
import 'package:expense_kit/model/database/database.dart';
import 'package:expense_kit/model/entity/category_entiry.dart';
class CategoryDb extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get categoryName => text()();
TextColumn get description => text().nullable()();
TextColumn get colorCode => text().nullable()();
TextColumn get iconCode => text().nullable()();
}
class CategoryQuery {
Future insert(CategoryDbCompanion companion) async {
return database.into(database.categoryDb).insert(companion);
}
Future<List<CategoryEntity>> getAll() async {
List<CategoryDbData> categories =
await database.select(database.categoryDb).get();
return categories
.map((e) => CategoryEntity(
id: e.id,
name: e.categoryName,
description: e.description,
colorCode: e.colorCode,
iconCode: e.iconCode,
))
.toList();
}
}
| 0
|
mirrored_repositories/rupiah/lib/model/database
|
mirrored_repositories/rupiah/lib/model/database/tables/expense.dart
|
import 'package:drift/drift.dart';
import 'package:expense_kit/model/database/database.dart';
import 'package:expense_kit/model/entity/expense_entity.dart';
class Expense extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get description => text().nullable()();
RealColumn get amount => real()();
IntColumn get type => intEnum<ExpenseType>()();
DateTimeColumn get date => dateTime().nullable()();
IntColumn get accountId => integer()();
IntColumn get categoryId => integer()();
BoolColumn get isEMI => boolean().withDefault(const Constant(false))();
IntColumn get emiId => integer().withDefault(const Constant(-1))();
}
class ExpenseTable {
Future insert(ExpenseEntity entity) async {
var companion = ExpenseCompanion.insert(
description: Value(entity.description),
amount: entity.amount,
type: entity.type,
date: Value(
entity.dateTime ?? DateTime.now(),
),
accountId: entity.accountId!,
categoryId: entity.categoryId ?? 0,
);
return await database.into(database.expense).insert(companion);
}
Future update(ExpenseEntity entity) async {
var companion = ExpenseCompanion.insert(
id: Value(entity.id),
description: Value(entity.description),
amount: entity.amount,
type: entity.type,
date: Value(
entity.dateTime ?? DateTime.now(),
),
accountId: entity.accountId!,
categoryId: entity.categoryId ?? 0,
);
return await database.expense.insertOnConflictUpdate(companion);
}
Future remove(ExpenseEntity entity) async {
return database.expense.deleteWhere((tbl) => tbl.id.isValue(entity.id));
}
Future removeByEMI(int emiID) async {
return database.expense.deleteWhere((tbl) => tbl.emiId.isValue(emiID));
}
Future<List<ExpenseEntity>> allExpenses() async {
final expenses = await database.select(database.expense).get();
return expenses
.map((e) => ExpenseEntity(
id: e.id,
description: e.description,
amount: e.amount,
type: e.type,
dateTime: e.date,
accountId: e.accountId,
categoryId: e.categoryId,
))
.toList();
}
// get all expenses before today date
Future<List<ExpenseEntity>> allExpensesBeforeToday() async {
var query = database.select(database.expense)
..where(
(row) => row.date.isSmallerThanValue(DateTime.now()),
);
final expenses = await query.get();
return expenses.map((e) {
return ExpenseEntity.fromMap(e.toJson());
}).toList();
}
MultiSelectable<ExpenseData> expenseStream() {
return database.select(database.expense)
..where(
(row) => row.date.isSmallerThanValue(DateTime.now()),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/model/database
|
mirrored_repositories/rupiah/lib/model/database/tables/mutual_fund.dart
|
import 'package:drift/drift.dart';
import 'package:expense_kit/model/database/database.dart';
enum MFType { sip, lumpSum }
enum SipPeriod { daily, monthly, weekly }
class MutualFund extends Table {
IntColumn get id => integer().autoIncrement()();
IntColumn get fundId => integer()();
TextColumn get name => text().nullable()();
TextColumn get description => text().nullable()();
RealColumn get amount => real()();
RealColumn get units => real()();
RealColumn get nav => real().nullable()();
RealColumn get currentValue => real().nullable()();
RealColumn get gainPercentage => real().nullable()();
TextColumn get type => textEnum<MFType>()();
TextColumn get period => textEnum<SipPeriod>()();
DateTimeColumn get investedDate => dateTime().nullable()();
IntColumn get accountId => integer()();
BoolColumn get isActive => boolean().withDefault(const Constant(true))();
}
class MutualFundQuery {
Future insert(MutualFundCompanion companion) async {
return await database
.into(database.mutualFund)
.insertOnConflictUpdate(companion);
}
Future<List<MutualFundData>> allMutualFunds() async {
final funds = await database.select(database.mutualFund).get();
return funds
.map((e) => MutualFundData(
id: e.id,
fundId: e.fundId,
name: e.name,
description: e.description,
amount: e.amount,
units: e.units,
type: e.type,
period: e.period,
investedDate: e.investedDate,
accountId: e.accountId,
isActive: e.isActive,
nav: e.nav,
currentValue: e.currentValue,
gainPercentage: e.gainPercentage,
))
.toList();
}
Future delete(int id) async {
return await database.mutualFund.deleteWhere(
(tbl) => tbl.id.isValue(id),
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/model
|
mirrored_repositories/rupiah/lib/model/service/api_client.dart
|
import 'package:dio/dio.dart';
import 'package:expense_kit/model/service/exceptions.dart';
class ApiClient {
final Dio _dio = Dio();
Future<dynamic> get(String path) async {
Response? response;
try {
response = await _dio.get(path);
} on DioException catch (e) {
throw ServiceError(
code: e.response?.statusCode,
message: e.response?.statusMessage,
trace: e.stackTrace,
);
}
if (response.statusCode == 200) {
return response.data;
} else {
throw ServiceError(
code: response.statusCode,
message: response.statusMessage,
);
}
}
Future<dynamic> post(
String path, {
Map<String, dynamic>? headers,
Object? data,
}) async {
Response? response;
try {
response = await _dio.post(path,
data: data,
options: Options(
headers: headers,
));
} on DioException catch (e) {
throw ServiceError(
code: e.response?.statusCode,
message: e.response?.statusMessage,
trace: e.stackTrace,
);
}
if (response.statusCode == 200) {
return response.data;
} else {
throw ServiceError(
code: response.statusCode,
message: response.statusMessage,
);
}
}
}
| 0
|
mirrored_repositories/rupiah/lib/model
|
mirrored_repositories/rupiah/lib/model/service/exceptions.dart
|
import 'package:logger/logger.dart';
class ServiceError implements Exception {
final int? code;
final String? message;
final StackTrace? trace;
const ServiceError({
required this.code,
required this.message,
this.trace,
});
@override
String toString() {
return 'Service Error: $code $message';
}
void log() {
var logger = Logger();
logger.e(toString());
}
}
| 0
|
mirrored_repositories/rupiah/lib/model
|
mirrored_repositories/rupiah/lib/model/service/mutual_fund_service.dart
|
import 'package:expense_kit/model/entity/mf_central_entity.dart';
import 'package:expense_kit/model/entity/mutual_fund.dart';
import 'package:expense_kit/model/service/api_client.dart';
import 'package:expense_kit/model/service/exceptions.dart';
import 'package:flutter/foundation.dart';
import 'package:logger/logger.dart';
class MutualFundService {
final ApiClient _client = ApiClient();
final String _basePath = 'https://api.mfapi.in/mf';
final Logger _logger = Logger();
Future<MutualFundEntity?> getDetails(String fundId) async {
try {
var response = await _client.get('$_basePath/$fundId/latest');
if (response == null) {
return null;
}
if (kDebugMode) {
print(response);
}
return MutualFundEntity.fromJson(response);
} on ServiceError catch (e) {
e.log();
return null;
}
}
// Future<List<Scheme>> getFunds() async {
// dynamic response;
//
// response = await _client.get(_basePath);
//
// return schemesFromJson(response);
// }
// Future<List<Scheme>> searchFund({required String query}) async {
// dynamic response;
//
// try {
// _logger.d('Search => $_basePath/search?q=$query');
// response = await _client.get('$_basePath/search?q=$query');
//
// return schemesFromJson(response);
// } on ServiceError catch (e) {
// e.log();
// return [];
// }
// }
Future<PortfolioData?> getMFPortfolio({
required String mobileNo,
required String pan,
required String reqId,
required String token,
}) async {
try {
var response = await _client.post(
'https://services.mfcentral.com/user/getportfolio',
data: {
"email": "",
"mobile": mobileNo,
"pan": pan,
"pekrn": "",
"reqId": reqId,
"metaData": {
"appType": "WEB",
"OSVersion": "",
"deviceName": "",
"deviceOS": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 "
"Safari/537.36"
}
},
headers: {
'Content-Type': 'application/json',
'accept': 'application/json',
'authorization': 'Bearer $token',
'origin': 'https://app.mfcentral.com',
},
);
if (response == null) {
return null;
}
if (kDebugMode) {
print(response);
}
return PortfolioData.fromJson(response);
} on ServiceError catch (e) {
e.log();
return null;
}
}
}
| 0
|
mirrored_repositories/rupiah/lib/model
|
mirrored_repositories/rupiah/lib/model/service/login_service.dart
|
import 'package:appwrite/appwrite.dart';
import 'package:appwrite/models.dart';
class LoginService {
static Client client = Client();
LoginService.init() {
client
.setEndpoint('https://cloud.appwrite.io/v1') // Your API Endpoint
.setProject('rupiah') // Your project ID
.setSelfSigned(); // Remove in production
}
static Future<Token> createAccount(String phoneNo, String userId) async {
Account account = Account(client);
return await account.createPhoneSession(
userId: userId,
phone: phoneNo,
);
}
static Future<User> updateSession(String userId, String otp) async {
Account account = Account(client);
final session = await account.updatePhoneSession(
userId: userId,
secret: otp,
);
return await account.get();
}
static Future<User> getUser() async {
Account account = Account(client);
return await account.get();
}
}
| 0
|
mirrored_repositories/rupiah/lib/model
|
mirrored_repositories/rupiah/lib/model/entity/category_entiry.dart
|
class CategoryEntity {
final int id;
final String name;
final String? description;
final String? colorCode;
final String? iconCode;
CategoryEntity({
required this.id,
required this.name,
this.description,
this.colorCode,
this.iconCode,
});
}
| 0
|
mirrored_repositories/rupiah/lib/model
|
mirrored_repositories/rupiah/lib/model/entity/expense_card_entity.dart
|
class ExpenseCardEntity {
final double totalBalance;
final double income;
final double expense;
ExpenseCardEntity({
this.totalBalance = 0.0,
this.income = 0.0,
this.expense = 0.0,
});
}
| 0
|
mirrored_repositories/rupiah/lib/model
|
mirrored_repositories/rupiah/lib/model/entity/mf_central_login_entiry.dart
|
class MFCentralEntity {
final String token;
final int notificationCount;
final String? redirectPath;
final bool isLoggedOut;
final bool isLoggedIn;
final bool firstTimeLoggedIn;
final bool enableTwoFactorAuth;
final bool appTourVisited;
final bool enabledPin;
final bool isFromPreLogin;
final String backupPin;
final String newToMF;
final String reqId;
final String pekrn;
final String displayName;
final String userRegisteredWith;
final String ftTransactions;
final String otmRegistration;
final String message;
final String showPopUp;
final String email;
final String mobile;
final String displayMobile;
final String pan;
MFCentralEntity({
required this.token,
required this.notificationCount,
this.redirectPath,
required this.isLoggedOut,
required this.isLoggedIn,
required this.firstTimeLoggedIn,
required this.enableTwoFactorAuth,
required this.appTourVisited,
required this.enabledPin,
required this.isFromPreLogin,
required this.backupPin,
required this.newToMF,
required this.reqId,
required this.pekrn,
required this.displayName,
required this.userRegisteredWith,
required this.ftTransactions,
required this.otmRegistration,
required this.message,
required this.showPopUp,
required this.email,
required this.mobile,
required this.displayMobile,
required this.pan,
});
factory MFCentralEntity.fromJson(Map<String, dynamic> json) {
return MFCentralEntity(
token: json['token'],
notificationCount: json['notificationCount'],
redirectPath: json['redirectPath'],
isLoggedOut: json['isLoggedOut'],
isLoggedIn: json['isLoggedIn'],
firstTimeLoggedIn: json['firstTimeLoggedIn'],
enableTwoFactorAuth: json['enableTwoFactorAuth'],
appTourVisited: json['appTourVisited'],
enabledPin: json['enabledPin'],
isFromPreLogin: json['isFromPreLogin'],
backupPin: json['backupPin'],
newToMF: json['newToMF'],
reqId: json['reqId'],
pekrn: json['pekrn'],
displayName: json['displayName'],
userRegisteredWith: json['userRegisteredWith'],
ftTransactions: json['ftTransactions'],
otmRegistration: json['otmRegistration'],
message: json['message'],
showPopUp: json['showPopUp'],
email: json['email'],
mobile: json['mobile'],
displayMobile: json['displayMobile'],
pan: json['pan'],
);
}
Map<String, dynamic> toJson() {
return {
'token': token,
'notificationCount': notificationCount,
'redirectPath': redirectPath,
'isLoggedOut': isLoggedOut,
'isLoggedIn': isLoggedIn,
'firstTimeLoggedIn': firstTimeLoggedIn,
'enableTwoFactorAuth': enableTwoFactorAuth,
'appTourVisited': appTourVisited,
'enabledPin': enabledPin,
'isFromPreLogin': isFromPreLogin,
'backupPin': backupPin,
'newToMF': newToMF,
'reqId': reqId,
'pekrn': pekrn,
'displayName': displayName,
'userRegisteredWith': userRegisteredWith,
'ftTransactions': ftTransactions,
'otmRegistration': otmRegistration,
'message': message,
'showPopUp': showPopUp,
'email': email,
'mobile': mobile,
'displayMobile': displayMobile,
'pan': pan,
};
}
}
class Matched {
final String amc;
final String amcName;
final dynamic folio;
final String isDemat;
Matched({
required this.amc,
required this.amcName,
required this.folio,
required this.isDemat,
});
factory Matched.fromJson(Map<String, dynamic> json) {
return Matched(
amc: json['amc'],
amcName: json['amcName'],
folio: json['folio'],
isDemat: json['isDemat'],
);
}
}
class Persist {
final int version;
final bool rehydrated;
Persist({
required this.version,
required this.rehydrated,
});
factory Persist.fromJson(Map<String, dynamic> json) {
return Persist(
version: json['version'],
rehydrated: json['rehydrated'],
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/model
|
mirrored_repositories/rupiah/lib/model/entity/scheme_entity.dart
|
class Scheme {
final int schemeCode;
final String schemeName;
const Scheme({
required this.schemeCode,
required this.schemeName,
});
factory Scheme.fromJson(Map<String, dynamic> json) {
return Scheme(
schemeCode: json['schemeCode'],
schemeName: json['schemeName'],
);
}
Map<String, dynamic> toJson() => {
'schemeCode': schemeCode,
'schemeName': schemeName,
};
}
List<Scheme> schemesFromJson(List<dynamic> json) {
return json.map((dynamic e) => Scheme.fromJson(e)).toList();
}
| 0
|
mirrored_repositories/rupiah/lib/model
|
mirrored_repositories/rupiah/lib/model/entity/expense_entity.dart
|
import 'package:flutter/foundation.dart';
import 'package:intl/intl.dart';
@immutable
class ExpenseEntity {
final double amount;
final int id;
final ExpenseType type;
final DateTime? dateTime;
final String? description;
final int? accountId;
final int? categoryId;
const ExpenseEntity({
this.id = 0,
this.amount = 0.0,
this.type = ExpenseType.outgoing,
this.dateTime,
this.description,
this.accountId,
this.categoryId,
});
factory ExpenseEntity.fromMap(
Map<String, dynamic> map,
) {
int seconds = map['date'] ?? 0;
var date = DateTime.fromMillisecondsSinceEpoch(seconds);
return ExpenseEntity(
dateTime: map['date'] != null ? date : null,
amount: map['amount'] ?? 0.0,
type: ExpenseType.values[map['type']],
description: map['description'],
id: map['id'],
accountId: map['accountId'],
categoryId: map['categoryId'],
);
}
String formattedDate() {
return DateFormat('MMM, dd hh:mm a').format(dateTime!);
}
ExpenseEntity copyWith({
int? id,
double? amount,
ExpenseType? type,
DateTime? dateTime,
String? description,
int? accountId,
int? categoryId,
}) {
return ExpenseEntity(
id: id ?? this.id,
amount: amount ?? this.amount,
type: type ?? this.type,
dateTime: dateTime ?? this.dateTime,
description: description ?? this.description,
accountId: accountId ?? this.accountId,
categoryId: categoryId ?? this.categoryId,
);
}
}
enum ExpenseType { income, outgoing, savings }
| 0
|
mirrored_repositories/rupiah/lib/model
|
mirrored_repositories/rupiah/lib/model/entity/account_entity.dart
|
// entity for the AccountTable
import 'package:expense_kit/model/database/tables/account.dart';
class AccountEntity {
final String? accountName;
final String? description;
final String? colorCode;
final String? iconCode;
final double? balance;
final AccountType accountType;
final int? id;
AccountEntity({
this.accountName,
this.description,
this.colorCode,
this.iconCode,
this.balance,
this.id,
this.accountType = AccountType.savings,
});
// copy with
AccountEntity copyWith({
String? accountName,
String? description,
String? colorCode,
String? iconCode,
int? id,
double? balance,
AccountType? accountType,
}) {
return AccountEntity(
accountName: accountName ?? this.accountName,
description: description ?? this.description,
colorCode: colorCode ?? this.colorCode,
iconCode: iconCode ?? this.iconCode,
id: id ?? this.id,
balance: balance ?? this.balance,
accountType: accountType ?? this.accountType,
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/model
|
mirrored_repositories/rupiah/lib/model/entity/mf_central_entity.dart
|
class PortfolioData {
final String reqId;
final String pan;
final String pekrn;
final String mobile;
final String email;
final List<Data> data;
final String tempDpId;
final List<Portfolio> portfolio;
PortfolioData({
required this.reqId,
required this.pan,
required this.pekrn,
required this.mobile,
required this.email,
required this.data,
required this.tempDpId,
required this.portfolio,
});
factory PortfolioData.fromJson(Map<String, dynamic> json) {
return PortfolioData(
reqId: json['reqId'],
pan: json['pan'],
pekrn: json['pekrn'],
mobile: json['mobile'],
email: json['email'],
data: List<Data>.from(json['data'].map((e) => Data.fromJson(e))),
tempDpId: json['tempDpId'],
portfolio: List<Portfolio>.from(
json['portfolio'].map((e) => Portfolio.fromJson(e))),
);
}
}
class Data {
final List<Summary> summary;
final List<Scheme> schemes;
Data({
required this.summary,
required this.schemes,
});
factory Data.fromJson(Map<String, dynamic> json) {
return Data(
summary:
List<Summary>.from(json['summary'].map((e) => Summary.fromJson(e))),
schemes:
List<Scheme>.from(json['schemes'].map((e) => Scheme.fromJson(e))),
);
}
}
class Summary {
final String amc;
final String amcName;
final String isDemat;
final String currentMktValue;
final String costValue;
final String gainLoss;
final String gainLossPercentage;
Summary({
required this.amc,
required this.amcName,
required this.isDemat,
required this.currentMktValue,
required this.costValue,
required this.gainLoss,
required this.gainLossPercentage,
});
factory Summary.fromJson(Map<String, dynamic> json) {
return Summary(
amc: json['amc'],
amcName: json['amcName'],
isDemat: json['isDemat'],
currentMktValue: json['currentMktValue'].toString(),
costValue: json['costValue'].toString(),
gainLoss: json['gainLoss'].toString(),
gainLossPercentage: json['gainLossPercentage'].toString(),
);
}
}
class Scheme {
final String amc;
final String amcName;
final String folio;
final String investorName;
final int age;
final String schemeCode;
final String schemeName;
final String schemeOption;
final String assetType;
final String schemeType;
final String nav;
final String navDate;
final String closingBalance;
final String availableUnits;
final String availableAmount;
final String currentMktValue;
final String costValue;
final String gainLoss;
final String gainLossPercentage;
final String isDemat;
final String lienUnitsFlag;
final int decimalUnits;
final int decimalAmount;
final int decimalNav;
final String brokerCode;
final String brokerName;
final String isin;
final String purAllow;
final String redAllow;
final String swtAllow;
final String sipAllow;
final String stpAllow;
final String swpAllow;
final String planMode;
final String dpId;
final String rtaName;
final String nomineeStatus;
Scheme({
required this.amc,
required this.amcName,
required this.folio,
required this.investorName,
required this.age,
required this.schemeCode,
required this.schemeName,
required this.schemeOption,
required this.assetType,
required this.schemeType,
required this.nav,
required this.navDate,
required this.closingBalance,
required this.availableUnits,
required this.availableAmount,
required this.currentMktValue,
required this.costValue,
required this.gainLoss,
required this.gainLossPercentage,
required this.isDemat,
required this.lienUnitsFlag,
required this.decimalUnits,
required this.decimalAmount,
required this.decimalNav,
required this.brokerCode,
required this.brokerName,
required this.isin,
required this.purAllow,
required this.redAllow,
required this.swtAllow,
required this.sipAllow,
required this.stpAllow,
required this.swpAllow,
required this.planMode,
required this.dpId,
required this.rtaName,
required this.nomineeStatus,
});
factory Scheme.fromJson(Map<String, dynamic> json) {
return Scheme(
amc: json['amc'],
amcName: json['amcName'],
folio: json['folio'],
investorName: json['investorName'],
age: json['age'],
schemeCode: json['schemeCode'],
schemeName: json['schemeName'],
schemeOption: json['schemeOption'],
assetType: json['assetType'],
schemeType: json['schemeType'],
nav: json['nav'].toString(),
navDate: json['navDate'],
closingBalance: json['closingBalance'].toString(),
availableUnits: json['availableUnits'].toString(),
availableAmount: json['availableAmount'].toString(),
currentMktValue: json['currentMktValue'].toString(),
costValue: json['costValue'].toString(),
gainLoss: json['gainLoss'].toString(),
gainLossPercentage: json['gainLossPercentage'].toString(),
isDemat: json['isDemat'],
lienUnitsFlag: json['lienUnitsFlag'],
decimalUnits: json['decimalUnits'],
decimalAmount: json['decimalAmount'],
decimalNav: json['decimalNav'],
brokerCode: json['brokerCode'],
brokerName: json['brokerName'],
isin: json['isin'],
purAllow: json['purAllow'],
redAllow: json['redAllow'],
swtAllow: json['swtAllow'],
sipAllow: json['sipAllow'],
stpAllow: json['stpAllow'],
swpAllow: json['swpAllow'],
planMode: json['planMode'],
dpId: json['dpId'],
rtaName: json['rtaName'],
nomineeStatus: json['nomineeStatus'],
);
}
}
class Portfolio {
final String currentMktValue;
final String costValue;
final String gainLoss;
final String gainLossPercentage;
final String isDemat;
Portfolio({
required this.currentMktValue,
required this.costValue,
required this.gainLoss,
required this.gainLossPercentage,
required this.isDemat,
});
factory Portfolio.fromJson(Map<String, dynamic> json) {
return Portfolio(
currentMktValue: json['currentMktValue'].toString(),
costValue: json['costValue'].toString(),
gainLoss: json['gainLoss'].toString(),
gainLossPercentage: json['gainLossPercentage'].toString(),
isDemat: json['isDemat'],
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/model
|
mirrored_repositories/rupiah/lib/model/entity/emi_entity.dart
|
import 'package:flutter/foundation.dart';
import 'package:intl/intl.dart';
import 'package:jiffy/jiffy.dart';
class EMIEntity {
final String? description;
final double amount;
final DateTime? endDate;
final int? id;
const EMIEntity({
this.description,
this.amount = 0.0,
this.endDate,
this.id,
});
String formattedDate() {
return endDate != null ? DateFormat('yyyy MMM').format(endDate!) : '';
}
double pending() {
num val = Jiffy.parseFromDateTime(
DateTime(
endDate!.year,
endDate!.month,
30,
),
).diff(Jiffy.now(), unit: Unit.month);
if (kDebugMode) {
print(val);
print(endDate);
}
return amount * val;
}
num pendingMonths() {
num val = Jiffy.parseFromDateTime(
DateTime(
endDate!.year,
endDate!.month,
30,
),
).diff(Jiffy.now(), unit: Unit.month);
return val;
}
EMIEntity copyWith({
String? description,
double? amount,
DateTime? endDate,
int? id,
}) {
return EMIEntity(
description: description ?? this.description,
amount: amount ?? this.amount,
endDate: endDate ?? this.endDate,
id: id ?? this.id,
);
}
}
| 0
|
mirrored_repositories/rupiah/lib/model
|
mirrored_repositories/rupiah/lib/model/entity/fund_detail.dart
|
import 'package:expense_kit/model/entity/mutual_fund.dart';
class FundDetails {
final int id;
final String fundId;
final double units;
final double invested;
final MutualFundEntity fund;
final String logoPath;
FundDetails({
required this.id,
required this.fundId,
required this.units,
required this.invested,
required this.fund,
required this.logoPath,
});
double get profitPercent =>
(((fund.currentNav * units) - invested) / invested) * 100;
double get profit => ((fund.currentNav * units) - invested);
}
| 0
|
mirrored_repositories/rupiah/lib/model
|
mirrored_repositories/rupiah/lib/model/entity/mutual_fund.dart
|
class MutualFundEntity {
Meta meta;
List<Data> data;
String status;
double get currentNav => double.parse(data.first.nav);
MutualFundEntity(
{required this.meta, required this.data, required this.status});
factory MutualFundEntity.fromJson(Map<String, dynamic> json) {
return MutualFundEntity(
meta: Meta.fromJson(json['meta']),
data: List<Data>.from(json['data'].map((data) => Data.fromJson(data))),
status: json['status'],
);
}
}
class Meta {
String fundHouse;
String schemeType;
String schemeCategory;
int schemeCode;
String schemeName;
Meta({
required this.fundHouse,
required this.schemeType,
required this.schemeCategory,
required this.schemeCode,
required this.schemeName,
});
factory Meta.fromJson(Map<String, dynamic> json) {
return Meta(
fundHouse: json['fund_house'],
schemeType: json['scheme_type'],
schemeCategory: json['scheme_category'],
schemeCode: json['scheme_code'],
schemeName: json['scheme_name'],
);
}
}
class Data {
String date;
String nav;
Data({required this.date, required this.nav});
factory Data.fromJson(Map<String, dynamic> json) {
return Data(
date: json['date'],
nav: json['nav'],
);
}
}
| 0
|
mirrored_repositories/rupiah/lib
|
mirrored_repositories/rupiah/lib/view_model/expense_card_state.dart
|
import 'package:expense_kit/model/database/tables/expense.dart';
import 'package:expense_kit/model/entity/expense_card_entity.dart';
import 'package:expense_kit/model/entity/expense_entity.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class ExpenseCardState extends StateNotifier<ExpenseCardEntity> {
ExpenseCardState() : super(ExpenseCardEntity());
void init() {
ExpenseTable().expenseStream().watch().listen((event) async {
state = ExpenseCardEntity();
double amount = 0;
double expense = 0;
for (var value in event) {
ExpenseEntity entity = ExpenseEntity.fromMap(value.toJson());
if (entity.type == ExpenseType.income) {
amount += entity.amount;
} else if (entity.type == ExpenseType.outgoing) {
expense += entity.amount;
}
}
state = ExpenseCardEntity(
income: amount,
expense: expense,
totalBalance: amount - expense,
);
});
}
}
final expenseCardState =
StateNotifierProvider<ExpenseCardState, ExpenseCardEntity>((ref) {
return ExpenseCardState()..init();
});
| 0
|
mirrored_repositories/rupiah/lib
|
mirrored_repositories/rupiah/lib/view_model/state_vm.dart
|
import 'dart:async';
import 'package:currency_text_input_formatter/currency_text_input_formatter.dart';
import 'package:expense_kit/utils/currency_utils.dart';
import 'package:expense_kit/utils/ui_extensions.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
abstract class StateModel<T extends StatefulWidget, C extends Cubit> extends State<T> {
late StreamSubscription _subscription;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
initView(context.read<C>());
_subscription = context.read<C>().stream.listen((state) {
listener(state);
});
setState(() {
cubit = context.read<C>();
state = context.read<C>().state;
});
});
}
C? cubit;
dynamic state;
@override
Widget build(BuildContext context) {
return BlocBuilder(
bloc: context.read<C>(),
builder: (context, state) => context.isTab
? buildTab(context, context.read<C>())
: buildMobile(context, context.read<C>()),
);
}
Widget buildTab(BuildContext context, C cubit) {
return context.widget;
}
Widget buildMobile(BuildContext context, C cubit) {
return context.widget;
}
void listener(dynamic state) {}
void initView(C cubit) {}
CurrencyTextInputFormatter currencyFormatter = CurrencyUtils.formatter;
String currency = CurrencyUtils.currencySymbol;
@override
void dispose() {
super.dispose();
_subscription.cancel();
}
}
| 0
|
mirrored_repositories/rupiah/lib
|
mirrored_repositories/rupiah/lib/view_model/create_expense.dart
|
import 'package:expense_kit/model/entity/expense_entity.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class CreateNotifier extends StateNotifier<ExpenseEntity> {
CreateNotifier() : super(const ExpenseEntity());
void addExpense(ExpenseEntity expense) {
state = expense;
}
void updateExpense(ExpenseEntity expense) {
state = expense;
}
void amount(double amount) {
if (amount > 0) {
state = state.copyWith(amount: amount);
} else {
state = state.copyWith(amount: null);
}
}
}
final createExpense =
StateNotifierProvider<CreateNotifier, ExpenseEntity>((ref) {
return CreateNotifier();
});
| 0
|
mirrored_repositories/rupiah/lib
|
mirrored_repositories/rupiah/lib/view_model/expense_viewmodel.dart
|
import 'package:expense_kit/model/database/tables/expense.dart';
import 'package:expense_kit/model/entity/expense_entity.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class ExpenseNotifier extends StateNotifier<List<ExpenseEntity>> {
ExpenseNotifier() : super([]);
Future add(ExpenseEntity expense) async {
await ExpenseTable().insert(expense);
await getAll();
}
Future update(ExpenseEntity expense) async {
await ExpenseTable().update(expense);
await getAll();
}
void removeExpense(ExpenseEntity expense) {
ExpenseTable().remove(expense);
getAll();
}
Future getAll() async {
state = await ExpenseTable().allExpensesBeforeToday();
}
}
final expenseProvider =
StateNotifierProvider<ExpenseNotifier, List<ExpenseEntity>>((ref) {
return ExpenseNotifier();
});
| 0
|
mirrored_repositories/rupiah/lib/view_model
|
mirrored_repositories/rupiah/lib/view_model/emi/create_emi_state.dart
|
import 'package:drift/drift.dart';
import 'package:expense_kit/model/database/database.dart';
import 'package:expense_kit/model/database/tables/emi.dart';
import 'package:expense_kit/model/entity/emi_entity.dart';
import 'package:expense_kit/model/entity/expense_entity.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:jiffy/jiffy.dart';
class CreateEMIState extends StateNotifier<EMIEntity> {
CreateEMIState() : super(const EMIEntity());
Future addEMI(EMIEntity emi, int count) async {
EmiData data = await EMITable().insert(emi);
List<ExpenseCompanion> companion = [];
List.generate(count, (index) {
print(index);
print(Jiffy.now().add(months: index).dateTime);
companion.add(
ExpenseCompanion.insert(
amount: emi.amount,
type: ExpenseType.outgoing,
accountId: -1,
categoryId: -1,
isEMI: const Value(true),
emiId: Value(data.id),
description: Value(emi.description),
date: Value(Jiffy.now().add(months: index).dateTime),
),
);
});
await database.batch(
(batch) => batch.insertAll(database.expense, companion),
);
}
void updateEMI(EMIEntity emi) {
state = emi;
}
void amount(double amount) {
if (amount > 0) {
state = state.copyWith(amount: amount);
} else {
state = state.copyWith(amount: null);
}
}
}
final emiState = StateNotifierProvider<CreateEMIState, EMIEntity>((ref) {
return CreateEMIState();
});
| 0
|
mirrored_repositories/rupiah/lib/view_model
|
mirrored_repositories/rupiah/lib/view_model/emi/emi_list_state.dart
|
import 'package:expense_kit/model/database/tables/emi.dart';
import 'package:expense_kit/model/database/tables/expense.dart';
import 'package:expense_kit/model/entity/emi_entity.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class EMIListState extends StateNotifier<List<EMIEntity>> {
EMIListState() : super(const []);
bool asc = false;
double totalAmount() {
return state.fold(
0, (previousValue, element) => previousValue + element.amount);
}
Future getAll() async {
state = await EMITable().get();
}
void sort() {
asc = !asc;
state = [...state]..sort(
(a, b) =>
asc ? a.amount.compareTo(b.amount) : b.amount.compareTo(a.amount),
);
}
double pending() {
return state.fold(
0, (previousValue, element) => previousValue + element.pending());
}
void delete(EMIEntity entity) async {
await EMITable().remove(entity);
await ExpenseTable().removeByEMI(entity.id!);
await getAll();
}
}
final emiListProvider =
StateNotifierProvider<EMIListState, List<EMIEntity>>((ref) {
return EMIListState()..getAll();
});
| 0
|
mirrored_repositories/rupiah/lib/view_model
|
mirrored_repositories/rupiah/lib/view_model/dashboard/dashboard_cubit.dart
|
import 'package:expense_kit/model/database/tables/expense.dart';
import 'package:expense_kit/model/entity/expense_entity.dart';
import 'package:expense_kit/utils/currency_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
part 'dashboard_state.dart';
class DashboardCubit extends Cubit<DashboardState> {
DashboardCubit() : super(DashboardInitial());
double savings = 0;
double mutualFund = 0;
void expense() async {
ExpenseTable().allExpensesBeforeToday().then((value) {
savings = value.fold(0.0, (previousValue, element) {
if (element.type == ExpenseType.income) {
return previousValue += element.amount;
} else {
return previousValue -= element.amount;
}
});
});
emit(DashboardInitial());
}
void update(double value) {
mutualFund = value;
emit(DashboardInitial());
}
String totalAmount() {
double balance = savings + mutualFund;
String locale = 'en_IN';
if (balance < 100000) {
locale = 'en_US';
}
return NumberFormat.compactCurrency(
symbol: currencySymbol,
locale: locale,
).format(balance);
}
double get balance => savings + mutualFund;
}
| 0
|
mirrored_repositories/rupiah/lib/view_model
|
mirrored_repositories/rupiah/lib/view_model/dashboard/dashboard_state.dart
|
part of 'dashboard_cubit.dart';
@immutable
abstract class DashboardState {}
class DashboardInitial extends DashboardState {}
| 0
|
mirrored_repositories/rupiah/lib/view_model
|
mirrored_repositories/rupiah/lib/view_model/account/account_list_state.dart
|
import 'package:expense_kit/model/database/tables/account.dart';
import 'package:expense_kit/model/entity/account_entity.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class AccountListState extends StateNotifier<List<AccountEntity>> {
AccountListState() : super(const []);
bool asc = false;
AccountEntity? selected;
void setSelected(AccountEntity entity) {
selected = entity;
state = [...state];
}
Future getAll() async {
state = await AccountTable().get();
}
// void sort() {
// asc = !asc;
// state = [...state]..sort(
// (a, b) =>
// asc ? a.amount.compareTo(b.amount) : b.amount.compareTo(a.amount),
// );
// }
void delete(AccountEntity entity) async {
await AccountTable().remove(entity);
await getAll();
}
}
final accountListState =
StateNotifierProvider<AccountListState, List<AccountEntity>>((ref) {
return AccountListState();
});
| 0
|
mirrored_repositories/rupiah/lib/view_model
|
mirrored_repositories/rupiah/lib/view_model/account/create_account_state.dart
|
import 'package:expense_kit/model/database/tables/account.dart';
import 'package:expense_kit/model/entity/account_entity.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class CreateAccountState extends StateNotifier<AccountEntity> {
CreateAccountState() : super(AccountEntity());
final AccountTable _table = AccountTable();
Future addAccount(AccountEntity entity) {
return _table.insert(entity);
}
void updateAccount(AccountEntity entity) {
state = entity;
}
}
final createAccountState =
StateNotifierProvider<CreateAccountState, AccountEntity>((ref) {
return CreateAccountState();
});
| 0
|
mirrored_repositories/rupiah/lib/view_model
|
mirrored_repositories/rupiah/lib/view_model/category/category_cubit.dart
|
import 'package:drift/drift.dart';
import 'package:expense_kit/model/database/database.dart';
import 'package:expense_kit/model/database/tables/category_table.dart';
import 'package:expense_kit/model/entity/category_entiry.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
part 'category_state.dart';
class CategoryCubit extends Cubit<CategoryState> {
CategoryCubit() : super(CategoryInitial());
CategoryDbCompanion companion = const CategoryDbCompanion();
List<CategoryEntity> _list = [];
set list(List<CategoryEntity> value) {
_list = value;
emit(CategoriesLoaded());
}
List<CategoryEntity> get list => _list;
final CategoryQuery _query = CategoryQuery();
void reset() {
companion = const CategoryDbCompanion();
emit(CategoryInitial());
}
void iconUpdate(String iconCode) {
companion = companion.copyWith(
iconCode: Value(iconCode),
);
emit(CategoryUpdated());
}
void colorUpdate(String colorCode) {
companion = companion.copyWith(
colorCode: Value(colorCode),
);
emit(CategoryUpdated());
}
void nameUpdate(String name) {
companion = companion.copyWith(
categoryName: Value(name),
);
emit(CategoryUpdated());
}
void descriptionUpdate(String description) {
companion = companion.copyWith(
description: Value(description),
);
emit(CategoryUpdated());
}
bool get valid =>
companion.categoryName.present && companion.categoryName.value.isNotEmpty;
void create() async {
await _query.insert(companion);
reset();
get();
}
void get() async {
list = await _query.getAll();
}
}
| 0
|
mirrored_repositories/rupiah/lib/view_model
|
mirrored_repositories/rupiah/lib/view_model/category/category_state.dart
|
part of 'category_cubit.dart';
@immutable
abstract class CategoryState {}
class CategoryInitial extends CategoryState {}
class CategoryUpdated extends CategoryState {}
class CategoriesLoaded extends CategoryState {}
| 0
|
mirrored_repositories/rupiah/lib/view_model
|
mirrored_repositories/rupiah/lib/view_model/auth/auth_cubit.dart
|
import 'package:appwrite/appwrite.dart';
import 'package:appwrite/models.dart';
import 'package:expense_kit/model/service/login_service.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
part 'auth_state.dart';
class AuthCubit extends Cubit<AuthState> {
AuthCubit() : super(AuthInitial());
bool _optSent = false;
bool get otpSent => _optSent;
String? _phone;
String? get phone => _phone;
set phone(String? phone) {
_phone = phone;
emit(AuthInitial());
}
String? _otp;
String? get otp => _otp;
Token? _token;
User? _user;
User? get user => _user;
bool validNumber() => _phone != null && _phone!.length == 10;
void validateLogin() async {
emit(UserLoggedIn());
_user = await LoginService.getUser();
emit(UserNotLoggedIn());
}
void fetchOTP() async {
emit(FetchingOTP());
_token = await LoginService.createAccount('+91$_phone', ID.unique());
_optSent = true;
emit(FetchedOTP());
}
void validateOTP(String otp) async {
emit(ValidatingOTP());
_user = await LoginService.updateSession(_token!.userId, otp);
emit(AuthSuccess());
}
}
| 0
|
mirrored_repositories/rupiah/lib/view_model
|
mirrored_repositories/rupiah/lib/view_model/auth/auth_state.dart
|
part of 'auth_cubit.dart';
abstract class AuthState {
const AuthState();
}
class AuthInitial extends AuthState {}
class FetchingOTP extends AuthState {}
class FetchedOTP extends AuthState {}
class ValidatingOTP extends AuthState {}
class UserLoggedIn extends AuthState {}
class UserNotLoggedIn extends AuthState {}
class AuthSuccess extends AuthState {}
| 0
|
mirrored_repositories/rupiah/lib/view_model
|
mirrored_repositories/rupiah/lib/view_model/mutual_fund/mutual_fund_cubit.dart
|
import 'package:expense_kit/model/entity/scheme_entity.dart';
import 'package:expense_kit/model/service/mutual_fund_service.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
part 'mutual_fund_state.dart';
class MutualFundCubit extends Cubit<MutualFundState> {
MutualFundCubit() : super(MutualFundInitial());
final _service = MutualFundService();
List<Scheme> _masterFunds = [];
List<Scheme> _funds = [];
List<Scheme> get funds => _funds;
void searchFund(String query) async {
if (query.length < 4) {
return;
}
emit(MutualFundLoading());
// _funds = await _service.searchFund(query: query);
emit(MutualFundLoaded());
}
void clear() {
_funds.clear();
emit(MutualFundInitial());
}
void loadFunds() async {
_funds.clear();
if (_masterFunds.isNotEmpty) {
_funds.addAll(_masterFunds);
emit(MutualFundLoaded());
return;
}
emit(MutualFundLoading());
// _masterFunds = await _service.getFunds();
// _funds.addAll(_masterFunds);
emit(MutualFundLoaded());
}
// void calculateSip() async {
// // var fund1 = await MutualFundService().getDetails('120828');
// double monthlyInvestment = 2000;
// double expectedReturnRate = 9.85;
// double timePeriod = 1;
// double investedAmount = 8000;
// double totalInvestment;
// double result;
// double i;
//
// i = (expectedReturnRate) / (12 * 100);
//
// result = (monthlyInvestment *
// (((pow((1 + i), (timePeriod * 12))) - 1) / i) *
// (1 + i)) -
// investedAmount;
//
// totalInvestment = investedAmount + result;
//
// print(totalInvestment);
// }
}
| 0
|
mirrored_repositories/rupiah/lib/view_model
|
mirrored_repositories/rupiah/lib/view_model/mutual_fund/mutual_fund_state.dart
|
part of 'mutual_fund_cubit.dart';
@immutable
abstract class MutualFundState {}
class MutualFundInitial extends MutualFundState {}
class MutualFundLoading extends MutualFundState {}
class MutualFundLoaded extends MutualFundState {}
| 0
|
mirrored_repositories/rupiah/lib/view_model/mutual_fund
|
mirrored_repositories/rupiah/lib/view_model/mutual_fund/create/create_mf_state.dart
|
part of 'create_mf_cubit.dart';
@immutable
abstract class CreateMfState {}
class CreateMfInitial extends CreateMfState {}
class FiledUpdated extends CreateMfState {}
class FundDetailsLoaded extends CreateMfState {}
| 0
|
mirrored_repositories/rupiah/lib/view_model/mutual_fund
|
mirrored_repositories/rupiah/lib/view_model/mutual_fund/create/create_mf_cubit.dart
|
import 'package:drift/drift.dart';
import 'package:expense_kit/model/database/database.dart';
import 'package:expense_kit/model/database/tables/mutual_fund.dart';
import 'package:expense_kit/model/entity/mutual_fund.dart';
import 'package:expense_kit/model/entity/scheme_entity.dart';
import 'package:expense_kit/model/service/mutual_fund_service.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
part 'create_mf_state.dart';
class CreateMfCubit extends Cubit<CreateMfState> {
CreateMfCubit() : super(CreateMfInitial());
final MutualFundQuery _query = MutualFundQuery();
num? _amount;
num? _currentValue;
MFType _type = MFType.sip;
Scheme? _scheme;
MutualFundEntity? fund;
// setters
set amount(num? value) {
_amount = value;
emit(FiledUpdated());
}
set currentValue(num? value) {
_currentValue = value;
emit(FiledUpdated());
}
set type(MFType value) {
_type = value;
emit(FiledUpdated());
}
set scheme(Scheme? value) {
_scheme = value;
emit(FiledUpdated());
}
// getters
num? get amount => _amount;
num? get currentValue => _currentValue;
MFType get type => _type;
Scheme? get scheme => _scheme;
bool get isValid =>
_amount != null &&
_currentValue != null &&
_scheme != null &&
fund != null;
/// Methods
void insert() async {
if (isValid) {
var units = _currentValue!.toDouble() / fund!.currentNav;
final companion = MutualFundCompanion(
fundId: Value(_scheme!.schemeCode),
name: Value(_scheme!.schemeName),
description: Value(_scheme!.schemeName),
amount: Value(_amount!.toDouble()),
units: Value(units),
type: Value(_type),
period: const Value(SipPeriod.monthly),
investedDate: Value(DateTime.now()),
accountId: const Value(-1),
);
await _query.insert(companion);
}
}
void fundDetails() async {
fund = await MutualFundService().getDetails(
_scheme!.schemeCode.toString(),
);
emit(FundDetailsLoaded());
}
}
| 0
|
mirrored_repositories/rupiah/lib/view_model/mutual_fund
|
mirrored_repositories/rupiah/lib/view_model/mutual_fund/mf_login/mf_login_cubit.dart
|
import 'dart:convert';
import 'package:drift/drift.dart';
import 'package:expense_kit/model/database/database.dart';
import 'package:expense_kit/model/database/tables/mutual_fund.dart';
import 'package:expense_kit/model/entity/mf_central_entity.dart';
import 'package:expense_kit/model/entity/mf_central_login_entiry.dart';
import 'package:expense_kit/model/service/exceptions.dart';
import 'package:expense_kit/model/service/mutual_fund_service.dart';
import 'package:expense_kit/view_model/savings/savings_cubit.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:shared_preferences/shared_preferences.dart';
part 'mf_login_state.dart';
class MfLoginCubit extends Cubit<MfLoginState> {
MfLoginCubit({required this.savingsCubit}) : super(MfLoginInitial());
final SavingsCubit savingsCubit;
final MutualFundService _service = MutualFundService();
init() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final String? login = prefs.getString('mf_login');
if (login != null) {
MFCentralEntity entity = MFCentralEntity.fromJson(json.decode(login));
try {
PortfolioData? data = await _service.getMFPortfolio(
mobileNo: entity.mobile,
pan: entity.pan,
reqId: entity.reqId,
token: entity.token,
);
if (data != null) {
for (var value in data.data) {
Scheme scheme = value.schemes.first;
final companion = MutualFundCompanion(
id: Value(int.parse(scheme.folio)),
fundId: Value(int.parse(scheme.folio)),
name: Value(scheme.schemeName),
description: Value(scheme.brokerName),
amount: Value(double.parse(scheme.costValue)),
units: Value(double.parse(scheme.availableUnits)),
type: const Value(MFType.sip),
period: const Value(SipPeriod.monthly),
investedDate: Value(DateTime.now()),
accountId: const Value(-1),
nav: Value(double.parse(scheme.nav)),
currentValue: Value(double.parse(scheme.currentMktValue)),
gainPercentage: Value(double.parse(scheme.gainLossPercentage)),
);
await MutualFundQuery().insert(companion);
}
savingsCubit.updateMutualFunds(data);
}
} on ServiceError catch (e) {
if (e.code == 401) {
emit(MFLoginExpired());
} else {
emit(MfLoginFailed());
}
}
} else {
emit(MFNotLoggedIn());
}
}
void setupCredentials(MFCentralEntity entity) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
String string = json.encode(entity.toJson());
await prefs.setString('mf_login', string);
init();
}
}
| 0
|
mirrored_repositories/rupiah/lib/view_model/mutual_fund
|
mirrored_repositories/rupiah/lib/view_model/mutual_fund/mf_login/mf_login_state.dart
|
part of 'mf_login_cubit.dart';
@immutable
abstract class MfLoginState {}
class MfLoginInitial extends MfLoginState {}
class MfLoginFailed extends MfLoginState {}
class MFLoginExpired extends MfLoginState {}
class MFNotLoggedIn extends MfLoginState {}
| 0
|
mirrored_repositories/rupiah/lib/view_model
|
mirrored_repositories/rupiah/lib/view_model/settings/settings_state.dart
|
part of 'settings_cubit.dart';
@immutable
abstract class SettingsState {}
class SettingsInitial extends SettingsState {}
class ThemeChanged extends SettingsState {
final Brightness brightness;
ThemeChanged({required this.brightness});
}
| 0
|
mirrored_repositories/rupiah/lib/view_model
|
mirrored_repositories/rupiah/lib/view_model/settings/settings_cubit.dart
|
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
part 'settings_state.dart';
class SettingsCubit extends Cubit<SettingsState> {
SettingsCubit() : super(SettingsInitial());
Brightness brightness = Brightness.light;
init() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
// if (prefs.getBool('isDark') == null) {
// prefs.setBool('isDark', false);
// }
if (prefs.getBool('isDark') ?? false) {
brightness = Brightness.dark;
} else {
brightness = Brightness.light;
}
emit(ThemeChanged(brightness: brightness));
}
void changeBrightness() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
if (brightness == Brightness.light) {
brightness = Brightness.dark;
} else {
brightness = Brightness.light;
}
prefs.setBool('isDark', brightness == Brightness.light ? false : true);
emit(ThemeChanged(brightness: brightness));
}
}
| 0
|
mirrored_repositories/rupiah/lib/view_model
|
mirrored_repositories/rupiah/lib/view_model/savings/savings_cubit.dart
|
import 'package:expense_kit/model/database/database.dart';
import 'package:expense_kit/model/database/tables/mutual_fund.dart';
import 'package:expense_kit/model/entity/mf_central_entity.dart';
import 'package:expense_kit/view_model/dashboard/dashboard_cubit.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
part 'savings_state.dart';
class SavingsCubit extends Cubit<SavingsState> {
final DashboardCubit dashboardCubit;
SavingsCubit({required this.dashboardCubit}) : super(SavingsInitial());
List<MutualFundData> _funds = [];
List<MutualFundData> get funds => _funds;
double mutualFundBalance = 0;
double stockBalance = 0;
double goldBalance = 0;
double epfBalance = 469195;
double realEstateBalance = 0;
double get total =>
mutualFundBalance + stockBalance + goldBalance + epfBalance + realEstateBalance;
double get profit => _funds.fold(
0.0,
(previousValue, element) => previousValue + (element.currentValue ?? 0.0),
);
double get profitPercentage =>
_funds.fold(
0.0,
(previousValue, element) => previousValue + (element.gainPercentage ?? 0.0),
) /
_funds.length;
double get invested => _funds.fold(
0.0,
(previousValue, element) => previousValue + (element.amount),
);
void getFunds() async {
_funds.clear();
_funds = await MutualFundQuery().allMutualFunds();
mutualFundBalance = _funds.fold(
0.0,
(previousValue, element) => previousValue + element.units * (element.nav ?? 0.0),
);
dashboardCubit.update(mutualFundBalance);
emit(FundLoaded());
}
void updateMutualFunds(PortfolioData data) {
mutualFundBalance = data.data.fold(
0.0,
(previousValue, element) =>
previousValue +
double.parse(
element.schemes.first.currentMktValue,
),
);
dashboardCubit.update(mutualFundBalance);
emit(FundLoaded());
}
void deleteFund(MutualFundData data) async {
await MutualFundQuery().delete(data.id);
_funds.removeWhere((element) => element.id == data.id);
emit(FundLoaded());
}
void update(double stocks, double mf) {
mutualFundBalance = mf;
stockBalance = stocks;
dashboardCubit.update(total);
emit(FundLoaded());
}
}
| 0
|
mirrored_repositories/rupiah/lib/view_model
|
mirrored_repositories/rupiah/lib/view_model/savings/savings_state.dart
|
part of 'savings_cubit.dart';
@immutable
abstract class SavingsState {}
class SavingsInitial extends SavingsState {}
class FundLoaded extends SavingsState {}
| 0
|
mirrored_repositories/rupiah/lib
|
mirrored_repositories/rupiah/lib/utils/ui_extensions.dart
|
import 'package:expense_kit/utils/currency_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
extension ValidateEmail on String {
bool isValidEmail() => RegExp(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$').hasMatch(this);
bool isValidPassword() =>
RegExp(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$').hasMatch(this);
String capitalize() {
return isNotEmpty ? '${this[0].toUpperCase()}${substring(1).toLowerCase()}' : '';
}
}
extension NavigationExtension on BuildContext {
TextStyle? body() {
return Theme.of(this).textTheme.bodyLarge?.copyWith();
}
TextStyle? medium() {
return Theme.of(this).textTheme.bodyMedium?.copyWith();
}
TextStyle? mediumBold() {
return Theme.of(this).textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.bold,
);
}
TextStyle? small() {
return Theme.of(this).textTheme.bodySmall?.copyWith();
}
TextStyle? smallBold() {
return Theme.of(this).textTheme.bodySmall?.copyWith(
fontWeight: FontWeight.bold,
);
}
TextStyle? smaller() {
return Theme.of(this).textTheme.bodySmall?.copyWith(
fontSize: 12,
);
}
TextStyle? hintText() {
return Theme.of(this).textTheme.bodySmall?.copyWith(
fontSize: 14,
color: Colors.grey,
);
}
TextStyle? smallerBold() {
return Theme.of(this).textTheme.bodySmall?.copyWith(
fontSize: 12,
fontWeight: FontWeight.bold,
);
}
TextStyle? boldBody() {
return Theme.of(this).textTheme.bodyLarge?.copyWith(
fontWeight: FontWeight.bold,
);
}
TextStyle? titleLarge() {
return Theme.of(this).textTheme.titleLarge;
}
TextStyle? titleLargeBold() {
return Theme.of(this).textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.bold,
);
}
TextStyle? titleMedium() {
return Theme.of(this).textTheme.titleMedium?.copyWith();
}
TextStyle? titleSmall() {
return Theme.of(this).textTheme.titleSmall?.copyWith();
}
void hideKeyboard() {
FocusScope.of(this).unfocus();
}
}
extension UIExtensionOnContext on BuildContext {
double get height => MediaQuery.of(this).size.height;
double get width => MediaQuery.of(this).size.width;
bool get isTab => MediaQuery.of(this).size.width > 600;
// this height is based on the device height and given value and this will auto adjust based on the device size
double dynamicHeight(double value) => height * value;
}
extension TextWidget on String {
Text toBody() => Text(this);
}
extension ListnerExtension on Widget {
BlocListener listener(
BuildContext context,
BlocWidgetListener listener,
) {
return BlocListener(
bloc: context.read(),
listener: listener,
child: this,
);
}
BlocBuilder update(
Cubit cubit,
) {
return BlocBuilder(
bloc: cubit,
builder: (context, state) => this,
);
}
}
extension SizeExtension on double {
SizedBox width() => SizedBox(
width: this,
);
SizedBox height() => SizedBox(
height: this,
);
String toCurrency() {
String locale = 'en_IN';
if (this > 0 && this < 100000) {
locale = 'en_US';
}
return NumberFormat.compactCurrency(
symbol: '$currencySymbol ',
locale: locale,
decimalDigits: 2,
).format(
this,
);
}
}
| 0
|
mirrored_repositories/rupiah/lib
|
mirrored_repositories/rupiah/lib/utils/currency_utils.dart
|
import 'package:currency_text_input_formatter/currency_text_input_formatter.dart';
class CurrencyUtils {
static String currencySymbol = '₹';
static CurrencyTextInputFormatter formatter = CurrencyTextInputFormatter(
symbol: '$currencySymbol ',
locale: 'en_IN',
decimalDigits: 2,
);
}
String currencySymbol = '₹';
final CurrencyTextInputFormatter formatter = CurrencyTextInputFormatter(
symbol: '$currencySymbol ',
locale: 'en_IN',
decimalDigits: 2,
);
| 0
|
mirrored_repositories/rupiah
|
mirrored_repositories/rupiah/test/widget_test.dart
|
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:expense_kit/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0
|
mirrored_repositories/rupiah/plugin/pdf_reader
|
mirrored_repositories/rupiah/plugin/pdf_reader/lib/pdf_text.dart
|
import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pdf_text/client_provider.dart';
const MethodChannel _CHANNEL = const MethodChannel('pdf_text');
const String _TEMP_DIR_NAME = ".flutter_pdf_text";
/// Class representing a PDF document.
/// In order to create a new [PDFDoc] instance, one of these static methods has
/// to be used: [PDFDoc.fromFile], [PDFDoc.fromPath], [PDFDoc.fromURL].
class PDFDoc {
late File _file;
late PDFDocInfo _info;
late List<PDFPage> _pages;
late String _password;
PDFDoc._internal();
/// Creates a [PDFDoc] object with a [File] instance.
/// Optionally, takes a [password] for encrypted PDF documents.
static Future<PDFDoc> fromFile(File file, {String password = ""}) async {
var doc = PDFDoc._internal();
doc._password = password;
doc._file = file;
late Map data;
try {
data = await _CHANNEL
.invokeMethod('initDoc', {"path": file.path, "password": password});
} on Exception catch (e) {
return Future.error(e);
}
doc._pages = List.generate(data["length"], (i) => PDFPage._fromDoc(doc, i));
doc._info = PDFDocInfo._fromMap(data["info"]);
return doc;
}
/// Creates a [PDFDoc] object with a file path.
/// Optionally, takes a [password] for encrypted PDF documents.
static Future<PDFDoc> fromPath(String path, {String password = ""}) async {
return await fromFile(File(path), password: password);
}
/// Creates a [PDFDoc] object with a URL.
/// Optionally, takes a [password] for encrypted PDF documents.
/// It downloads the PDF file located in the given URL and saves it
/// in the app's temporary directory.
static Future<PDFDoc> fromURL(String url, {String password = ""}) async {
File file;
try {
String tempDirPath = (await getTemporaryDirectory()).path;
String filePath = join(tempDirPath, _TEMP_DIR_NAME,
url.split("/").last.split(".").first + ".pdf");
file = File(filePath);
file.createSync(recursive: true);
file.writeAsBytesSync(
(await ClientProvider().client.get(Uri.parse(url))).bodyBytes);
} on Exception catch (e) {
return Future.error(e);
}
return await fromFile(file, password: password);
}
/// Gets the page of the document at the given page number.
PDFPage pageAt(int pageNumber) => _pages[pageNumber - 1];
/// Gets the pages of this document.
/// The pages indexes start at 0, but the first page has number 1.
/// Therefore, if you need to access the 5th page, you will do:
/// var page = doc.pages[4]
/// print(page.number) -> 5
List<PDFPage> get pages => _pages;
/// Gets the number of pages of this document.
int get length => _pages.length;
/// Gets the information of this document.
PDFDocInfo get info => _info;
/// Gets the entire text content of the document.
Future<String> get text async {
// Collecting missing pages
List<int> missingPagesNumbers = [];
_pages.forEach((page) {
if (page._text == null) {
missingPagesNumbers.add(page.number);
}
});
late List<String> missingPagesTexts;
// Reading missing pages, if any exists
if (missingPagesNumbers.isNotEmpty) {
try {
missingPagesTexts =
List<String>.from(await (_CHANNEL.invokeMethod('getDocText', {
"path": _file.path,
"missingPagesNumbers": missingPagesNumbers,
"password": _password
})));
} on Exception catch (e) {
return Future.error(e);
}
}
// Populating missing pages
for (var i = 0; i < missingPagesNumbers.length; i++) {
pageAt(missingPagesNumbers[i])._text = missingPagesTexts[i];
}
/// Returning the entire text, concatenating all pages
return _pages.fold<String>("", (pv, page) => "$pv${page._text}");
}
/// Deletes the file related to this [PDFDoc].
/// Throws an exception if the [FileSystemEntity] cannot be deleted.
void deleteFile() {
if (_file.existsSync()) {
_file.deleteSync();
}
}
/// Deletes all the files of the documents that have been imported
/// from outside the local file system (e.g. using [fromURL]).
static Future deleteAllExternalFiles() async {
try {
String tempDirPath = (await getTemporaryDirectory()).path;
Directory dir = Directory(join(tempDirPath, _TEMP_DIR_NAME));
if (dir.existsSync()) {
dir.deleteSync(recursive: true);
}
} catch (e) {
return Future.error(e);
}
}
}
/// Class representing a PDF document page.
/// It needs not to be directly instantiated, instances will be automatically
/// created by the [PDFDoc] class.
class PDFPage {
late PDFDoc _parentDoc;
late int _number;
String? _text;
PDFPage._fromDoc(PDFDoc parentDoc, int number) {
_parentDoc = parentDoc;
_number = number;
}
/// Gets the text of this page.
/// The text retrieval is lazy. So the text of a page is only loaded when
/// it is requested for the first time.
Future<String> get text async {
// Loading the text
if (_text == null) {
try {
_text = await _CHANNEL.invokeMethod('getDocPageText', {
"path": _parentDoc._file.path,
"number": number,
"password": _parentDoc._password
});
} on Exception catch (e) {
return Future.error(e);
}
}
return _text!;
}
/// Gets the page number.
int get number => _number + 1;
}
/// Class representing the information of a PDF document.
/// It needs not to be directly instantiated, instances will be automatically
/// created by the [PDFDoc] class.
class PDFDocInfo {
String? _author;
DateTime? _creationDate;
DateTime? _modificationDate;
String? _creator;
String? _producer;
List<String>? _keywords;
String? _title;
String? _subject;
PDFDocInfo._fromMap(Map data)
: this._internal(
data["author"],
data["creationDate"] != null
? DateTime.tryParse(data["creationDate"])
: null,
data["modificationDate"] != null
? DateTime.tryParse(data["modificationDate"])
: null,
data["creator"],
data["producer"],
data["keywords"] != null
? List<String>.from(data["keywords"])
: null,
data["title"],
data["subject"]);
PDFDocInfo._internal(
this._author,
this._creationDate,
this._modificationDate,
this._creator,
this._producer,
this._keywords,
this._title,
this._subject);
/// Gets the author of the document. This contains the original string of the
/// authors contained in the document. Therefore there might be multiple
/// authors separated by comma. Returns null if no author exists.
String? get author => _author;
/// Gets the list of authors of the document. This is inferred by splitting
/// the author string by comma. Returns null if no author exists.
List<String>? get authors {
if (author == null) {
return null;
}
var authorString = author!.replaceAll(";", ",");
authorString = authorString.replaceAll("&", ",");
authorString = authorString.replaceAll("and", ",");
List<String> splitted = authorString.split(",");
List<String> ret = [];
for (var token in splitted) {
var start = 0;
var end = token.length - 1;
while (start < token.length && token[start] == ' ') {
start++;
}
while (end >= 0 && token[end] == ' ') {
end--;
}
if (end - start >= 0) {
ret.add(token.substring(start, end + 1));
}
}
return ret;
}
/// Gets the creation date of the document. Returns null if no creation
/// date exists.
DateTime? get creationDate => _creationDate;
/// Gets the modification date of the document. Returns null if no
/// modification date exists.
DateTime? get modificationDate => _modificationDate;
/// Gets the creator of the document. Returns null if no creator exists.
String? get creator => _creator;
/// Gets the producer of the document. Returns null if no producer exists.
String? get producer => _producer;
/// Gets the list of keywords of the document. Returns null if no keyword exists.
List<String>? get keywords => _keywords;
/// Gets the title of the document. Returns null if no title exists.
String? get title => _title;
/// Gets the subject of the document. Returns null if no subject exists.
String? get subject => _subject;
}
| 0
|
mirrored_repositories/rupiah/plugin/pdf_reader
|
mirrored_repositories/rupiah/plugin/pdf_reader/lib/client_provider.dart
|
import 'package:http/http.dart' show Client;
class ClientProvider {
final Client _client;
static ClientProvider? _instance;
/// defaults to the standard dart http client
ClientProvider._create(Client? client) : this._client = client ?? Client();
factory ClientProvider({Client? client}) =>
_instance ?? (_instance = ClientProvider._create(client));
Client get client => _client;
}
| 0
|
mirrored_repositories/rupiah/plugin/pdf_reader
|
mirrored_repositories/rupiah/plugin/pdf_reader/test/pdf_text_test.dart
|
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
const MethodChannel channel = MethodChannel('pdf_text');
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() {
channel.setMockMethodCallHandler((MethodCall methodCall) async {
return '42';
});
});
tearDown(() {
channel.setMockMethodCallHandler(null);
});
}
| 0
|
mirrored_repositories/Todoinator
|
mirrored_repositories/Todoinator/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:todoinator/app/data/hive_data_store.dart';
import 'package:todoinator/app/modules/home/views/home_view.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:todoinator/app/shared/models/task.dart';
import 'package:flutter/services.dart';
Future<void> main() async{
await Hive.initFlutter();
Hive.registerAdapter<Task>(TaskAdapter());
//open box
var box = await Hive.openBox<Task>('tasks');
//delete
box.values.forEach((task) {
if(task.createdAt.day != DateTime.now().day){
box.delete(task.id);
}
});
runApp(BaseWidget(child: MyApp()));
}
class BaseWidget extends InheritedWidget{
BaseWidget({required this.child}) : super(child:child);
final HiveDataStore dataStore = HiveDataStore();
final Widget child;
static BaseWidget of(BuildContext context){
final base = context.dependOnInheritedWidgetOfExactType<BaseWidget>();
if(base != null){
return base;
}else{
throw StateError('Could not find ancestor widget of type BaseWidget');
}
}
@override
bool updateShouldNotify(covariant InheritedWidget oldWidget) {
return false;
}
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: Colors.white,
systemNavigationBarColor: Colors.black,
systemNavigationBarIconBrightness: Brightness.light,
// statusBarBrightness: Brightness.light,
statusBarIconBrightness: Brightness.dark,
));
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Todoinator',
theme: ThemeData(
primarySwatch: Colors.blue,
appBarTheme: AppBarTheme(elevation: 0.0,
backgroundColor: Colors.white,
iconTheme: IconThemeData(color: Colors.black))
),
home: HomeView(),
);
}
}
| 0
|
mirrored_repositories/Todoinator/lib/app/shared
|
mirrored_repositories/Todoinator/lib/app/shared/models/task.dart
|
import 'package:uuid/uuid.dart';
import 'package:hive/hive.dart';
part 'task.g.dart';
@HiveType(typeId: 0)
class Task extends HiveObject{
Task({required this.id, required this.name,required this.createdAt,required this.isCompleted});
factory Task.create({required String name, DateTime? createdAt }) =>
Task(id: Uuid().v1(),
name: name,
createdAt: createdAt ?? DateTime.now(),
isCompleted: false);
@HiveField(0)
final String id;
@HiveField(1)
String name;
@HiveField(2)
final DateTime createdAt;
@HiveField(3)
bool isCompleted;
}
| 0
|
mirrored_repositories/Todoinator/lib/app/shared
|
mirrored_repositories/Todoinator/lib/app/shared/models/task.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'task.dart';
// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************
class TaskAdapter extends TypeAdapter<Task> {
@override
final int typeId = 0;
@override
Task read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int, dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return Task(
id: fields[0] as String,
name: fields[1] as String,
createdAt: fields[2] as DateTime,
isCompleted: fields[3] as bool,
);
}
@override
void write(BinaryWriter writer, Task obj) {
writer
..writeByte(4)
..writeByte(0)
..write(obj.id)
..writeByte(1)
..write(obj.name)
..writeByte(2)
..write(obj.createdAt)
..writeByte(3)
..write(obj.isCompleted);
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is TaskAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}
| 0
|
mirrored_repositories/Todoinator/lib/app/modules/home
|
mirrored_repositories/Todoinator/lib/app/modules/home/views/home_view.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:todoinator/app/modules/home/views/setting.dart';
import 'package:todoinator/app/modules/home/widgets/taskWidget.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:todoinator/app/shared/models/task.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
//import 'package:flutter_gradient_colors/flutter_gradient_colors.dart';
import 'package:todoinator/main.dart';
class HomeView extends StatefulWidget {
const HomeView({Key? key}) : super(key: key);
@override
_HomeViewState createState() => _HomeViewState();
}
class _HomeViewState extends State<HomeView> {
String sValue = '';
final tController = TextEditingController();
@override
Widget build(BuildContext context) {
final base = BaseWidget.of(context);
//final box = base.dataStore.box;
return ValueListenableBuilder(
valueListenable: base.dataStore.listenToTasks(),
builder: (context, Box<Task> box, Widget? child) {
var tasks = box.values.toList();
tasks.sort((a, b) => a.createdAt.compareTo(b.createdAt));
return SafeArea(
child: Scaffold(
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
floatingActionButton: FloatingActionButton(
child: Icon(FontAwesomeIcons.plus),
backgroundColor: Colors.blueAccent,
onPressed: () {
showModalBottomSheet(
context: context,
builder: (context) {
return Container(
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom),
margin: EdgeInsets.symmetric(horizontal: 16),
child: ListTile(
title: TextField(
controller: tController,
// controller: _controller,
decoration: InputDecoration(
suffixIcon: IconButton(
icon: Icon(
Icons.check,
),
onPressed: () {
sValue = tController.text;
print(tController.text);
showCupertinoDialog(
context: context,
builder: (context) {
return CupertinoAlertDialog(
content: Text(tController.text),
actions: [
CupertinoButton(
child: Text('ok'),
onPressed: () {
Navigator.pop(context);
Navigator.pop(context);
DatePicker.showTimePicker(
context,
showSecondsColumn:
false,
showTitleActions:
true,
// minTime: DateTime.now(),
//maxTime: DateTime(2019, 6, 7),
onConfirm: (date) {
print('confirm $date');
if (sValue.isNotEmpty) {
var task =
Task.create(
name: sValue,
createdAt:
date);
base.dataStore
.addTask(
task: task);
tController.clear();
}
},
currentTime:
DateTime.now());
})
],
);
});
},
),
border: InputBorder.none,
hintText: 'Enter task name'),
onSubmitted: (value) {
Navigator.pop(context);
DatePicker.showTimePicker(context,
showSecondsColumn: false,
showTitleActions: true,
// minTime: DateTime.now(),
//maxTime: DateTime(2019, 6, 7),
onConfirm: (date) {
print('confirm $date');
if (value.isNotEmpty) {
var task = Task.create(
name: value, createdAt: date);
base.dataStore.addTask(task: task);
}
}, currentTime: DateTime.now());
},
autofocus: true,
),
),
);
});
}),
backgroundColor: Colors.black,
body: Column(
children: [
Container(
height: MediaQuery.of(context).size.height / 7.8,
color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(15.0),
child: Row(
// mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Image.asset(
'assets/icon.png',
scale: 2.7,
),
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
FittedBox(child: Text('Good Morning')),
FittedBox(
child: Text(
'Whats Going on Today ? ',
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 20),
),
),
],
),
Spacer(
flex: 1,
),
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const SettingPage()),
);
},
child: Icon(Icons.settings)),
],
),
),
),
ClipRRect(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(25),
bottomRight: Radius.circular(25)),
child: Container(
color: Colors.white,
height: MediaQuery.of(context).size.height / 1.30,
child: ListView.builder(
itemCount: tasks.length,
itemBuilder: (BuildContext context, int index) {
var task = tasks[index];
return Dismissible(
background: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.delete_outline,
color: Colors.grey,
),
SizedBox(
width: 8,
),
Text('This task was deleted',
style: TextStyle(
color: Colors.grey,
))
],
),
onDismissed: (direction) {
base.dataStore.deleteTask(task: task);
print('hey');
},
key: Key(task.id),
child: TaskWidget(task: tasks[index]));
},
),
),
),
Align(
alignment: Alignment.bottomCenter,
// alignment: Alignment.bottomCenter,
child: Container(
// color: Colors.red,
height: MediaQuery.of(context).size.height * 0.08,
// color: Colors.red,
child: Center(
child: Text(
tasks.length.toString() + ' tasks remaining',
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold),
),
),
),
)
],
),
),
);
},
);
}
}
| 0
|
mirrored_repositories/Todoinator/lib/app/modules/home
|
mirrored_repositories/Todoinator/lib/app/modules/home/views/about.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class AboutPage extends StatelessWidget {
const AboutPage({ Key? key }) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
elevation: 0,
leading: GestureDetector(child: Icon(CupertinoIcons.back,)),
),
body: Column(
),
);
}
}
| 0
|
mirrored_repositories/Todoinator/lib/app/modules/home
|
mirrored_repositories/Todoinator/lib/app/modules/home/views/setting.dart
|
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:todoinator/app/modules/home/views/version.dart';
// import 'about.dart';
//import 'package:giffy_dialog/giffy_dialog.dart';
class SettingPage extends StatelessWidget {
const SettingPage({ Key? key }) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
centerTitle: true,
title: Text('Settings',style: TextStyle(color: Colors.black),),
elevation: 1,
leading: InkWell(child: Icon(CupertinoIcons.back,),onTap:(){
Navigator.pop(context);
} ),
),
body: ListView(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
elevation: 0,
child: Column(
mainAxisAlignment:MainAxisAlignment.center,
children: [
Image.asset('assets/icon.png',scale: 2,),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text('Todoinator',style: TextStyle(fontWeight: FontWeight.bold),),
)
],
),
),
),
Divider(
height: 2,
),
Card(
elevation: 0,
child: ListTile(
leading: Icon(FontAwesomeIcons.question),
title: Text('How to?'),
subtitle: Text('How the app works?'),
iconColor: Colors.blueAccent,
onTap: (){
showDialog(context: context, builder: (BuildContext context)=>CupertinoAlertDialog(
title: Text('How to use the app?'),
content: Text("You can add Daily todo's by cliking the + button"+
" on the bottom right, All the tasks dissapear within 24 Hours "),
actions: [
CupertinoDialogAction(child: Text('Got it'),onPressed: (){
Navigator.of(context).pop();
},)
],
));
}
),
),
// ListTile(
// leading: Icon(FontAwesomeIcons.fileAlt),
// title: Text('Terms & Conditions'),
// subtitle: Text('Privacy & terms'),
// iconColor: Colors.blueAccent,
// ),
ListTile(
leading: Icon(FontAwesomeIcons.codeBranch),
title: Text('Version'),
subtitle: Text('Version info'),
iconColor: Colors.blueAccent,
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const VersionPage()),
);
},
)
],
)
);
}
}
| 0
|
mirrored_repositories/Todoinator/lib/app/modules/home
|
mirrored_repositories/Todoinator/lib/app/modules/home/views/version.dart
|
import 'package:flutter/material.dart';
class VersionPage extends StatelessWidget {
const VersionPage({ Key? key }) : super(key: key);
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: Colors.black,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Image.asset('assets/icon.png'),
Text('Todoinator',style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold),),
Text(' ',style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold),),
Text('Version: ',style: TextStyle(color: Colors.white,fontWeight: FontWeight.normal),),
Text('Beta - 1.0.16',style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold),)
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/Todoinator/lib/app/modules/home
|
mirrored_repositories/Todoinator/lib/app/modules/home/widgets/taskWidget.dart
|
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:todoinator/app/shared/models/task.dart';
class TaskWidget extends StatefulWidget {
const TaskWidget({Key? key, required this.task}) : super(key: key);
final Task task;
@override
_TaskWidgetState createState() => _TaskWidgetState();
}
class _TaskWidgetState extends State<TaskWidget> {
TextEditingController taskController = TextEditingController();
@override
void initState() {
super.initState();
taskController.text = widget.task.name;
}
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(.1),
offset: Offset(0, 4),
blurRadius: 10)
]),
child: ListTile(
leading: GestureDetector(
onTap: (){
widget.task.isCompleted =!widget.task.isCompleted;
widget.task.save();
},
child: Container(
decoration: BoxDecoration(
color: widget.task.isCompleted ? Colors.green : Colors.white,
shape: BoxShape.circle,
border: Border.all(color: Colors.grey, width: .8)),
child: Icon(
Icons.check,
color: Colors.white,
),
),
),
title: widget.task.isCompleted
? Text(
taskController.text,
style: TextStyle(
color: Colors.grey,
decoration: TextDecoration.lineThrough),
) : TextField(
controller: taskController,
decoration: InputDecoration(border: InputBorder.none),
onSubmitted: (value){
if(value.isNotEmpty){
widget.task.name = value;
widget.task.save();
}
},
)
,
trailing: Text(
DateFormat('hh:mm a').format(widget.task.createdAt),
style: TextStyle(fontSize: 14, color: Colors.grey),
)),
);
}
}
| 0
|
mirrored_repositories/Todoinator/lib/app
|
mirrored_repositories/Todoinator/lib/app/data/hive_data_store.dart
|
import 'package:flutter/foundation.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:todoinator/app/shared/models/task.dart';
class HiveDataStore {
static const taskBoxName = 'tasks';
final Box<Task> box = Hive.box<Task>(taskBoxName);
Future<void> addTask({required Task task})async{
await box.put(task.id, task);
}
Future<Task?> getTask({required String id})async{
return box.get(id);
}
Future<void> updateTask({required Task task})async{
await task.save();
}
Future<void> deleteTask({required Task task})async{
await task.delete();
}
ValueListenable<Box<Task>> listenToTasks(){
return Hive.box<Task>(taskBoxName).listenable();
}
}
| 0
|
mirrored_repositories/Todoinator
|
mirrored_repositories/Todoinator/test/widget_test.dart
|
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:todoinator/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0
|
mirrored_repositories/Quizeapplication
|
mirrored_repositories/Quizeapplication/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:quizeapplication/Screens/StartQuize.dart';
import 'package:quizeapplication/Screens/QuizePage.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(primarySwatch: Colors.amber, fontFamily: "rabar_21"),
initialRoute: "/",
routes: {
"/": (context) => QuizePage(),
"/QuizStart": (context) => QuizStart()
},
debugShowCheckedModeBanner: false,
);
}
}
| 0
|
mirrored_repositories/Quizeapplication/lib
|
mirrored_repositories/Quizeapplication/lib/Screens/QuizePage.dart
|
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:quizeapplication/Screens/StartQuize.dart';
import 'package:quizeapplication/class/player.dart';
class QuizePage extends StatefulWidget {
const QuizePage({super.key});
@override
State<QuizePage> createState() => _QuizePageState();
}
class _QuizePageState extends State<QuizePage> {
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: Scaffold(
appBar: AppBar(
title: Text("پرسیار و وەلام"),
centerTitle: true,
),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(15.0),
child: Center(
child: Column(
children: [
Image(
image: AssetImage("assets/image/Feb-Business_9.jpg"),
),
TextField(
onChanged: (v) {
Player.name = v;
},
decoration: InputDecoration(
labelText: "ناو",
hintText: " ناوت بنوسە ...",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15))),
),
SizedBox(
height: 15,
),
FloatingActionButton.extended(
onPressed: () {
if (Player.name != "") {
Navigator.of(context)
.pushReplacementNamed("/QuizStart");
} else {
setState(() {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
duration: Duration(seconds: 1),
backgroundColor: Colors.redAccent,
content: Text("تکاییە ناوت داخل بکە")));
});
}
},
label: Text("دەستپێکردن"))
],
),
),
)
],
),
),
);
}
}
| 0
|
mirrored_repositories/Quizeapplication/lib
|
mirrored_repositories/Quizeapplication/lib/Screens/StartQuize.dart
|
import 'dart:async';
import 'dart:ffi';
import 'dart:io';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:quizeapplication/class/Quetions.dart';
import 'package:quizeapplication/class/player.dart';
class QuizStart extends StatefulWidget {
const QuizStart({super.key});
@override
State<QuizStart> createState() => _QuizStartState();
}
class _QuizStartState extends State<QuizStart> {
List Charector = ["A", "B", "C", "D"];
int index_quetion = 7;
ListtOfQuetions quetions = ListtOfQuetions();
Player _player = Player();
int anwer_user = -1;
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: Scaffold(
appBar: AppBar(
title: Text("پرسیارەکان"),
centerTitle: true,
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child:
Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
SizedBox(
height: 5,
),
Text("ناو : " + Player.name,
style: TextStyle(fontFamily: "rabar_22", fontSize: 16)),
Padding(
padding: const EdgeInsets.all(8.0),
child: Divider(),
),
Center(
child: Text(
"پرسیاری : " + (index_quetion + 1).toString(),
style: TextStyle(fontSize: 20),
),
),
Expanded(
child: Container(
child: Column(
children: [
Row(
children: [
SizedBox(
width: 8,
),
// Text(
// (index_quetion + 1).toString() + ") ",
// style: TextStyle(fontSize: 25),
// ),
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
textAlign: TextAlign.justify,
ListtOfQuetions
.Listt_qutions![index_quetion].Quetion,
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 16),
),
),
)
],
),
Expanded(
child: Container(
child: ListView.builder(
itemCount: 4,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
onTap: () async {
if (anwer_user == -1) {
_player.checquetion(index, index_quetion);
setState(() {
anwer_user = index;
});
ListtOfQuetions.Listt_qutions!.length >
index_quetion + 1
? Timer(Duration(seconds: 1), () {
setState(() {
index_quetion += 1;
anwer_user = -1;
});
})
: _showMyDialog();
}
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8)),
tileColor: Color.fromARGB(226, 255, 193, 7),
title: Text(
ListtOfQuetions.Listt_qutions![index_quetion]
.options_answer[index]
.toString(),
style: TextStyle(fontFamily: "rabar_22"),
),
leading: Container(
width: 35,
height: 35,
child: Center(
child: Text(
Charector[index],
style:
TextStyle(fontWeight: FontWeight.bold),
)),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: color_fun(index)),
),
),
);
},
),
),
),
FloatingActionButton.extended(
onPressed: () {
Navigator.of(context).pushReplacementNamed("/");
},
icon: Icon(Icons.arrow_back_ios_sharp),
label: Text("پەرەی سەرەکی")),
SizedBox(
height: 20,
)
],
),
),
)
]),
),
),
);
}
color_fun(int index) {
if (index == ListtOfQuetions.Listt_qutions![index_quetion].Ansuwer &&
anwer_user != -1) {
return Colors.green;
} else if (index == anwer_user && anwer_user != -1) {
return Color.fromARGB(255, 219, 67, 29);
} else {
return Color.fromARGB(255, 224, 224, 224);
}
}
Future<void> _showMyDialog() async {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: AlertDialog(
title: Text('ئەنجام '),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text(" کۆی وەلامە راستەکانت بریتین لە " +
Player.currect_anwer.length.toString()),
Text("کۆی پرسیارەکان بریتی بوون لە " +
ListtOfQuetions.Listt_qutions!.length.toString()),
],
),
),
actions: <Widget>[
TextButton(
child: Text('دوبارە هەولدان'),
onPressed: () {
Navigator.of(context).pushReplacementNamed("/QuizStart");
},
),
TextButton(
child: Text('داخستن'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
),
);
},
);
}
}
| 0
|
mirrored_repositories/Quizeapplication/lib
|
mirrored_repositories/Quizeapplication/lib/class/player.dart
|
// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:quizeapplication/class/Quetions.dart';
class Player {
static String name = "";
static List<int> currect_anwer = [];
static List<int> uncurrect_anwer = [];
int? total_answer;
checquetion(int yourchois, int idquetion) {
if (yourchois == ListtOfQuetions.Listt_qutions![idquetion].Ansuwer) {
currect_anwer.add(yourchois);
} else {
uncurrect_anwer.add(yourchois);
}
}
}
| 0
|
mirrored_repositories/Quizeapplication/lib
|
mirrored_repositories/Quizeapplication/lib/class/Quetions.dart
|
// ignore_for_file: public_member_api_docs, sort_constructors_first
class Quetions {
int id_qution = 0;
String Quetion;
int Ansuwer;
List<String> options_answer;
Quetions({
required this.Quetion,
required this.Ansuwer,
required this.options_answer,
}) {
id_qution += 1;
}
}
class ListtOfQuetions {
static List<Quetions>? Listt_qutions;
ListtOfQuetions() {
Listt_qutions = [];
Listt_qutions!.add(Quetions(
Quetion: "بۆ یهکهم جار قورئانی پیرۆز لهسهردهمی کێ دا نووسراوه ؟ ",
Ansuwer: 2,
options_answer: [
"لهسهردهمی عمر خطاب ( ڕهزای خوای لێ بێت )",
"لهسهردهمی علی کوری ئەبوطالب ( ڕهزای خوای لێ بێت )",
"لهسهردهمی عوسمان کوڕی عهففان ( ڕهزای خوای لێ بێت )",
"لهسهردهمی ئەبوبەکری سدیق ( ڕهزای خوای لێ بێت )"
]));
Listt_qutions!.add(Quetions(
Quetion: "پێغهمبهر ( صلي الله علية وسلم ) چهند نووسهری ههبوو ؟ ",
Ansuwer: 2,
options_answer: [
"پێغهمبهر ( صلي الله علية وسلم ) بیست و یەک نووسهری ههبوو ",
"پێغهمبهر ( صلي الله علية وسلم ) بیست نووسهری ههبوو ",
"پێغهمبهر ( صلي الله علية وسلم ) بیست و شهش نووسهری ههبوو ",
"پێغهمبهر ( صلي الله علية وسلم ) بیست و نۆ نووسهری ههبوو "
]));
Listt_qutions!.add(Quetions(
Quetion: "کۆکردنهوهی قورئان ی پیرۆز لهساڵی چهندی هجری بوو ؟ ",
Ansuwer: 3,
options_answer: [
"له ساڵی 21ی هجری بوو . ",
"له ساڵی 24ی هجری بوو . ",
"له ساڵی 27ی هجری بوو . ",
"له ساڵی 25ی هجری بوو . "
]));
Listt_qutions!.add(Quetions(
Quetion: "قورئان چهند پیته ؟",
Ansuwer: 2,
options_answer: ["3040750 ", "3040730 ", "3040740 ", "304078"]));
Listt_qutions!.add(Quetions(
Quetion: "قورئانی پیرۆز چهند سورهته ؟ ",
Ansuwer: 0,
options_answer: [
"114 سورهته . ",
"110 سورهته . ",
"111 سورهته . ",
"1112 سورهته ."
]));
Listt_qutions!.add(Quetions(
Quetion: "قورئانی پیرۆز چهند حیزبه ؟ ",
Ansuwer: 0,
options_answer: [
"60 حیزبه ",
"61 حیزبه ",
"55 حیزبه ",
"62 حیزبه "
]));
Listt_qutions!.add(Quetions(
Quetion: "قورئان چهند پیته ؟",
Ansuwer: 2,
options_answer: ["3040750 ", "3040730 ", "3040740 ", "304078"]));
Listt_qutions!.add(Quetions(
Quetion: "قورئان چهند پیته ؟",
Ansuwer: 2,
options_answer: ["3040750 ", "3040730 ", "3040740 ", "304078"]));
}
void add_Quetion(Quetions temp) {
Listt_qutions?.add(temp);
}
size() {
return Listt_qutions == null ? 0 : Listt_qutions!.length;
}
}
| 0
|
mirrored_repositories/Quizeapplication
|
mirrored_repositories/Quizeapplication/test/widget_test.dart
|
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:quizeapplication/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0
|
mirrored_repositories/OpenAI-ChatGPT-Flutter
|
mirrored_repositories/OpenAI-ChatGPT-Flutter/lib/main.dart
|
import 'package:chat_gpt/provider/chat_provider.dart';
import 'package:chat_gpt/provider/models_provider.dart';
import 'package:chat_gpt/utils/app_colors.dart';
import 'package:chat_gpt/view/splash_screen.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => ModelProvider()),
ChangeNotifierProvider(create: (_) => ChatProvider())
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
scaffoldBackgroundColor: AppColors.backgroundColor,
appBarTheme: const AppBarTheme(color: AppColors.cardColor),
),
home: const SplashScreen(),
),
);
}
}
| 0
|
mirrored_repositories/OpenAI-ChatGPT-Flutter/lib
|
mirrored_repositories/OpenAI-ChatGPT-Flutter/lib/view/chat_screen.dart
|
import 'dart:developer';
import 'package:chat_gpt/models/chat_model.dart';
import 'package:chat_gpt/provider/chat_provider.dart';
import 'package:chat_gpt/services/api_services.dart';
import 'package:chat_gpt/services/services.dart';
import 'package:chat_gpt/utils/app_colors.dart';
import 'package:chat_gpt/view/widgets/chat_widget.dart';
import 'package:chat_gpt/view/widgets/custom_text_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:provider/provider.dart';
import '../provider/models_provider.dart';
class ChatScreen extends StatefulWidget {
const ChatScreen({super.key});
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
bool _isTyping = false;
late TextEditingController _textEditingController;
late ScrollController scrollController;
late FocusNode focusNode;
@override
void initState() {
_textEditingController = TextEditingController();
focusNode = FocusNode();
scrollController = ScrollController();
super.initState();
}
@override
void dispose() {
_textEditingController.dispose();
focusNode.dispose();
scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final provider = Provider.of<ModelProvider>(context, listen: false);
final chatProvider = Provider.of<ChatProvider>(context, listen: false);
return Scaffold(
appBar: AppBar(
leading: Padding(
padding: const EdgeInsets.all(8.0),
child: Image.asset("assets/images/openai_logo.jpg"),
),
title: const Text("ChatGPT"),
actions: [
IconButton(
onPressed: () async {
await Services.showBottomSheet(context: context);
},
icon: const Icon(
Icons.more_vert_rounded,
color: Colors.white,
))
],
),
body: Column(
children: [
Flexible(
child: ListView.builder(
itemCount: chatProvider.getchatList.length,
controller: scrollController,
itemBuilder: (context, index) {
return ChatWidget(
msg: chatProvider.getchatList[index].msg,
index: chatProvider.getchatList[index].chatIndex,
);
},
),
),
if (_isTyping) ...[
const SpinKitThreeBounce(
color: Colors.white,
size: 18,
),
],
const SizedBox(height: 15),
Container(
color: AppColors.cardColor,
padding: const EdgeInsets.all(8),
child: Row(
children: [
Expanded(
child: TextField(
focusNode: focusNode,
controller: _textEditingController,
style: const TextStyle(color: Colors.white),
onSubmitted: (value) async {
await sendMessages(
provider: provider, chatProvider: chatProvider);
},
decoration: const InputDecoration.collapsed(
hintText: "How can i help you",
hintStyle: TextStyle(color: Colors.grey)),
),
),
IconButton(
onPressed: () {
sendMessages(
provider: provider, chatProvider: chatProvider);
},
icon: const Icon(
Icons.send,
color: Colors.white,
))
],
),
)
],
),
);
}
void scrollToEnd() {
scrollController.animateTo(
scrollController.position.maxScrollExtent,
duration: const Duration(seconds: 2),
curve: Curves.easeOut,
);
}
Future<void> sendMessages({
required ModelProvider provider,
required ChatProvider chatProvider,
}) async {
if (_isTyping) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: CustomTextWidget(
label: "You can't send multiple messages.",
),
backgroundColor: Colors.red,
),
);
return;
}
if (_textEditingController.text.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: CustomTextWidget(
label: "Please type a message",
),
backgroundColor: Colors.red,
),
);
return;
}
try {
String sendMsg = _textEditingController.text;
setState(() {
_isTyping = true;
chatProvider.addUserMessage(msg: sendMsg);
_textEditingController.clear();
focusNode.unfocus();
});
await chatProvider.botMessage(
msg: sendMsg,
modelID: provider.currentModel,
);
setState(() {});
} catch (e) {
log("error is: $e");
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: CustomTextWidget(
label: e.toString(),
),
backgroundColor: Colors.red,
));
} finally {
setState(() {
scrollToEnd();
_isTyping = false;
});
}
}
}
| 0
|
mirrored_repositories/OpenAI-ChatGPT-Flutter/lib
|
mirrored_repositories/OpenAI-ChatGPT-Flutter/lib/view/splash_screen.dart
|
import 'dart:async';
import 'package:chat_gpt/view/chat_screen.dart';
import 'package:chat_gpt/view/widgets/custom_text_widget.dart';
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';
class SplashScreen extends StatefulWidget {
const SplashScreen({super.key});
@override
State<SplashScreen> createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
super.initState();
Timer(
const Duration(seconds: 3),
() => Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) => const ChatScreen())));
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: Column(
children: [
SizedBox(
height: MediaQuery.of(context).size.height * 0.7,
child: Lottie.asset('assets/animations/robot.json'),
),
const CustomTextWidget(
label: "ChatGPT",
fontSize: 22,
fontWeight: FontWeight.bold,
)
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/OpenAI-ChatGPT-Flutter/lib/view
|
mirrored_repositories/OpenAI-ChatGPT-Flutter/lib/view/widgets/custom_text_widget.dart
|
import 'package:flutter/material.dart';
class CustomTextWidget extends StatelessWidget {
const CustomTextWidget(
{Key? key,
required this.label,
this.fontSize = 16,
this.color,
this.fontWeight})
: super(key: key);
final String label;
final double fontSize;
final Color? color;
final FontWeight? fontWeight;
@override
Widget build(BuildContext context) {
return Text(
label,
// textAlign: TextAlign.justify,
style: TextStyle(
color: color ?? Colors.white,
fontSize: fontSize,
fontWeight: fontWeight ?? FontWeight.w500,
),
);
}
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.