repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/dt_money/lib/src/features/new_transaction | mirrored_repositories/dt_money/lib/src/features/new_transaction/widgets/toggleable_expense_button.dart | import 'package:flutter/material.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import '../../../shared/colors.dart';
class ToggleableExpenseButton extends StatelessWidget {
const ToggleableExpenseButton({
super.key,
required this.isSelected,
required this.onPressed,
});
final bool isSelected;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 58,
child: TextButton(
onPressed: onPressed,
style: TextButton.styleFrom(
backgroundColor: isSelected ? AppColors.redDark : AppColors.gray3,
padding: const EdgeInsets.symmetric(vertical: 16),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(6)),
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
PhosphorIcons.arrowCircleDown,
color: isSelected ? AppColors.white : AppColors.red,
),
const SizedBox(width: 8),
const Text(
'Saída',
style: TextStyle(
fontSize: 16,
color: AppColors.white,
height: 1.6,
),
)
],
),
),
);
}
}
| 0 |
mirrored_repositories/dt_money/lib/src/features/new_transaction | mirrored_repositories/dt_money/lib/src/features/new_transaction/widgets/toggleable_income_button.dart | import 'package:flutter/material.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import '../../../shared/colors.dart';
class ToggleableIncomeButton extends StatelessWidget {
const ToggleableIncomeButton({
super.key,
required this.isSelected,
required this.onPressed,
});
final bool isSelected;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 58,
child: TextButton(
onPressed: onPressed,
style: TextButton.styleFrom(
backgroundColor: isSelected ? AppColors.greenDark : AppColors.gray3,
padding: const EdgeInsets.symmetric(vertical: 16),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(6)),
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
PhosphorIcons.arrowCircleUp,
color: isSelected ? AppColors.white : AppColors.greenLight,
),
const SizedBox(width: 8),
const Text(
'Entrada',
style: TextStyle(
fontSize: 16,
color: AppColors.white,
height: 1.6,
),
)
],
),
),
);
}
}
| 0 |
mirrored_repositories/dt_money/lib/src/features/new_transaction | mirrored_repositories/dt_money/lib/src/features/new_transaction/widgets/new_transaction_header.dart | import 'package:flutter/material.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import '../../../shared/colors.dart';
class NewTransactionHeader extends StatelessWidget {
const NewTransactionHeader({super.key});
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Nova transação',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
height: 1.6,
color: AppColors.white,
),
),
SizedBox(
height: 24,
width: 24,
child: IconButton(
onPressed: () => Navigator.pop(context),
padding: EdgeInsets.zero,
icon: const Icon(PhosphorIcons.x, color: AppColors.gray5),
),
),
],
);
}
}
| 0 |
mirrored_repositories/dt_money/lib/src/features/new_transaction | mirrored_repositories/dt_money/lib/src/features/new_transaction/widgets/toggleable_buttons_row.dart | import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../notifiers/transaction_type_notifier.dart';
import 'toggleable_expense_button.dart';
import 'toggleable_income_button.dart';
class ToggleableButtonsRow extends StatelessWidget {
const ToggleableButtonsRow({
super.key,
required this.transactionTypeNotifier,
required this.setIncome,
required this.setExpense,
});
final ValueListenable<ToggleableButtonsState> transactionTypeNotifier;
final VoidCallback setIncome;
final VoidCallback setExpense;
@override
Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable: transactionTypeNotifier,
builder: (_, type, __) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: [
Expanded(
child: ToggleableIncomeButton(
isSelected: type == ToggleableButtonsState.income,
onPressed: setIncome,
),
),
const SizedBox(width: 8),
Expanded(
child: ToggleableExpenseButton(
isSelected: type == ToggleableButtonsState.expense,
onPressed: setExpense,
),
),
],
);
},
);
}
}
| 0 |
mirrored_repositories/dt_money/lib/src/features | mirrored_repositories/dt_money/lib/src/features/home/home_page.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../shared/colors.dart';
import 'widgets/dashboard.dart';
import 'widgets/home_app_bar.dart';
import 'widgets/made_with_love.dart';
import 'widgets/new_transaction_fab.dart';
import 'widgets/transactions_list.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final scrollController = ScrollController();
bool isFABVisible = false;
@override
void initState() {
super.initState();
scrollController.addListener(_onScroll);
}
_onScroll() {
if (scrollController.offset > 120) {
toggleFABVisible(true);
} else {
toggleFABVisible(false);
}
}
toggleFABVisible(bool isVisible) {
if (isFABVisible != isVisible) {
setState(() => isFABVisible = isVisible);
}
}
@override
Widget build(BuildContext context) {
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);
return LayoutBuilder(builder: (context, constraints) {
return Scaffold(
backgroundColor: AppColors.gray2,
extendBodyBehindAppBar: true,
body: ListView(
controller: scrollController,
padding: const EdgeInsets.only(),
children: const [
HomeAppBar(),
Dashboard(),
TransactionsList(),
SizedBox(height: 8),
MadeWithLoveByAlvesLuc()
],
),
floatingActionButton: isFABVisible && constraints.maxWidth < 720
? const NewTransactionFAB()
: null,
);
});
}
}
| 0 |
mirrored_repositories/dt_money/lib/src/features/home | mirrored_repositories/dt_money/lib/src/features/home/widgets/home_app_bar.dart | import 'package:flutter/material.dart';
import '../../../shared/colors.dart';
import '../../../shared/widgets/primary_button.dart';
import '../../new_transaction/new_transaction_dialog.dart';
import '../../new_transaction/new_transaction_sheet.dart';
class HomeAppBar extends StatelessWidget {
const HomeAppBar({super.key});
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, constraints) {
if (constraints.maxWidth > 720) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 24),
height: 200,
color: AppColors.gray1,
alignment: Alignment.center,
child: Container(
constraints: const BoxConstraints(maxWidth: 1120),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Image.asset('assets/images/Logo.png'),
PrimaryButton(
label: 'Nova transação',
buttonSize: ButtonSize.medium,
onPressed: () => _showNewTransactionDialog(context),
),
],
),
),
);
}
return Container(
padding: const EdgeInsets.symmetric(horizontal: 24),
height: 200,
color: AppColors.gray1,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Image.asset('assets/images/Logo.png'),
PrimaryButton(
label: 'Nova transação',
onPressed: () => _showNewTransactionForm(context),
),
],
),
);
});
}
Future<void> _showNewTransactionDialog(context) async {
showDialog(
context: context,
barrierDismissible: true,
barrierColor: const Color.fromRGBO(0, 0, 0, 0.75),
builder: (context) {
return const NewTransactionDialog();
},
);
}
Future<void> _showNewTransactionForm(context) async {
showModalBottomSheet(
isScrollControlled: true,
context: context,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
backgroundColor: AppColors.gray2,
builder: (context) {
return const NewTransactionSheet();
},
);
}
}
| 0 |
mirrored_repositories/dt_money/lib/src/features/home | mirrored_repositories/dt_money/lib/src/features/home/widgets/made_with_love.dart | import 'package:flutter/material.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import 'package:url_launcher/url_launcher.dart';
class MadeWithLoveByAlvesLuc extends StatelessWidget {
const MadeWithLoveByAlvesLuc({super.key});
@override
Widget build(BuildContext context) {
return SafeArea(
bottom: true,
top: false,
child: Center(
child: TextButton(
onPressed: _launchURL,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
mainAxisSize: MainAxisSize.min,
children: const [
Text('Made with 💙 by alvesluc'),
SizedBox(width: 8),
Icon(PhosphorIcons.githubLogo)
],
),
),
),
),
);
}
_launchURL() async {
final githubUrl = Uri.parse('https://github.com/alvesluc');
if (await canLaunchUrl(githubUrl)) {
await launchUrl(githubUrl);
} else {
throw 'Could not launch $githubUrl';
}
}
}
| 0 |
mirrored_repositories/dt_money/lib/src/features/home | mirrored_repositories/dt_money/lib/src/features/home/widgets/expenses_card.dart | import 'package:dt_money/src/shared/extensions.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import '../../../shared/colors.dart';
class ExpensesCard extends StatelessWidget {
const ExpensesCard({
super.key,
required this.totalExpenses,
this.isMobile = true,
this.lastEntry,
});
final double totalExpenses;
final DateTime? lastEntry;
final bool isMobile;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.only(
left: 32,
top: 24,
right: 24,
bottom: 24,
),
width: 280,
decoration: BoxDecoration(
color: AppColors.gray4,
borderRadius: BorderRadius.circular(6),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Saídas',
style: TextStyle(
fontSize: isMobile ? 16 : 20,
color: AppColors.gray6,
height: 1.6,
),
),
const Icon(
PhosphorIcons.arrowCircleDown,
color: AppColors.red,
size: 32,
)
],
),
const SizedBox(height: 14),
Text(
'R\$ ${totalExpenses.toCurrency()}',
style: TextStyle(
height: 1.4,
fontSize: isMobile ? 24 : 32,
fontWeight: FontWeight.bold,
color: AppColors.gray7,
),
),
const SizedBox(height: 2),
Text(
lastEntry != null ? 'Última saída: ${ DateFormat('dd/MM/y').format(lastEntry!)}': '',
style: const TextStyle(
color: AppColors.gray5,
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/dt_money/lib/src/features/home | mirrored_repositories/dt_money/lib/src/features/home/widgets/total_balance_card.dart | import 'package:dt_money/src/shared/extensions.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import '../../../shared/colors.dart';
class TotalBalanceCard extends StatelessWidget {
const TotalBalanceCard({
super.key,
required this.totalBalance,
this.isMobile = true,
this.firstEntry,
this.lastEntry,
});
final double totalBalance;
final DateTime? firstEntry;
final DateTime? lastEntry;
final bool isMobile;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.only(
left: 32,
top: 24,
right: 24,
bottom: 24,
),
width: 280,
decoration: BoxDecoration(
color: AppColors.greenDark,
borderRadius: BorderRadius.circular(6),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Total',
style: TextStyle(
fontSize: isMobile ? 16 : 20,
color: AppColors.gray6,
height: 1.6,
),
),
const Icon(
PhosphorIcons.currencyDollar,
color: AppColors.white,
size: 32,
)
],
),
const SizedBox(height: 14),
Text(
'R\$ ${totalBalance.toCurrency()}',
style: TextStyle(
height: 1.4,
fontSize: isMobile ? 24 : 32,
fontWeight: FontWeight.bold,
color: AppColors.gray7,
),
),
const SizedBox(height: 2),
Text(
firstEntry == null || lastEntry == null
? ''
: 'De ${DateFormat('dd/MM/y').format(firstEntry!)} até ${DateFormat('dd/MM/y').format(lastEntry!)}',
// lastEntry != null ? 'Última saída: ${ DateFormat('dd/MM/y').format(lastEntry!)}': '',
style: const TextStyle(
color: AppColors.gray6,
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/dt_money/lib/src/features/home | mirrored_repositories/dt_money/lib/src/features/home/widgets/transaction.dart | import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import '../../../shared/colors.dart';
import '../../../shared/extensions.dart';
import '../models/transaction.dart';
class Transaction extends StatelessWidget {
const Transaction({
super.key,
required this.transaction,
this.isMobile = true,
});
final TransactionModel transaction;
final bool isMobile;
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.symmetric(horizontal: 24),
padding: isMobile
? const EdgeInsets.all(20)
: const EdgeInsets.symmetric(vertical: 20, horizontal: 32),
decoration: BoxDecoration(
color: AppColors.gray3,
borderRadius: BorderRadius.circular(6),
),
child: Builder(
builder: (context) {
if (isMobile) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
transaction.description,
style: const TextStyle(
color: AppColors.gray6,
fontSize: 16,
height: 1.6,
),
),
Builder(builder: (_) {
switch (transaction.type) {
case TransactionType.income:
return Text(
'R\$ ${transaction.value.toCurrency()}',
style: const TextStyle(
color: AppColors.greenLight,
fontSize: 20,
height: 1.6,
fontWeight: FontWeight.bold,
),
);
case TransactionType.expense:
return Text(
'- R\$ ${transaction.value.toCurrency()}',
style: const TextStyle(
color: AppColors.red,
fontSize: 20,
height: 1.6,
fontWeight: FontWeight.bold,
),
);
}
}),
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
const Icon(
PhosphorIcons.tagSimple,
color: AppColors.gray5,
size: 16,
),
const SizedBox(width: 4),
Text(
transaction.category,
style: const TextStyle(
fontSize: 16,
color: AppColors.gray5,
height: 1.6,
),
)
],
),
Row(
children: [
const Icon(
PhosphorIcons.calendarBlank,
color: AppColors.gray5,
size: 16,
),
const SizedBox(width: 4),
Text(
DateFormat('dd/MM/y').format(transaction.entryDate),
style: const TextStyle(
fontSize: 16,
color: AppColors.gray5,
height: 1.6,
),
)
],
),
],
)
],
);
}
return Table(
columnWidths: const <int, TableColumnWidth>{
0: FlexColumnWidth(),
1: FixedColumnWidth(200),
2: FixedColumnWidth(240),
3: IntrinsicColumnWidth(),
},
defaultVerticalAlignment: TableCellVerticalAlignment.middle,
children: [
TableRow(
children: [
Text(
transaction.description,
style: const TextStyle(
color: AppColors.gray6,
fontSize: 16,
height: 1.6,
),
),
Builder(builder: (_) {
switch (transaction.type) {
case TransactionType.income:
return Text(
'R\$ ${transaction.value.toCurrency()}',
style: const TextStyle(
color: AppColors.greenLight,
fontSize: 16,
height: 1.6,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.start,
);
case TransactionType.expense:
return Text(
'- R\$ ${transaction.value.toCurrency()}',
style: const TextStyle(
color: AppColors.red,
fontSize: 16,
height: 1.6,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.start,
);
}
}),
Row(
children: [
const Icon(
PhosphorIcons.tagSimple,
color: AppColors.gray5,
size: 16,
),
const SizedBox(width: 4),
Text(
transaction.category,
style: const TextStyle(
fontSize: 16,
color: AppColors.gray5,
height: 1.6,
),
)
],
),
Row(
children: [
const Icon(
PhosphorIcons.calendarBlank,
color: AppColors.gray5,
size: 16,
),
const SizedBox(width: 4),
Text(
DateFormat('dd/MM/y').format(transaction.entryDate),
style: const TextStyle(
fontSize: 16,
color: AppColors.gray5,
height: 1.6,
),
)
],
),
],
),
],
);
},
));
}
}
| 0 |
mirrored_repositories/dt_money/lib/src/features/home | mirrored_repositories/dt_money/lib/src/features/home/widgets/income_card.dart | import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import '../../../shared/colors.dart';
import '../../../shared/extensions.dart';
class IncomeCard extends StatelessWidget {
const IncomeCard({
super.key,
this.isMobile = true,
required this.totalIncome,
this.lastEntry,
});
final double totalIncome;
final DateTime? lastEntry;
final bool isMobile;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.only(
left: 32,
top: 24,
right: 24,
bottom: 24,
),
width: 280,
decoration: BoxDecoration(
color: AppColors.gray4,
borderRadius: BorderRadius.circular(6),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Entradas',
style: TextStyle(
fontSize: isMobile ? 16 : 20,
color: AppColors.gray6,
height: 1.6,
),
),
const Icon(
PhosphorIcons.arrowCircleUp,
color: AppColors.greenLight,
size: 32,
)
],
),
const SizedBox(height: 14),
Text(
'R\$ ${totalIncome.toCurrency()}',
style: TextStyle(
height: 1.4,
fontSize: isMobile ? 24 : 32,
fontWeight: FontWeight.bold,
color: AppColors.gray7,
),
),
const SizedBox(height: 2),
Text(
lastEntry != null
? 'Última entrada: ${DateFormat('dd/MM/y').format(lastEntry!)}'
: '',
style: const TextStyle(
color: AppColors.gray5,
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/dt_money/lib/src/features/home | mirrored_repositories/dt_money/lib/src/features/home/widgets/search_transactions.dart | import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../providers/transactions_provider.dart';
import '../../../shared/widgets/default_textfield.dart';
class SearchTransactions extends StatefulWidget {
const SearchTransactions({super.key});
@override
State<SearchTransactions> createState() => _SearchTransactionsState();
}
class _SearchTransactionsState extends State<SearchTransactions> {
Timer? _debounce;
_onSearchChanged(String query) {
if (_debounce?.isActive ?? false) _debounce?.cancel();
_debounce = Timer(const Duration(milliseconds: 300), () {
final transactionsStore = context.read<TransactionsStore>();
transactionsStore.searchTransaction(query);
});
}
@override
void dispose() {
_debounce?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Align(
alignment: Alignment.center,
child: LayoutBuilder(
builder: (_, constraints) {
return Container(
height: 48,
constraints: const BoxConstraints(maxWidth: 1168),
padding: const EdgeInsets.symmetric(horizontal: 24),
transform: Matrix4.translationValues(0.0, -12.0, 0.0),
child: DefaultTextField(
hint: 'Busque por uma transação',
onChanged: _onSearchChanged,
),
);
},
));
}
}
| 0 |
mirrored_repositories/dt_money/lib/src/features/home | mirrored_repositories/dt_money/lib/src/features/home/widgets/dashboard.dart | import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../providers/dashboard_provider.dart';
import 'expenses_card.dart';
import 'income_card.dart';
import 'total_balance_card.dart';
class Dashboard extends StatefulWidget {
const Dashboard({super.key});
@override
State<Dashboard> createState() => _DashboardState();
}
class _DashboardState extends State<Dashboard> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<DashboardStore>().getDashboard();
});
}
@override
Widget build(BuildContext context) {
final store = context.watch<DashboardStore>();
final state = store.value;
if (state is SuccessDashboardState) {
return LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth > 920) {
return Center(
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 24),
transform: Matrix4.translationValues(0.0, -48.0, 0.0),
width: 1120,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: [
Expanded(
child: IncomeCard(
totalIncome: state.dashboard.totalIncome,
lastEntry: state.dashboard.lastIncomeDate,
isMobile: false,
),
),
const SizedBox(width: 32),
Expanded(
child: ExpensesCard(
totalExpenses: state.dashboard.totalExpenses,
lastEntry: state.dashboard.lastExpenseDate,
isMobile: false,
),
),
const SizedBox(width: 32),
Expanded(
child: TotalBalanceCard(
totalBalance: state.dashboard.totalBalance,
firstEntry: state.dashboard.firstEntry,
lastEntry: state.dashboard.lastEntry,
isMobile: false,
),
),
],
),
),
);
}
return Container(
height: 150,
transform: Matrix4.translationValues(0.0, -48.0, 0.0),
child: ListView(
padding: const EdgeInsets.symmetric(horizontal: 24),
scrollDirection: Axis.horizontal,
children: [
IncomeCard(
totalIncome: state.dashboard.totalIncome,
lastEntry: state.dashboard.lastIncomeDate,
),
const SizedBox(width: 16),
ExpensesCard(
totalExpenses: state.dashboard.totalExpenses,
lastEntry: state.dashboard.lastExpenseDate,
),
const SizedBox(width: 16),
TotalBalanceCard(
totalBalance: state.dashboard.totalBalance,
firstEntry: state.dashboard.firstEntry,
lastEntry: state.dashboard.lastEntry,
),
],
),
);
},
);
}
return const _DefaultDashboard();
}
}
class _DefaultDashboard extends StatelessWidget {
const _DefaultDashboard();
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth > 920) {
return Center(
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 24),
transform: Matrix4.translationValues(0.0, -48.0, 0.0),
width: 1120,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: const [
Expanded(
child: IncomeCard(totalIncome: 0, isMobile: false),
),
SizedBox(width: 32),
Expanded(
child: ExpensesCard(totalExpenses: 0, isMobile: false),
),
SizedBox(width: 32),
Expanded(
child: TotalBalanceCard(totalBalance: 0, isMobile: false),
),
],
),
),
);
}
return Container(
height: 150,
transform: Matrix4.translationValues(0.0, -48.0, 0.0),
child: ListView(
padding: const EdgeInsets.symmetric(horizontal: 24),
scrollDirection: Axis.horizontal,
children: const [
IncomeCard(totalIncome: 0),
SizedBox(width: 16),
ExpensesCard(totalExpenses: 0),
SizedBox(width: 16),
TotalBalanceCard(totalBalance: 0),
],
),
);
},
);
}
}
| 0 |
mirrored_repositories/dt_money/lib/src/features/home | mirrored_repositories/dt_money/lib/src/features/home/widgets/transactions_list.dart | import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../providers/transactions_provider.dart';
import '../../../shared/extensions.dart';
import '../../../shared/widgets/column_builder.dart';
import 'search_transactions.dart';
import 'transaction.dart';
import 'transactions_header.dart';
class TransactionsList extends StatefulWidget {
const TransactionsList({super.key});
@override
State<TransactionsList> createState() => _TransactionsListState();
}
class _TransactionsListState extends State<TransactionsList> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<TransactionsStore>().getTransactions();
});
}
@override
Widget build(BuildContext context) {
final store = context.watch<TransactionsStore>();
final state = store.value;
if (state is LoadingTransactionsState) {
return const CircularProgressIndicator.adaptive();
}
if (state is ErrorTransactionsState) {
return Text(state.message);
}
if (state is SuccessTransactionsState) {
return Column(
children: [
const TransactionsHeader(),
const SearchTransactions(),
LayoutBuilder(builder: (context, constraints) {
if (constraints.isDesktop) {
if (store.queriedTransactions.isEmpty) {
return Align(
alignment: Alignment.center,
child: Container(
constraints: const BoxConstraints(maxWidth: 1168),
child: ColumnBuilder(
itemCount: state.transactions.length,
itemBuilder: (context, i) {
return Column(
children: [
Transaction(
transaction: state.transactions[i],
isMobile: false,
),
const SizedBox(height: 8),
],
);
},
),
),
);
} else {
return Align(
alignment: Alignment.center,
child: Container(
constraints: const BoxConstraints(maxWidth: 1168),
child: ColumnBuilder(
itemCount: state.queriedTransactions.length,
itemBuilder: (context, i) {
return Column(
children: [
Transaction(
transaction: state.queriedTransactions[i],
isMobile: false,
),
const SizedBox(height: 8),
],
);
},
),
),
);
}
}
if (store.queriedTransactions.isEmpty) {
return ColumnBuilder(
itemCount: state.transactions.length,
verticalDirection: VerticalDirection.up,
itemBuilder: (context, i) {
return Column(
children: [
Transaction(transaction: state.transactions[i]),
const SizedBox(height: 12),
],
);
},
);
} else {
return ColumnBuilder(
itemCount: state.queriedTransactions.length,
verticalDirection: VerticalDirection.up,
itemBuilder: (context, i) {
return Column(
children: [
Transaction(transaction: state.queriedTransactions[i]),
const SizedBox(height: 12),
],
);
},
);
}
}),
],
);
}
return const CircularProgressIndicator.adaptive();
}
}
| 0 |
mirrored_repositories/dt_money/lib/src/features/home | mirrored_repositories/dt_money/lib/src/features/home/widgets/transactions_header.dart | import 'package:flutter/material.dart';
import '../../../shared/colors.dart';
class TransactionsHeader extends StatelessWidget {
const TransactionsHeader({super.key});
@override
Widget build(BuildContext context) {
return Align(
alignment: Alignment.center,
child: Container(
constraints: const BoxConstraints(maxWidth: 1168),
padding: const EdgeInsets.symmetric(horizontal: 24),
transform: Matrix4.translationValues(0.0, -24.0, 0.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: const [
Text(
'Transações',
style: TextStyle(fontSize: 18, color: AppColors.gray6),
),
Text(
'2 itens',
style: TextStyle(fontSize: 16, color: AppColors.gray5),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/dt_money/lib/src/features/home | mirrored_repositories/dt_money/lib/src/features/home/widgets/new_transaction_fab.dart | import 'package:flutter/material.dart';
import 'package:phosphor_flutter/phosphor_flutter.dart';
import '../../../shared/colors.dart';
import '../../new_transaction/new_transaction_sheet.dart';
class NewTransactionFAB extends StatelessWidget {
const NewTransactionFAB({super.key});
@override
Widget build(BuildContext context) {
return FloatingActionButton(
backgroundColor: AppColors.green,
onPressed: () => _showNewTransactionForm(context),
child: const Icon(
PhosphorIcons.plus,
color: AppColors.white,
),
);
}
Future<void> _showNewTransactionForm(context) async {
showModalBottomSheet(
isScrollControlled: true,
context: context,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
backgroundColor: AppColors.gray2,
builder: (context) {
return const NewTransactionSheet();
},
);
}
}
| 0 |
mirrored_repositories/dt_money/lib/src/features/home | mirrored_repositories/dt_money/lib/src/features/home/models/total_expenses.dart | class TotalExpensesModel {
final double value;
final DateTime lastEntryDate;
TotalExpensesModel(
this.value,
this.lastEntryDate,
);
Map<String, dynamic> toMap() {
return <String, dynamic>{
'value': value,
'lastEntryDate': lastEntryDate.millisecondsSinceEpoch,
};
}
factory TotalExpensesModel.fromMap(Map<String, dynamic> map) {
return TotalExpensesModel(
map['value'] as double,
DateTime.fromMillisecondsSinceEpoch(map['lastEntryDate'] as int),
);
}
@override
String toString() =>
'TotalExpensesModel(value: $value, lastEntryDate: $lastEntryDate)';
}
| 0 |
mirrored_repositories/dt_money/lib/src/features/home | mirrored_repositories/dt_money/lib/src/features/home/models/total_income.dart | class TotalIncomeModel {
final double value;
final DateTime lastEntryDate;
TotalIncomeModel(
this.value,
this.lastEntryDate,
);
Map<String, dynamic> toMap() {
return <String, dynamic>{
'value': value,
'lastEntryDate': lastEntryDate.millisecondsSinceEpoch,
};
}
factory TotalIncomeModel.fromMap(Map<String, dynamic> map) {
return TotalIncomeModel(
map['value'] as double,
DateTime.fromMillisecondsSinceEpoch(map['lastEntryDate'] as int),
);
}
@override
String toString() =>
'TotalIncomeModel(value: $value, lastEntryDate: $lastEntryDate)';
}
| 0 |
mirrored_repositories/dt_money/lib/src/features/home | mirrored_repositories/dt_money/lib/src/features/home/models/transaction.dart | import 'dart:convert';
import 'package:intl/intl.dart';
import '../../../shared/extensions.dart';
enum TransactionType {
income('income'),
expense('expense');
const TransactionType(this.value);
final String value;
}
class TransactionModel {
final String description;
final double value;
final String category;
final TransactionType type;
final DateTime entryDate;
TransactionModel({
required this.description,
required this.value,
required this.category,
required this.type,
required this.entryDate,
});
Map<String, dynamic> toMap() {
return <String, dynamic>{
'description': description,
'value': value,
'category': category,
'type': type.value,
'entryDate': entryDate.millisecondsSinceEpoch,
};
}
factory TransactionModel.fromMap(Map<String, dynamic> map) {
return TransactionModel(
description: map['description'] as String,
value: map['value'] as double,
category: map['category'] as String,
type: TransactionType.values.byName(map['type']),
entryDate: DateTime.fromMillisecondsSinceEpoch(map['entryDate'] as int),
);
}
String toJson() => json.encode(toMap());
factory TransactionModel.fromJson(String source) {
return TransactionModel.fromMap(
json.decode(source) as Map<String, dynamic>,
);
}
@override
String toString() {
return 'TransactionModel(description: $description, value: $value, category: $category, type: $type)';
}
String toQuery() {
return '($description ${value.toCurrency()} $category ${DateFormat('dd/MM/y').format(entryDate)})'.toLowerCase();
}
}
| 0 |
mirrored_repositories/dt_money/lib/src/features/home | mirrored_repositories/dt_money/lib/src/features/home/models/dashboard_model.dart | // ignore_for_file: public_member_api_docs, sort_constructors_first
class DashboardModel {
final double totalIncome;
final DateTime? lastIncomeDate;
final double totalExpenses;
final DateTime? lastExpenseDate;
final double totalBalance;
final DateTime? firstEntry;
final DateTime? lastEntry;
DashboardModel(
this.totalIncome,
this.lastIncomeDate,
this.totalExpenses,
this.lastExpenseDate,
this.totalBalance,
this.firstEntry,
this.lastEntry,
);
@override
String toString() {
return 'DashboardModel(totalIncome: $totalIncome, lastIncomeDate: $lastIncomeDate, totalExpenses: $totalExpenses, lastExpenseDate: $lastExpenseDate, totalBalance: $totalBalance, firstEntry: $firstEntry, lastEntry: $lastEntry)';
}
}
| 0 |
mirrored_repositories/dt_money/lib/src/features/home | mirrored_repositories/dt_money/lib/src/features/home/models/total_balance.dart | class TotalBalanceModel {
final double value;
final DateTime periodicityStart;
final DateTime periodicityEnd;
TotalBalanceModel(
this.value,
this.periodicityStart,
this.periodicityEnd,
);
Map<String, dynamic> toMap() {
return <String, dynamic>{
'value': value,
'periodicityStart': periodicityStart.millisecondsSinceEpoch,
'periodicityEnd': periodicityEnd.millisecondsSinceEpoch,
};
}
factory TotalBalanceModel.fromMap(Map<String, dynamic> map) {
return TotalBalanceModel(
map['value'] as double,
DateTime.fromMillisecondsSinceEpoch(map['periodicityStart'] as int),
DateTime.fromMillisecondsSinceEpoch(map['periodicityEnd'] as int),
);
}
@override
String toString() =>
'TotalBalanceModel(value: $value, periodicityStart: $periodicityStart, periodicityEnd: $periodicityEnd)';
}
| 0 |
mirrored_repositories/dt_money/lib/src | mirrored_repositories/dt_money/lib/src/services/local_storage_service.dart | import 'package:dt_money/src/features/home/models/transaction.dart';
abstract class LocalStorageService {
Future<void> addTransaction(TransactionModel transaction);
Future<List<TransactionModel>> getTransactions();
} | 0 |
mirrored_repositories/dt_money/lib/src/services | mirrored_repositories/dt_money/lib/src/services/shared_preferences_service/shared_preferences_service.dart | import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../../features/home/models/transaction.dart';
import '../local_storage_service.dart';
class SharedPreferencesImpl implements LocalStorageService {
@override
Future<List<TransactionModel>> getTransactions() async {
return _getStoredTransactions();
}
@override
Future<void> addTransaction(TransactionModel newTransaction) async {
final sharedPreferences = await SharedPreferences.getInstance();
final transactions = await _getStoredTransactions();
transactions.add(newTransaction);
sharedPreferences.setString('transactions', _toJson(transactions));
}
Future<List<TransactionModel>> _getStoredTransactions() async {
final sharedPreferences = await SharedPreferences.getInstance();
final storedTransactionsJson = sharedPreferences.getString('transactions');
final transactions = <TransactionModel>[];
if (storedTransactionsJson != null) {
final storedTransactions = jsonDecode(storedTransactionsJson);
for (var transactionJson in storedTransactions) {
transactions.add(TransactionModel.fromJson(transactionJson));
}
}
return transactions;
}
String _toJson(List<TransactionModel> transactions) {
return jsonEncode(List.from(transactions.map((e) => e.toJson())));
}
}
| 0 |
mirrored_repositories/dt_money/lib/src | mirrored_repositories/dt_money/lib/src/providers/transactions_provider.dart | import 'package:flutter/material.dart';
import '../features/home/models/transaction.dart';
import '../services/local_storage_service.dart';
class TransactionsStore extends ValueNotifier<TransactionsState> {
TransactionsStore(this._transactionsService) : super(InitialTransactionsState());
final TransactionsService _transactionsService;
late List<TransactionModel> _localTransactions;
final queriedTransactions = <TransactionModel>[];
Future<void> getTransactions() async {
value = LoadingTransactionsState();
try {
final transactions = await _transactionsService.getTransactions();
value = SuccessTransactionsState(transactions, queriedTransactions);
_localTransactions = transactions;
} catch (e) {
value = ErrorTransactionsState(e.toString());
}
}
Future<void> addTransaction(TransactionModel transaction) async {
value = LoadingTransactionsState();
try {
await _transactionsService.addTransaction(transaction);
_localTransactions.add(transaction);
value = SuccessTransactionsState(_localTransactions, queriedTransactions);
} catch (e) {
value = ErrorTransactionsState(e.toString());
}
}
void searchTransaction(String query) {
queriedTransactions.clear();
for (var transaction in _localTransactions) {
if (transaction.toQuery().contains(query.toLowerCase())) {
queriedTransactions.add(transaction);
}
}
value = SuccessTransactionsState(_localTransactions, queriedTransactions);
}
}
class TransactionsService {
TransactionsService(this._localStorage);
final LocalStorageService _localStorage;
Future<List<TransactionModel>> getTransactions() async {
return _localStorage.getTransactions();
}
Future<void> addTransaction(TransactionModel transaction) async {
if (_isTransactionValid(transaction)) {
await _localStorage.addTransaction(transaction);
}
}
bool _isTransactionValid(TransactionModel transaction) {
return transaction.description.isNotEmpty &&
transaction.value > 0 &&
transaction.category.isNotEmpty;
}
}
abstract class TransactionsState {}
class InitialTransactionsState extends TransactionsState {}
class LoadingTransactionsState extends TransactionsState {}
class SuccessTransactionsState extends TransactionsState {
final List<TransactionModel> transactions;
final List<TransactionModel> queriedTransactions;
SuccessTransactionsState(this.transactions, this.queriedTransactions);
}
class ErrorTransactionsState extends TransactionsState {
final String message;
ErrorTransactionsState(this.message);
}
| 0 |
mirrored_repositories/dt_money/lib/src | mirrored_repositories/dt_money/lib/src/providers/dashboard_provider.dart | import 'package:flutter/material.dart';
import '../features/home/models/dashboard_model.dart';
import '../features/home/models/transaction.dart';
import '../services/local_storage_service.dart';
class DashboardStore extends ValueNotifier<DashboardState> {
DashboardStore(this._transactionsService) : super(InitialDashboardState());
final DashboardService _transactionsService;
double _totalIncome = 0;
DateTime? _lastIncomeDate;
double _totalExpenses = 0;
DateTime? _lastExpenseDate;
double _totalBalance = 0;
DateTime? _firstEntryDate;
DateTime? _lastEntryDate;
Future<void> getDashboard() async {
value = LoadingDashboardState();
try {
final transactions = await _transactionsService.getTransactions();
for (var transaction in transactions) {
sortTransactionValue(transaction);
}
value = SuccessDashboardState(
DashboardModel(
_totalIncome,
_lastIncomeDate,
_totalExpenses,
_lastExpenseDate,
_totalBalance,
_firstEntryDate,
_lastEntryDate,
),
);
} catch (e) {
value = ErrorDashboardState(e.toString());
}
}
Future<void> updateDashboard(TransactionModel transaction) async {
sortTransactionValue(transaction);
value = SuccessDashboardState(
DashboardModel(
_totalIncome,
_lastIncomeDate,
_totalExpenses,
_lastExpenseDate,
_totalBalance,
_firstEntryDate,
_lastEntryDate,
),
);
}
void sortTransactionValue(TransactionModel transaction) {
switch (transaction.type) {
case TransactionType.income:
_handleIncomeValues(transaction);
break;
case TransactionType.expense:
_handleExpenseValues(transaction);
break;
}
_totalBalance = _totalIncome - _totalExpenses;
_firstEntryDate = _getFirstEntry(_firstEntryDate, transaction.entryDate);
_lastEntryDate = _getLatestEntry(_lastIncomeDate, _lastExpenseDate);
}
void _handleIncomeValues(TransactionModel transaction) {
_totalIncome += transaction.value;
_lastIncomeDate = _getLatestEntry(_lastIncomeDate, transaction.entryDate);
}
void _handleExpenseValues(TransactionModel transaction) {
_totalExpenses += transaction.value;
_lastExpenseDate = _getLatestEntry(_lastExpenseDate, transaction.entryDate);
}
DateTime _getFirstEntry(DateTime? firstEntry, DateTime compareDate) {
if (firstEntry == null) return compareDate;
if (firstEntry.isBefore(compareDate)) return firstEntry;
return compareDate;
}
DateTime? _getLatestEntry(
DateTime? lastIncomeDate,
DateTime? compareDate,
) {
if (lastIncomeDate == null && compareDate == null) return null;
if (compareDate == null) return null;
if (lastIncomeDate == null) return compareDate;
if (lastIncomeDate.isAfter(compareDate)) return lastIncomeDate;
return compareDate;
}
}
class DashboardService {
DashboardService(this._localStorage);
final LocalStorageService _localStorage;
Future<List<TransactionModel>> getTransactions() async {
return _localStorage.getTransactions();
}
}
abstract class DashboardState {}
class InitialDashboardState extends DashboardState {}
class LoadingDashboardState extends DashboardState {}
class SuccessDashboardState extends DashboardState {
final DashboardModel dashboard;
SuccessDashboardState(this.dashboard);
}
class ErrorDashboardState extends DashboardState {
final String message;
ErrorDashboardState(this.message);
}
| 0 |
mirrored_repositories/dt_money/test/src/features | mirrored_repositories/dt_money/test/src/features/home/new_transaction_controller_test.dart | import 'package:dt_money/src/features/home/models/transaction.dart';
import 'package:dt_money/src/features/home/new_transaction_controller.dart';
import 'package:dt_money/src/services/shared_preferences_service/shared_preferences_service.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
late NewTransactionController controller;
late TransactionModel incomeTransaction;
late TransactionModel expenseTransaction;
late TransactionModel invalidTransaction;
setUp(() {
controller = NewTransactionController(SharedPreferencesImpl());
incomeTransaction = TransactionModel(
description: 'Desenvolvimento de aplicativo',
value: 12000.0,
category: 'Venda',
type: TransactionType.income,
);
expenseTransaction = TransactionModel(
description: 'Desenvolvimento de aplicativo',
value: 12000.0,
category: 'Venda',
type: TransactionType.expense,
);
invalidTransaction = TransactionModel(
description: '',
value: 0,
category: '',
type: TransactionType.expense,
);
});
group('NewTransactionController', () {
group('newTransaction', () {
test('should create a new income transaction', () {
controller.newTransaction(incomeTransaction);
expect(controller.transactions.contains(incomeTransaction), true);
expect(controller.transactions.last.type, TransactionType.income);
});
test('should create a new expense transaction', () {
controller.newTransaction(expenseTransaction);
expect(controller.transactions.contains(expenseTransaction), true);
expect(controller.transactions.last.type, TransactionType.expense);
});
test('should not create a transaction if value is 0', () {
controller.newTransaction(invalidTransaction);
expect(controller.transactions.contains(invalidTransaction), false);
});
});
});
}
| 0 |
mirrored_repositories/dt_money/test/src/features/home | mirrored_repositories/dt_money/test/src/features/home/models/transaction_test.dart | import 'dart:convert';
import 'package:dt_money/src/features/home/models/transaction.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('TransactionModel', () {
test('should set transaction from stored json', () {
final transaction = TransactionModel.fromMap(jsonDecode(transactionJson));
expect(transaction.description, 'Something');
expect(transaction.value, 1);
expect(transaction.category, 'sunt');
expect(transaction.type, TransactionType.income);
});
test('should set transactions from stored json', () {
final list = jsonDecode(transactionsJson);
final transactions = <TransactionModel>[];
for (var e in list) {
transactions.add(TransactionModel.fromMap(e));
}
expect(transactions[0].description, 'Something');
expect(transactions[0].value, 1);
expect(transactions[0].category, 'sunt');
expect(transactions[0].type, TransactionType.income);
expect(transactions[1].description, 'Something else');
expect(transactions[1].value, 1);
expect(transactions[1].category, 'sunt');
expect(transactions[1].type, TransactionType.expense);
});
});
}
const transactionsJson = """
[
{
"description": "Something",
"value": 1,
"category": "sunt",
"type": "income"
},
{
"description": "Something else",
"value": 1,
"category": "sunt",
"type": "expense"
}
]
""";
const transactionJson = """
{
"description": "Something",
"value": 1,
"category": "sunt",
"type": "income"
}
""";
| 0 |
mirrored_repositories/upsplash-flutter | mirrored_repositories/upsplash-flutter/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:upsplash_app/ui/app.dart';
void main() {
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(statusBarColor: Colors.white));
runApp(MyApp());
}
| 0 |
mirrored_repositories/upsplash-flutter/lib | mirrored_repositories/upsplash-flutter/lib/repository/download_repository.dart | import 'package:image_downloader/image_downloader.dart';
import 'package:upsplash_app/models/PhotoListResponse.dart';
abstract class DownloadRepository {
Future downloadImage(PhotoListBean photoListBean);
}
class UpshplashDownloadRepository implements DownloadRepository {
@override
downloadImage(PhotoListBean photoListBean) async {
await ImageDownloader.downloadImage(
photoListBean.urls.raw,
destination: AndroidDestinationType.custom(
directory: "upsplash",
)..subDirectory("${photoListBean.id}.jpg"),
);
}
}
| 0 |
mirrored_repositories/upsplash-flutter/lib | mirrored_repositories/upsplash-flutter/lib/repository/photo_repository.dart | import 'package:dio/dio.dart';
import 'package:upsplash_app/models/PhotoListResponse.dart';
abstract class PhotoRepository {
Future<List<PhotoListBean>> getPhotos(int page);
}
class MainPhotoRepository implements PhotoRepository {
@override
Future<List<PhotoListBean>> getPhotos(int page) async {
try {
Response response = await Dio().get(
"https://api.unsplash.com/photos/?client_id=e2658d4b6b17ae24b50a7ab36d13ca67da9761322a5e4cb0e9cc531e69cecb90&page=$page");
List<PhotoListBean> list =
PhotoListResponse.fromJsonArray(response.data).results;
list.forEach((value){
print(value.color);
});
print(list.length);
return list;
} catch (error, stacktrace) {
print(error);
print(stacktrace);
return null;
}
}
}
| 0 |
mirrored_repositories/upsplash-flutter/lib | mirrored_repositories/upsplash-flutter/lib/repository/collection_repository.dart | import 'package:dio/dio.dart';
import 'package:upsplash_app/models/CollectionListResponse.dart';
abstract class CollectionRepository {
Future<List<CollectionListItem>> getCollections(int page);
}
class MainCollectionRepository extends CollectionRepository {
@override
Future<List<CollectionListItem>> getCollections(int page) async {
Response response = await Dio().get(
"https://api.unsplash.com/collections/?client_id=e2658d4b6b17ae24b50a7ab36d13ca67da9761322a5e4cb0e9cc531e69cecb90&page=$page");
List<CollectionListItem> list =
CollectionListResponse.fromJsonArray(response.data).results;
print(list.length);
return list;
}
}
| 0 |
mirrored_repositories/upsplash-flutter/lib/blocs | mirrored_repositories/upsplash-flutter/lib/blocs/collection_list/collection_list_state.dart | import 'package:meta/meta.dart';
import 'package:upsplash_app/models/CollectionListResponse.dart';
@immutable
abstract class CollectionListState {}
class InitialCollectionListState extends CollectionListState {}
class CollectionListError extends CollectionListState {}
class CollectionListLoaded extends CollectionListState {
final List<CollectionListItem> collections;
final int page;
CollectionListLoaded(this.collections, this.page);
CollectionListLoaded copyWith(List<CollectionListItem> collections, page) {
return CollectionListLoaded(collections, page);
}
}
| 0 |
mirrored_repositories/upsplash-flutter/lib/blocs | mirrored_repositories/upsplash-flutter/lib/blocs/collection_list/bloc.dart | export 'collection_list_bloc.dart';
export 'collection_list_event.dart';
export 'collection_list_state.dart';
| 0 |
mirrored_repositories/upsplash-flutter/lib/blocs | mirrored_repositories/upsplash-flutter/lib/blocs/collection_list/collection_list_event.dart | import 'package:meta/meta.dart';
@immutable
abstract class CollectionListEvent {}
class FetchEvent extends CollectionListEvent {}
| 0 |
mirrored_repositories/upsplash-flutter/lib/blocs | mirrored_repositories/upsplash-flutter/lib/blocs/collection_list/collection_list_bloc.dart | import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:rxdart/rxdart.dart';
import 'package:upsplash_app/repository/collection_repository.dart';
import './bloc.dart';
class CollectionListBloc
extends Bloc<CollectionListEvent, CollectionListState> {
final CollectionRepository _repository;
CollectionListBloc(this._repository);
@override
CollectionListState get initialState => InitialCollectionListState();
@override
Stream<CollectionListState> transformEvents(
Stream<CollectionListEvent> events,
Stream<CollectionListState> Function(CollectionListEvent event) next,
) {
return super.transformEvents(
(events as Observable<CollectionListEvent>).debounceTime(
Duration(milliseconds: 500),
),
next,
);
}
@override
Stream<CollectionListState> mapEventToState(
CollectionListEvent event,
) async* {
final currentState = state;
if (event is FetchEvent) {
try {
if (currentState is InitialCollectionListState) {
final collections = await _repository.getCollections(0);
yield CollectionListLoaded(collections, 0);
} else if (currentState is CollectionListLoaded) {
var fetchPage = currentState.page + 1;
final collections = await _repository.getCollections(fetchPage);
yield collections.isEmpty
? currentState.copyWith(collections, fetchPage)
: CollectionListLoaded(
currentState.collections + collections, fetchPage);
}
} catch (error, stacktrace) {
yield CollectionListError();
print(error);
print(stacktrace);
}
}
}
}
| 0 |
mirrored_repositories/upsplash-flutter/lib/blocs | mirrored_repositories/upsplash-flutter/lib/blocs/photo_detail/bloc.dart | export 'photo_detail_bloc.dart';
export 'photo_detail_event.dart';
export 'photo_detail_state.dart'; | 0 |
mirrored_repositories/upsplash-flutter/lib/blocs | mirrored_repositories/upsplash-flutter/lib/blocs/photo_detail/photo_detail_bloc.dart | import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:upsplash_app/models/PhotoListResponse.dart';
import 'package:upsplash_app/repository/download_repository.dart';
import './bloc.dart';
class PhotoDetailBloc extends Bloc<PhotoDetailEvent, PhotoDetailState> {
final PhotoListBean _photoListBean;
final DownloadRepository downloadRepository = UpshplashDownloadRepository();
PhotoDetailBloc(this._photoListBean);
@override
PhotoDetailState get initialState => InitialPhotoDetailState();
@override
Stream<PhotoDetailState> mapEventToState(
PhotoDetailEvent event,
) async* {
final currentState = state;
if (event is DownloadImageEvent && !(currentState is DownloadingState)) {
yield* _mapDownloadToState();
}
}
Stream<PhotoDetailState> _mapDownloadToState() async* {
try {
yield DownloadingState();
await downloadRepository.downloadImage(_photoListBean);
yield DownloadedState();
} catch (error, stacktrace) {
print(error);
print(stacktrace);
yield ErrorDownloadingState();
}
}
}
| 0 |
mirrored_repositories/upsplash-flutter/lib/blocs | mirrored_repositories/upsplash-flutter/lib/blocs/photo_detail/photo_detail_event.dart | import 'package:meta/meta.dart';
@immutable
abstract class PhotoDetailEvent {}
class DownloadImageEvent extends PhotoDetailEvent {}
| 0 |
mirrored_repositories/upsplash-flutter/lib/blocs | mirrored_repositories/upsplash-flutter/lib/blocs/photo_detail/photo_detail_state.dart | import 'package:meta/meta.dart';
@immutable
abstract class PhotoDetailState {}
class InitialPhotoDetailState extends PhotoDetailState {}
class DownloadingState extends PhotoDetailState {}
class DownloadedState extends PhotoDetailState {}
class ErrorDownloadingState extends PhotoDetailState {}
| 0 |
mirrored_repositories/upsplash-flutter/lib/blocs | mirrored_repositories/upsplash-flutter/lib/blocs/photo_list/photo_list_event.dart | import 'package:equatable/equatable.dart';
abstract class PhotoListEvent extends Equatable {
const PhotoListEvent();
@override
List<Object> get props => [];
}
class FetchEvent extends PhotoListEvent {}
| 0 |
mirrored_repositories/upsplash-flutter/lib/blocs | mirrored_repositories/upsplash-flutter/lib/blocs/photo_list/bloc.dart | export 'photo_list_bloc.dart';
export 'photo_list_event.dart';
export 'photo_list_state.dart'; | 0 |
mirrored_repositories/upsplash-flutter/lib/blocs | mirrored_repositories/upsplash-flutter/lib/blocs/photo_list/photo_list_state.dart | import 'package:upsplash_app/models/PhotoListResponse.dart';
abstract class PhotoListState {
const PhotoListState();
}
class InitialPhotoListState extends PhotoListState {}
class PhotoListError extends PhotoListState {}
class PhotoListLoaded extends PhotoListState {
final List<PhotoListBean> photos;
final int page;
PhotoListLoaded(this.photos, this.page);
PhotoListLoaded copyWith(List<PhotoListBean> photos) {
return PhotoListLoaded(photos, page);
}
}
| 0 |
mirrored_repositories/upsplash-flutter/lib/blocs | mirrored_repositories/upsplash-flutter/lib/blocs/photo_list/photo_list_bloc.dart | import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:rxdart/rxdart.dart';
import 'package:upsplash_app/repository/photo_repository.dart';
import './bloc.dart';
class PhotoListBloc extends Bloc<PhotoListEvent, PhotoListState> {
final PhotoRepository photoRepository;
PhotoListBloc(this.photoRepository);
@override
PhotoListState get initialState => InitialPhotoListState();
@override
Stream<PhotoListState> transformEvents(
Stream<PhotoListEvent> events,
Stream<PhotoListState> Function(PhotoListEvent event) next,
) {
return super.transformEvents(
(events as Observable<PhotoListEvent>).debounceTime(
Duration(milliseconds: 500),
),
next,
);
}
@override
Stream<PhotoListState> mapEventToState(
PhotoListEvent event,
) async* {
final currentState = state;
if (event is FetchEvent) {
try {
if (currentState is InitialPhotoListState) {
final photos = await photoRepository.getPhotos(0);
yield PhotoListLoaded(photos, 0);
} else if (currentState is PhotoListLoaded) {
int currentPage = currentState.page;
final photos =
await photoRepository.getPhotos(currentPage++);
print("current_page = $currentPage");
yield photos.isEmpty
? currentState.copyWith(photos)
: PhotoListLoaded(currentState.photos + photos, currentPage);
}
} catch (error, stacktrace) {
yield PhotoListError();
print(error);
print(stacktrace);
}
}
}
}
| 0 |
mirrored_repositories/upsplash-flutter/lib | mirrored_repositories/upsplash-flutter/lib/models/CollectionListResponse.dart | import 'package:upsplash_app/models/PhotoListResponse.dart';
class CollectionListResponse {
final List<CollectionListItem> results;
CollectionListResponse(this.results);
CollectionListResponse.fromJsonArray(List json)
: results = json.map((i) => new CollectionListItem.fromJson(i)).toList();
}
class CollectionListItem {
String title;
String description;
String publishedAt;
String updatedAt;
String shareKey;
bool private;
int id;
int totalPhotos;
CoverPhotoBean coverPhoto;
LinksBean links;
UserBean user;
CollectionListItem(
{this.title,
this.description,
this.publishedAt,
this.updatedAt,
this.shareKey,
this.private,
this.id,
this.totalPhotos,
this.coverPhoto,
this.links,
this.user});
CollectionListItem.fromJson(Map<String, dynamic> json) {
this.title = json['title'];
this.description = json['description'];
this.publishedAt = json['published_at'];
this.updatedAt = json['updated_at'];
this.shareKey = json['share_key'];
this.private = json['private'];
this.id = json['id'];
this.totalPhotos = json['total_photos'];
this.coverPhoto = json['cover_photo'] != null
? CoverPhotoBean.fromJson(json['cover_photo'])
: null;
this.links =
json['links'] != null ? LinksBean.fromJson(json['links']) : null;
this.user = json['user'] != null ? UserBean.fromJson(json['user']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['title'] = this.title;
data['description'] = this.description;
data['published_at'] = this.publishedAt;
data['updated_at'] = this.updatedAt;
data['share_key'] = this.shareKey;
data['private'] = this.private;
data['id'] = this.id;
data['total_photos'] = this.totalPhotos;
if (this.coverPhoto != null) {
data['cover_photo'] = this.coverPhoto.toJson();
}
if (this.links != null) {
data['links'] = this.links.toJson();
}
if (this.user != null) {
data['user'] = this.user.toJson();
}
return data;
}
}
class CoverPhotoBean {
String id;
String color;
String description;
bool likedByUser;
int width;
int height;
int likes;
LinksBean links;
UrlsBean urls;
UserBean user;
CoverPhotoBean(
{this.id,
this.color,
this.description,
this.likedByUser,
this.width,
this.height,
this.likes,
this.links,
this.urls,
this.user});
CoverPhotoBean.fromJson(Map<String, dynamic> json) {
this.id = json['id'];
this.color = json['color'];
this.description = json['description'];
this.likedByUser = json['liked_by_user'];
this.width = json['width'];
this.height = json['height'];
this.likes = json['likes'];
this.links =
json['links'] != null ? LinksBean.fromJson(json['links']) : null;
this.urls = json['urls'] != null ? UrlsBean.fromJson(json['urls']) : null;
this.user = json['user'] != null ? UserBean.fromJson(json['user']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['color'] = this.color;
data['description'] = this.description;
data['liked_by_user'] = this.likedByUser;
data['width'] = this.width;
data['height'] = this.height;
data['likes'] = this.likes;
if (this.links != null) {
data['links'] = this.links.toJson();
}
if (this.urls != null) {
data['urls'] = this.urls.toJson();
}
if (this.user != null) {
data['user'] = this.user.toJson();
}
return data;
}
}
class LinksBean {
String self;
String html;
String photos;
String likes;
String portfolio;
LinksBean({this.self, this.html, this.photos, this.likes, this.portfolio});
LinksBean.fromJson(Map<String, dynamic> json) {
this.self = json['self'];
this.html = json['html'];
this.photos = json['photos'];
this.likes = json['likes'];
this.portfolio = json['portfolio'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['self'] = this.self;
data['html'] = this.html;
data['photos'] = this.photos;
data['likes'] = this.likes;
data['portfolio'] = this.portfolio;
return data;
}
}
class UserBean {
String id;
String username;
String name;
String portfolioUrl;
String bio;
String location;
int totalLikes;
int totalPhotos;
int totalCollections;
LinksBean links;
ProfileImageBean profileImage;
UserBean(
{this.id,
this.username,
this.name,
this.portfolioUrl,
this.bio,
this.location,
this.totalLikes,
this.totalPhotos,
this.totalCollections,
this.links,
this.profileImage});
UserBean.fromJson(Map<String, dynamic> json) {
this.id = json['id'];
this.username = json['username'];
this.name = json['name'];
this.portfolioUrl = json['portfolio_url'];
this.bio = json['bio'];
this.location = json['location'];
this.totalLikes = json['total_likes'];
this.totalPhotos = json['total_photos'];
this.totalCollections = json['total_collections'];
this.links =
json['links'] != null ? LinksBean.fromJson(json['links']) : null;
this.profileImage = json['profile_image'] != null
? ProfileImageBean.fromJson(json['profile_image'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['username'] = this.username;
data['name'] = this.name;
data['portfolio_url'] = this.portfolioUrl;
data['bio'] = this.bio;
data['location'] = this.location;
data['total_likes'] = this.totalLikes;
data['total_photos'] = this.totalPhotos;
data['total_collections'] = this.totalCollections;
if (this.links != null) {
data['links'] = this.links.toJson();
}
if (this.profileImage != null) {
data['profile_image'] = this.profileImage.toJson();
}
return data;
}
}
class ProfileImageBean {
String small;
String medium;
String large;
ProfileImageBean({this.small, this.medium, this.large});
ProfileImageBean.fromJson(Map<String, dynamic> json) {
this.small = json['small'];
this.medium = json['medium'];
this.large = json['large'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['small'] = this.small;
data['medium'] = this.medium;
data['large'] = this.large;
return data;
}
}
| 0 |
mirrored_repositories/upsplash-flutter/lib | mirrored_repositories/upsplash-flutter/lib/models/PhotoListResponse.dart | class PhotoListResponse {
final List<PhotoListBean> results;
PhotoListResponse(this.results);
PhotoListResponse.fromJsonArray(List json)
: results = json.map((i) => new PhotoListBean.fromJson(i)).toList();
}
class PhotoListBean {
String id;
String createdAt;
String updatedAt;
String color;
String altDescription;
bool likedByUser;
int width;
int height;
int likes;
LinksBean links;
SponsorshipBean sponsorship;
UrlsBean urls;
UserBean user;
PhotoListBean(
{this.id,
this.createdAt,
this.updatedAt,
this.color,
this.altDescription,
this.likedByUser,
this.width,
this.height,
this.likes,
this.links,
this.sponsorship,
this.urls,
this.user});
PhotoListBean.fromJson(Map<String, dynamic> json) {
this.id = json['id'];
this.createdAt = json['created_at'];
this.updatedAt = json['updated_at'];
this.color = json['color'];
this.altDescription = json['alt_description'];
this.likedByUser = json['liked_by_user'];
this.width = json['width'];
this.height = json['height'];
this.likes = json['likes'];
this.links =
json['links'] != null ? LinksBean.fromJson(json['links']) : null;
this.sponsorship = json['sponsorship'] != null
? SponsorshipBean.fromJson(json['sponsorship'])
: null;
this.urls = json['urls'] != null ? UrlsBean.fromJson(json['urls']) : null;
this.user = json['user'] != null ? UserBean.fromJson(json['user']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
data['color'] = this.color;
data['alt_description'] = this.altDescription;
data['liked_by_user'] = this.likedByUser;
data['width'] = this.width;
data['height'] = this.height;
data['likes'] = this.likes;
if (this.links != null) {
data['links'] = this.links.toJson();
}
if (this.sponsorship != null) {
data['sponsorship'] = this.sponsorship.toJson();
}
if (this.urls != null) {
data['urls'] = this.urls.toJson();
}
if (this.user != null) {
data['user'] = this.user.toJson();
}
return data;
}
}
class LinksBean {
String self;
String html;
String photos;
String likes;
String portfolio;
String following;
String followers;
LinksBean(
{this.self,
this.html,
this.photos,
this.likes,
this.portfolio,
this.following,
this.followers});
LinksBean.fromJson(Map<String, dynamic> json) {
this.self = json['self'];
this.html = json['html'];
this.photos = json['photos'];
this.likes = json['likes'];
this.portfolio = json['portfolio'];
this.following = json['following'];
this.followers = json['followers'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['self'] = this.self;
data['html'] = this.html;
data['photos'] = this.photos;
data['likes'] = this.likes;
data['portfolio'] = this.portfolio;
data['following'] = this.following;
data['followers'] = this.followers;
return data;
}
}
class SponsorshipBean {
String impressionsId;
String tagline;
SponsorBean sponsor;
List<String> impressionUrls;
SponsorshipBean(
{this.impressionsId, this.tagline, this.sponsor, this.impressionUrls});
SponsorshipBean.fromJson(Map<String, dynamic> json) {
this.impressionsId = json['impressions_id'];
this.tagline = json['tagline'];
this.sponsor =
json['sponsor'] != null ? SponsorBean.fromJson(json['sponsor']) : null;
List<dynamic> impressionUrlsList = json['impression_urls'];
this.impressionUrls = new List();
this.impressionUrls.addAll(impressionUrlsList.map((o) => o.toString()));
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['impressions_id'] = this.impressionsId;
data['tagline'] = this.tagline;
if (this.sponsor != null) {
data['sponsor'] = this.sponsor.toJson();
}
data['impression_urls'] = this.impressionUrls;
return data;
}
}
class UrlsBean {
String raw;
String full;
String regular;
String small;
String thumb;
UrlsBean({this.raw, this.full, this.regular, this.small, this.thumb});
UrlsBean.fromJson(Map<String, dynamic> json) {
this.raw = json['raw'];
this.full = json['full'];
this.regular = json['regular'];
this.small = json['small'];
this.thumb = json['thumb'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['raw'] = this.raw;
data['full'] = this.full;
data['regular'] = this.regular;
data['small'] = this.small;
data['thumb'] = this.thumb;
return data;
}
}
class UserBean {
String id;
String updatedAt;
String username;
String name;
String firstName;
String lastName;
String twitterUsername;
String portfolioUrl;
String bio;
String instagramUsername;
bool acceptedTos;
int totalCollections;
int totalLikes;
int totalPhotos;
LinksBean links;
ProfileImageBean profileImage;
UserBean(
{this.id,
this.updatedAt,
this.username,
this.name,
this.firstName,
this.lastName,
this.twitterUsername,
this.portfolioUrl,
this.bio,
this.instagramUsername,
this.acceptedTos,
this.totalCollections,
this.totalLikes,
this.totalPhotos,
this.links,
this.profileImage});
UserBean.fromJson(Map<String, dynamic> json) {
this.id = json['id'];
this.updatedAt = json['updated_at'];
this.username = json['username'];
this.name = json['name'];
this.firstName = json['first_name'];
this.lastName = json['last_name'];
this.twitterUsername = json['twitter_username'];
this.portfolioUrl = json['portfolio_url'];
this.bio = json['bio'];
this.instagramUsername = json['instagram_username'];
this.acceptedTos = json['accepted_tos'];
this.totalCollections = json['total_collections'];
this.totalLikes = json['total_likes'];
this.totalPhotos = json['total_photos'];
this.links =
json['links'] != null ? LinksBean.fromJson(json['links']) : null;
this.profileImage = json['profile_image'] != null
? ProfileImageBean.fromJson(json['profile_image'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['updated_at'] = this.updatedAt;
data['username'] = this.username;
data['name'] = this.name;
data['first_name'] = this.firstName;
data['last_name'] = this.lastName;
data['twitter_username'] = this.twitterUsername;
data['portfolio_url'] = this.portfolioUrl;
data['bio'] = this.bio;
data['instagram_username'] = this.instagramUsername;
data['accepted_tos'] = this.acceptedTos;
data['total_collections'] = this.totalCollections;
data['total_likes'] = this.totalLikes;
data['total_photos'] = this.totalPhotos;
if (this.links != null) {
data['links'] = this.links.toJson();
}
if (this.profileImage != null) {
data['profile_image'] = this.profileImage.toJson();
}
return data;
}
}
class SponsorBean {
String id;
String updatedAt;
String username;
String name;
String firstName;
String lastName;
String twitterUsername;
String portfolioUrl;
String bio;
String instagramUsername;
bool acceptedTos;
int totalCollections;
int totalLikes;
int totalPhotos;
LinksBean links;
ProfileImageBean profileImage;
SponsorBean(
{this.id,
this.updatedAt,
this.username,
this.name,
this.firstName,
this.lastName,
this.twitterUsername,
this.portfolioUrl,
this.bio,
this.instagramUsername,
this.acceptedTos,
this.totalCollections,
this.totalLikes,
this.totalPhotos,
this.links,
this.profileImage});
SponsorBean.fromJson(Map<String, dynamic> json) {
this.id = json['id'];
this.updatedAt = json['updated_at'];
this.username = json['username'];
this.name = json['name'];
this.firstName = json['first_name'];
this.lastName = json['last_name'];
this.twitterUsername = json['twitter_username'];
this.portfolioUrl = json['portfolio_url'];
this.bio = json['bio'];
this.instagramUsername = json['instagram_username'];
this.acceptedTos = json['accepted_tos'];
this.totalCollections = json['total_collections'];
this.totalLikes = json['total_likes'];
this.totalPhotos = json['total_photos'];
this.links =
json['links'] != null ? LinksBean.fromJson(json['links']) : null;
this.profileImage = json['profile_image'] != null
? ProfileImageBean.fromJson(json['profile_image'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['updated_at'] = this.updatedAt;
data['username'] = this.username;
data['name'] = this.name;
data['first_name'] = this.firstName;
data['last_name'] = this.lastName;
data['twitter_username'] = this.twitterUsername;
data['portfolio_url'] = this.portfolioUrl;
data['bio'] = this.bio;
data['instagram_username'] = this.instagramUsername;
data['accepted_tos'] = this.acceptedTos;
data['total_collections'] = this.totalCollections;
data['total_likes'] = this.totalLikes;
data['total_photos'] = this.totalPhotos;
if (this.links != null) {
data['links'] = this.links.toJson();
}
if (this.profileImage != null) {
data['profile_image'] = this.profileImage.toJson();
}
return data;
}
}
class ProfileImageBean {
String small;
String medium;
String large;
ProfileImageBean({this.small, this.medium, this.large});
ProfileImageBean.fromJson(Map<String, dynamic> json) {
this.small = json['small'];
this.medium = json['medium'];
this.large = json['large'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['small'] = this.small;
data['medium'] = this.medium;
data['large'] = this.large;
return data;
}
}
| 0 |
mirrored_repositories/upsplash-flutter/lib | mirrored_repositories/upsplash-flutter/lib/utils/hex_color.dart | import 'dart:ui';
class HexColor extends Color {
static int _getColorFromHex(String hexColor) {
hexColor = hexColor.toUpperCase().replaceAll("#", "");
if (hexColor.length == 6) {
hexColor = "FF" + hexColor;
}
return int.parse(hexColor, radix: 16);
}
static int _inverted(int color) {
return Color(0xffffff).value ^ color;
}
HexColor(final String hexColor, {bool inverted = false})
: super(inverted
? _inverted(_getColorFromHex(hexColor))
: _getColorFromHex(hexColor));
}
| 0 |
mirrored_repositories/upsplash-flutter/lib | mirrored_repositories/upsplash-flutter/lib/ui/app.dart | import 'package:flutter/material.dart';
import 'package:upsplash_app/ui/pages/home.dart';
import 'package:upsplash_app/ui/pages/photo_detail.dart';
import 'package:upsplash_app/ui/styles/theme.dart';
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: mainTheme,
debugShowCheckedModeBanner: false,
initialRoute: HomePage.routeName,
routes: {
HomePage.routeName: (context) => HomePage(),
PhotoDetailPage.routeName: (context) => PhotoDetailPage(),
},
);
}
}
| 0 |
mirrored_repositories/upsplash-flutter/lib/ui | mirrored_repositories/upsplash-flutter/lib/ui/widgets/collection_list.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:upsplash_app/blocs/collection_list/bloc.dart';
import 'package:upsplash_app/repository/collection_repository.dart';
import 'package:upsplash_app/ui/widgets/bottom_loader.dart';
class CollectionListWidget extends StatelessWidget {
@override
Widget build(BuildContext context) => BlocProvider(
create: (context) => CollectionListBloc(MainCollectionRepository()),
child: _CollectionListWidget());
}
class _CollectionListWidget extends StatefulWidget {
@override
State<StatefulWidget> createState() => _CollectionListState();
}
class _CollectionListState extends State<_CollectionListWidget>
with AutomaticKeepAliveClientMixin {
CollectionListBloc _bloc;
final _scrollController = ScrollController();
final _scrollThreshold = 200.0;
@override
void initState() {
_scrollController.addListener(_onScroll);
_bloc = BlocProvider.of<CollectionListBloc>(context)..add(FetchEvent());
super.initState();
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
void _onScroll() {
final maxScroll = _scrollController.position.maxScrollExtent;
final currentScroll = _scrollController.position.pixels;
if (maxScroll - currentScroll <= _scrollThreshold) {
_bloc.add(FetchEvent());
}
}
@override
// TODO: implement wantKeepAlive
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
return BlocBuilder<CollectionListBloc, CollectionListState>(
builder: (context, state) {
if (state is CollectionListError)
return Center(
child: Text("error"),
);
if (state is InitialCollectionListState) {
return Center(
child: CircularProgressIndicator(),
);
}
if (state is CollectionListLoaded) {
return ListView.builder(
itemCount: state.collections.length + 1,
controller: _scrollController,
itemBuilder: (context, index) {
if (index >= state.collections.length) return BottomLoader();
final item = state.collections[index];
double displayHeight = MediaQuery.of(context).size.height;
double displayWidth = MediaQuery.of(context).size.width;
return Stack(children: <Widget>[
Image.network(item.coverPhoto.urls.regular,
height: displayHeight / 3,
width: displayWidth,
fit: BoxFit.cover),
Positioned(
bottom: 10,
left: 10,
child: Text(
item.title,
style: TextStyle(
color: Colors.white,
fontSize: 40,
),
),
),
]);
});
}
return Center();
},
);
}
}
| 0 |
mirrored_repositories/upsplash-flutter/lib/ui | mirrored_repositories/upsplash-flutter/lib/ui/widgets/photo_list.dart | import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:transparent_image/transparent_image.dart';
import 'package:upsplash_app/blocs/photo_list/bloc.dart';
import 'package:upsplash_app/models/PhotoListResponse.dart';
import 'package:upsplash_app/repository/photo_repository.dart';
import 'package:upsplash_app/ui/pages/photo_detail.dart';
import 'package:upsplash_app/utils/hex_color.dart';
import 'bottom_loader.dart';
class PhotoListWidget extends StatelessWidget {
final PhotoRepository repository;
const PhotoListWidget(this.repository) : super();
@override
Widget build(BuildContext context) {
return BlocProvider(
child: _PhotoListWidget(),
create: (context) => PhotoListBloc(repository),
);
}
}
class _PhotoListWidget extends StatefulWidget {
@override
State<StatefulWidget> createState() => _PhotoListWidgetState();
}
class _PhotoListWidgetState extends State<_PhotoListWidget>
with AutomaticKeepAliveClientMixin {
PhotoListBloc _bloc;
final _scrollController = ScrollController();
final _scrollThreshold = 200.0;
@override
void initState() {
_scrollController.addListener(_onScroll);
_bloc = BlocProvider.of<PhotoListBloc>(context);
_bloc.add(FetchEvent());
super.initState();
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
void _onScroll() {
final maxScroll = _scrollController.position.maxScrollExtent;
final currentScroll = _scrollController.position.pixels;
if (maxScroll - currentScroll <= _scrollThreshold) {
_bloc.add(FetchEvent());
}
}
@override
Widget build(BuildContext context) {
return BlocBuilder<PhotoListBloc, PhotoListState>(
builder: (buildContext, state) {
if (state is PhotoListError)
return Center(
child: Text("error"),
);
if (state is InitialPhotoListState)
return Center(
child: CircularProgressIndicator(),
);
if (state is PhotoListLoaded) {
return ListView.builder(
itemCount: state.photos.length + 1,
controller: _scrollController,
itemBuilder: (buildContext, index) {
if (index >= state.photos.length) return BottomLoader();
PhotoListBean item = state.photos[index];
double displayWidth = MediaQuery.of(context).size.width;
double finalHeight = displayWidth / (item.width / item.height);
Color primaryColor = HexColor(item.color);
return InkWell(
onTap: () {
_onPhotoTap(item);
},
child: Hero(
tag: "photo${item.id}",
child: Stack(
children: <Widget>[
SizedBox(
width: displayWidth,
height: finalHeight,
child: DecoratedBox(
decoration: BoxDecoration(color: primaryColor),
),
),
FadeInImage.memoryNetwork(
image: item.urls.thumb,
placeholder: kTransparentImage,
fit: BoxFit.fitWidth,
width: displayWidth,
height: finalHeight,
),
FadeInImage.memoryNetwork(
image: item.urls.regular,
placeholder: kTransparentImage,
fit: BoxFit.fitWidth,
width: displayWidth,
height: finalHeight,
),
],
),
),
);
});
}
return Center(child: Text("sesh"));
},
);
}
_onPhotoTap(PhotoListBean photoListBean) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PhotoDetailPage(),
// Pass the arguments as part of the RouteSettings. The
// ExtractArgumentScreen reads the arguments from these
// settings.
settings: RouteSettings(
arguments: PhotoDetailPageArguments(photoListBean),
),
),
);
}
@override
// TODO: implement wantKeepAlive
bool get wantKeepAlive => true;
}
| 0 |
mirrored_repositories/upsplash-flutter/lib/ui | mirrored_repositories/upsplash-flutter/lib/ui/widgets/bottom_loader.dart | import 'package:flutter/material.dart';
class BottomLoader extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.center,
child: Center(
child: SizedBox(
width: 50,
height: 50,
child: Center(child: CircularProgressIndicator()),
),
),
);
}
}
| 0 |
mirrored_repositories/upsplash-flutter/lib/ui | mirrored_repositories/upsplash-flutter/lib/ui/pages/home.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:upsplash_app/repository/photo_repository.dart';
import 'package:upsplash_app/ui/widgets/collection_list.dart';
import 'package:upsplash_app/ui/widgets/photo_list.dart';
class HomePage extends StatelessWidget {
static final routeName = "homePage";
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
title: Text("Upsplash"),
bottom: TabBar(
tabs: <Widget>[
Tab(
text: "Home",
),
Tab(
text: "Collections",
)
],
),
),
body: TabBarView(
children: [
PhotoListWidget(MainPhotoRepository()),
CollectionListWidget()
],
),
),
);
}
}
| 0 |
mirrored_repositories/upsplash-flutter/lib/ui | mirrored_repositories/upsplash-flutter/lib/ui/pages/photo_detail.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:permission/permission.dart';
import 'package:upsplash_app/blocs/photo_detail/bloc.dart';
import 'package:upsplash_app/models/PhotoListResponse.dart';
class PhotoDetailPageArguments {
final PhotoListBean photoListBean;
PhotoDetailPageArguments(this.photoListBean);
}
class PhotoDetailPage extends StatelessWidget {
static final routeName = "photoDetailPage";
@override
Widget build(BuildContext context) {
PhotoDetailPageArguments args = ModalRoute.of(context).settings.arguments;
return BlocProvider(
create: (context) => PhotoDetailBloc(args.photoListBean),
child: PhotoDetailWidget(
photoListBean: args.photoListBean,
),
);
}
}
class PhotoDetailWidget extends StatefulWidget {
final PhotoListBean photoListBean;
const PhotoDetailWidget({Key key, this.photoListBean}) : super(key: key);
@override
State<StatefulWidget> createState() {
return PhotoDetailWidgetState();
}
}
class PhotoDetailWidgetState extends State<PhotoDetailWidget> {
PhotoDetailBloc _bloc;
@override
void initState() {
_bloc = BlocProvider.of<PhotoDetailBloc>(context);
super.initState();
}
@override
Widget build(BuildContext context) {
return BlocBuilder<PhotoDetailBloc, PhotoDetailState>(
builder: (context, state) {
return Scaffold(
appBar: AppBar(
title: Text(widget.photoListBean.user.name),
),
body: Hero(
tag: "photo${widget.photoListBean.id}",
child: Image.network(widget.photoListBean.urls.regular),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
_onSavePressed();
},
child: (state is DownloadingState)
? _buildLoading()
: Icon(Icons.file_download,color: Colors.white,)));
});
}
Future<bool> _checkPermission() async {
var permissions = await Permission.getPermissionsStatus([
PermissionName.Storage,
]);
return permissions[0].permissionStatus == PermissionStatus.allow;
}
_onSavePressed() async {
if (await _checkPermission()) {
_bloc.add(DownloadImageEvent());
} else {
await _requestPermission();
_onSavePressed();
}
}
_requestPermission() async {
var permissionNames =
await Permission.requestPermissions([PermissionName.Storage]);
}
_buildLoading() {
return CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
);
}
}
| 0 |
mirrored_repositories/upsplash-flutter/lib/ui | mirrored_repositories/upsplash-flutter/lib/ui/styles/theme.dart | import 'package:flutter/material.dart';
final mainTheme = ThemeData(
fontFamily: 'Roboto',
scaffoldBackgroundColor: Colors.white,
primarySwatch: Colors.grey,
appBarTheme: AppBarTheme(
brightness: Brightness.light,
iconTheme: IconThemeData(color: Colors.black87),
actionsIconTheme: IconThemeData(color: Colors.black87),
color: Colors.white,
textTheme: TextTheme(
title: TextStyle(color: Colors.black87, fontSize: 18),
button: TextStyle(color: Colors.black87),
)));
| 0 |
mirrored_repositories/upsplash-flutter | mirrored_repositories/upsplash-flutter/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:upsplash_app/main.dart';
import 'package:upsplash_app/ui/app.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(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/M-Box-Login-UI | mirrored_repositories/M-Box-Login-UI/lib/Forget_Password.dart | import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.white,
body: SafeArea(
child: Column(
children: [
const SizedBox(
height: 50,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Image(
height: 50,
width: 50,
image: AssetImage('images/logo.png'),
),
const SizedBox(
width: 10,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Text(
"Maintaince",
style: TextStyle(
fontSize: 24,
fontFamily: 'Rubik Medium',
color: Color(0xff2D3142)),
),
Text(
'BOX',
style: TextStyle(
fontSize: 24,
fontFamily: 'Rubik Medium',
color: Color(0xffF9703B)),
),
],
)
],
),
const SizedBox(
height: 40,
),
const Center(
child: Text(
"Forget Password ",
style: TextStyle(
fontSize: 24,
fontFamily: 'Rubik Medium',
color: Color(0xff2D3142)),
)),
const SizedBox(
height: 14,
),
const Center(
child: Text(
"This App is Mainly Focus On\n Maintiance Costumer Side",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 24,
fontFamily: 'Rubik Regular',
color: Color(0xff4C5980)),
)),
SizedBox(
height: 50,
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: TextFormField(
decoration: InputDecoration(
hintText: "Email",
fillColor: const Color(0xffF8F9FA),
filled: true,
prefixIcon: const Icon(
Icons.email_outlined,
color: Color(0xff323F4B),
),
focusedBorder: OutlineInputBorder(
borderSide:
const BorderSide(color: Color(0xffE4E7EB)),
borderRadius: BorderRadius.circular(10)),
enabledBorder: OutlineInputBorder(
borderSide:
const BorderSide(color: Color(0xffE4E7EB)),
borderRadius: BorderRadius.circular(10)),
),
),
),
SizedBox(
height: 120,
),
const SizedBox(
height: 100,
),
Container(
height: 50,
width: 300,
decoration: BoxDecoration(
color: Color(0xffF9703B),
borderRadius: BorderRadius.circular(10)),
child: const Center(
child: Text(
'SEND OTP',
style: TextStyle(
fontSize: 18,
fontFamily: 'Rubik Medium',
color: Colors.white),
),
),
),
SizedBox(
height: 15,
),
],
),
)));
}
}
| 0 |
mirrored_repositories/M-Box-Login-UI | mirrored_repositories/M-Box-Login-UI/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.white,
body: SafeArea(
child: Column(
children: [
const SizedBox(
height: 50,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Image(
height: 50,
width: 50,
image: AssetImage('images/logo.png'),
),
const SizedBox(
width: 10,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Text(
"Maintaince",
style: TextStyle(
fontSize: 24,
fontFamily: 'Rubik Medium',
color: Color(0xff2D3142)),
),
Text(
'BOX',
style: TextStyle(
fontSize: 24,
fontFamily: 'Rubik Medium',
color: Color(0xffF9703B)),
),
],
)
],
),
const SizedBox(
height: 40,
),
const Center(
child: Text(
"Login ",
style: TextStyle(
fontSize: 24,
fontFamily: 'Rubik Medium',
color: Color(0xff2D3142)),
)),
const SizedBox(
height: 14,
),
const Center(
child: Text(
"This App is Mainly Focus On\n Maintiance Costumer Side",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 24,
fontFamily: 'Rubik Regular',
color: Color(0xff4C5980)),
)),
SizedBox(
height: 50,
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 20 ),
child: TextFormField(
decoration: InputDecoration(
hintText: "Email",
fillColor: const Color(0xffF8F9FA),
filled: true,
prefixIcon: const Icon(
Icons.alternate_email,
color: Color(0xff323F4B),
),
focusedBorder: OutlineInputBorder(
borderSide:const BorderSide(color: Color(0xffE4E7EB)),
borderRadius: BorderRadius.circular(10)
),
enabledBorder: OutlineInputBorder(
borderSide:const BorderSide(color: Color(0xffE4E7EB)),
borderRadius: BorderRadius.circular(10)),
),
),
),
SizedBox(
height: 20,
),
Padding(
padding:EdgeInsets.only(left: 20,right: 20,top: 10,),
child:TextFormField(
decoration: InputDecoration(
hintText: "Password",
fillColor: const Color(0xffF8F9FA),
filled: true,
prefixIcon: const Icon(
Icons.lock_open,
color: Color(0xff323F4B),
),
focusedBorder: OutlineInputBorder(
borderSide:
const BorderSide(color: Color(0xffE4E7EB)),
borderRadius: BorderRadius.circular(10)
),
enabledBorder: OutlineInputBorder(
borderSide:const BorderSide(color: Color(0xffE4E7EB)),
borderRadius: BorderRadius.circular(10)),
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: const [
Padding(
padding:EdgeInsets.only(left: 20,right: 20,top: 10,),
child: Text(
"Forget Password ?",
textAlign: TextAlign.end,
style: TextStyle(
fontSize: 16,
decoration: TextDecoration.underline,
fontFamily: 'Rubik Regular',
color: Color(0xff2D3142)),
),
),
],
),
const SizedBox(
height: 100,
),
Container(
height: 50,
width: 300,
decoration: BoxDecoration(
color: Color(0xffF9703B),
borderRadius: BorderRadius.circular(10)),
child: const Center(
child: Text(
'Log In',
style: TextStyle(
fontSize: 18,
fontFamily: 'Rubik Medium',
color: Colors.white),
),
),
),
SizedBox(
height: 15,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text(
"Don't have an account ?",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18,
fontFamily: 'Rubik Regular',
color: Color(0xff4C5980)),
),
Text(
"Sign Up",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18,
fontFamily: 'Rubik Medium',
color: Color(0xffF9703B)),
)
],
),
],
),
)));
}
}
| 0 |
mirrored_repositories/M-Box-Login-UI | mirrored_repositories/M-Box-Login-UI/lib/create_a_account_UI.dart | import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.white,
body: SafeArea(
child: Column(
children: [
const SizedBox(
height: 50,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Image(
height: 50,
width: 50,
image: AssetImage('images/logo.png'),
),
const SizedBox(
width: 10,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Text(
"Maintaince",
style: TextStyle(
fontSize: 24,
fontFamily: 'Rubik Medium',
color: Color(0xff2D3142)),
),
Text(
'BOX',
style: TextStyle(
fontSize: 24,
fontFamily: 'Rubik Medium',
color: Color(0xffF9703B)),
),
],
)
],
),
const SizedBox(
height: 40,
),
const Center(
child: Text(
"Create a Account ",
style: TextStyle(
fontSize: 24,
fontFamily: 'Rubik Medium',
color: Color(0xff2D3142)),
)),
const SizedBox(
height: 14,
),
const Center(
child: Text(
"This App is Mainly Focus On\n Maintiance Costumer Side",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 24,
fontFamily: 'Rubik Regular',
color: Color(0xff4C5980)),
)),
SizedBox(
height: 50,
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 20 ),
child: TextFormField(
decoration: InputDecoration(
hintText: "Name",
fillColor: const Color(0xffF8F9FA),
filled: true,
prefixIcon: const Icon(
Icons.perm_identity_rounded,
color: Color(0xff323F4B),
),
focusedBorder: OutlineInputBorder(
borderSide:const BorderSide(color: Color(0xffE4E7EB)),
borderRadius: BorderRadius.circular(10)
),
enabledBorder: OutlineInputBorder(
borderSide:const BorderSide(color: Color(0xffE4E7EB)),
borderRadius: BorderRadius.circular(10)),
),
),
),
SizedBox(
height: 20,
),
Padding(
padding:EdgeInsets.only(left: 20,right: 20,top: 10,bottom: 5,),
child:TextFormField(
decoration: InputDecoration(
hintText: "Contact",
fillColor: const Color(0xffF8F9FA),
filled: true,
prefixIcon: const Icon(
Icons.phone,
color: Color(0xff323F4B),
),
focusedBorder: OutlineInputBorder(
borderSide:
const BorderSide(color: Color(0xffE4E7EB)),
borderRadius: BorderRadius.circular(10)
),
enabledBorder: OutlineInputBorder(
borderSide:const BorderSide(color: Color(0xffE4E7EB)),
borderRadius: BorderRadius.circular(10)),
),
),
),
SizedBox(
height: 20,
),
Padding(
padding:EdgeInsets.only(left: 20,right: 20,top: 10,bottom: 5,),
child: TextFormField(
decoration: InputDecoration(
hintText: "Email",
fillColor: const Color(0xffF8F9FA),
filled: true,
prefixIcon: const Icon(
Icons.email_outlined,
color: Color(0xff323F4B),
),
focusedBorder: OutlineInputBorder(
borderSide:const BorderSide(color: Color(0xffE4E7EB)),
borderRadius: BorderRadius.circular(10)
),
enabledBorder: OutlineInputBorder(
borderSide:const BorderSide(color: Color(0xffE4E7EB)),
borderRadius: BorderRadius.circular(10)),
),
),
),
SizedBox(
height: 20,
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 20 ),
child: TextFormField(
decoration: InputDecoration(
hintText: "Password",
fillColor: const Color(0xffF8F9FA),
filled: true,
prefixIcon: const Icon(
Icons.lock_open,
color: Color(0xff323F4B),
),
focusedBorder: OutlineInputBorder(
borderSide:const BorderSide(color: Color(0xffE4E7EB)),
borderRadius: BorderRadius.circular(10)
),
enabledBorder: OutlineInputBorder(
borderSide:const BorderSide(color: Color(0xffE4E7EB)),
borderRadius: BorderRadius.circular(10)),
),
),
),
const SizedBox(
height: 60,
),
Container(
height: 50,
width: 300,
decoration: BoxDecoration(
color: Color(0xfff8703c),
borderRadius: BorderRadius.circular(10)),
child: const Center(
child: Text(
'Create a Account',
style: TextStyle(
fontSize: 18,
fontFamily: 'Rubik Medium',
color: Colors.white),
),
),
),
SizedBox(
height: 15,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text(
"Already have an account ? ",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18,
fontFamily: 'Rubik Regular',
color: Color(0xff4C5980)),
),
Text(
"Login In",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18,
fontFamily: 'Rubik Medium',
color: Color(0xffF9703B)),
)
],
),
],
),
)));
}
}
| 0 |
mirrored_repositories/M-Box-Login-UI/.dart_tool | mirrored_repositories/M-Box-Login-UI/.dart_tool/dartpad/web_plugin_registrant.dart | // Flutter web plugin registrant file.
//
// Generated file. Do not edit.
//
// ignore_for_file: type=lint
void registerPlugins() {}
| 0 |
mirrored_repositories/M-Box-Login-UI | mirrored_repositories/M-Box-Login-UI/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:lgoin_ui/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/fluttter_quiz_app | mirrored_repositories/fluttter_quiz_app/lib/quiz.dart | import 'package:flutter/material.dart';
import './question.dart';
import './answer.dart';
class Quiz extends StatelessWidget {
final int questionIndex;
final List<Map<String, Object>> questions;
final Function answerQusetionFunction;
Quiz(
{required this.questionIndex,
required this.questions,
required this.answerQusetionFunction});
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Question(questions[questionIndex]['questionText'].toString()),
for (var answer in (questions[questionIndex]['answers']
as List<Map<String, Object>>))
Answer(() => answerQusetionFunction(answer['score']),
answer['text'].toString()),
],
);
}
}
| 0 |
mirrored_repositories/fluttter_quiz_app | mirrored_repositories/fluttter_quiz_app/lib/question.dart | import 'package:flutter/material.dart';
class Question extends StatelessWidget {
final String questionText;
Question(this.questionText);
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
margin: EdgeInsets.all(10.0),
child: Text(
questionText,
style: TextStyle(fontSize: 28),
textAlign: TextAlign.center,
));
}
}
| 0 |
mirrored_repositories/fluttter_quiz_app | mirrored_repositories/fluttter_quiz_app/lib/answer.dart | import 'package:flutter/material.dart';
class Answer extends StatelessWidget {
final VoidCallback selectHandler;
final String answer;
Answer(this.selectHandler, this.answer);
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.blue),
),
onPressed: selectHandler,
child: Text(
answer,
),
),
);
}
}
| 0 |
mirrored_repositories/fluttter_quiz_app | mirrored_repositories/fluttter_quiz_app/lib/result.dart | import 'package:flutter/material.dart';
class Result extends StatelessWidget {
final int score;
final VoidCallback resetHandler;
Result(this.score, this.resetHandler);
String get resultPhrase {
final String resultText;
switch (score) {
case 1:
resultText = 'Good Job!';
break;
case 2:
resultText = 'Great Job!';
break;
case 3:
resultText = 'Excellent Job!';
break;
default:
resultText = 'You did it!';
break;
}
return resultText;
}
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: [
Text(
resultPhrase,
style: TextStyle(
fontSize: 36,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
TextButton(
onPressed: resetHandler,
child: Text(
'Restart Quiz',
style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold),
),
style: TextButton.styleFrom(
primary: Colors.blue,
)),
],
));
}
}
| 0 |
mirrored_repositories/fluttter_quiz_app | mirrored_repositories/fluttter_quiz_app/lib/main.dart | import 'package:flutter/material.dart';
import './quiz.dart';
import './result.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
var _questionIndex = 0;
var _totalScore = 0;
final _questions = const [
{
'questionText': 'What\'s the best color?',
'answers': [
{'text': 'Black', 'score': 0},
{'text': 'Red', 'score': 0},
{'text': 'White', 'score': 0},
{'text': 'Yellow <3', 'score': 1},
],
},
{
'questionText': 'What\'s the best animal?',
'answers': [
{'text': 'Dog', 'score': 1},
{'text': 'Cat', 'score': 0},
{'text': 'Tortoise', 'score': 0},
{'text': 'Bird', 'score': 0},
],
},
{
'questionText': 'What\'s the best italian dish?',
'answers': [
{'text': 'Spaghetti', 'score': 0},
{'text': 'Pizza', 'score': 1},
{'text': 'Lasagna', 'score': 0},
{'text': 'Italian breadsticks', 'score': 0},
],
},
];
void _answerQuestion(int score) {
_totalScore += score;
setState(() {
_questionIndex = _questionIndex + 1;
});
print(_totalScore);
}
void _resetQuiz() {
setState(() {
_questionIndex = 0;
_totalScore = 0;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
brightness: Brightness.light,
primaryColor: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text("Quiz App"),
),
body: _questionIndex < _questions.length
? Quiz(
questionIndex: _questionIndex,
questions: _questions,
answerQusetionFunction: _answerQuestion)
: Result(_totalScore, _resetQuiz),
),
);
}
}
| 0 |
mirrored_repositories/fluttter_quiz_app | mirrored_repositories/fluttter_quiz_app/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:fluttter_quiz_app/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(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/SaregamaApp | mirrored_repositories/SaregamaApp/lib/main.dart | // Author : Rahul Shahare
// Author url : https://github.com/Rahulshahare
// repository url : https://github.com/Rahulshahare/SaregamaApp
import 'package:flutter/material.dart';
import 'package:audioplayers/audio_cache.dart';
import 'package:double_back_to_close_app/double_back_to_close_app.dart';
import 'package:url_launcher/url_launcher.dart' as UrlLauncher;
void main() {
//runApp(MyApp());
runApp(
MaterialApp(
home: SecondRoute(),
title: 'SaReGaMa App',
)
);
}
Expanded _CreateButton(Color color, String filename ){
return(
Expanded(
child:FlatButton(
color: color,
onPressed: (){
final player = AudioCache();
player.play(filename);
},
) ,
)
);
}
Widget _buildArea(bool makeFade){
bool light = makeFade;
return(
SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
_CreateButton( light ? Colors.red[600] : Colors.red,'note1.wav'),
_CreateButton( light ? Colors.orange[600] : Colors.orange ,'note2.wav'),
_CreateButton( light ? Colors.yellow[600] : Colors.yellow ,'note3.wav'),
_CreateButton( light ? Colors.green[600] : Colors.green ,'note4.wav'),
_CreateButton( light ? Colors.blue[600] : Colors.blue ,'note5.wav'),
_CreateButton( light ? Colors.indigo[600] : Colors.indigo ,'note6.wav'),
_CreateButton( light ? Colors.purple[600] : Colors.purple ,'note7.wav'),
],
),
)
);
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
// This widget is the root of your application.
bool makeFade = false;
void _toggleTheme(){
setState(() {
if (makeFade) {
makeFade = false;
} else {
makeFade = true;
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.black,
brightness: Brightness.dark,
title: Text(
'Saregama App',
style: TextStyle(
fontFamily: 'Pacifico',
fontSize: 25.0,
),
),
actions: [
IconButton(
icon: Icon(Icons.language),
onPressed: (){
_toggleTheme();
},
),
IconButton(
icon: Icon(Icons.info),
onPressed: (){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
},
)
],
),
backgroundColor: Colors.black,
body: DoubleBackToCloseApp(
snackBar: const SnackBar(
content: Text('Tap Back again to Exit'),
),
child: _buildArea(makeFade),
),
);
}
}
class SecondRoute extends StatelessWidget {
final Uri _emailLaunchData = Uri(
scheme: 'mailto',
path: '[email protected]',
queryParameters: {
'subject':'Hey its from Saregama App',
'body':'Hi there, I am feeling happy to contact you',
}
);
final Uri _phoneLaunchData = Uri(
scheme: 'tel',
path: '+91 8999445733'
);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.black,
),
backgroundColor: Colors.teal,
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircleAvatar(
radius: 70.0,
backgroundImage: AssetImage('images/rahul.jpg'),
),
Text(
'Rahul Shahare',
style: TextStyle(
fontFamily: 'Pacifico',
fontSize: 40.0,
color: Colors.white,
),
),
Text(
'Founder CEO @ OCEANGREEN TECHNOLOGIES',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Source Sans Pro',
color: Colors.teal.shade100,
fontSize: 20.0,
letterSpacing: 1.0,
),
),
SizedBox(
height: 20.0,
width: 150.0,
child: Divider(
color: Colors.teal.shade100,
),
),
Card(
child: ListTile(
onTap: () => UrlLauncher.launch(_phoneLaunchData.toString()),
leading: Icon(
Icons.phone,
color: Colors.teal,
),
title: Text(
'8999445733',
style: TextStyle(
color: Colors.teal[900],
fontSize: 20.0,
),
),
),
),
Card(
child: ListTile(
onTap: () => UrlLauncher.launch(_emailLaunchData.toString()),
leading: Icon(
Icons.email,
color: Colors.teal,
),
title: Text(
'[email protected]',
style: TextStyle(
color: Colors.teal[900],
fontSize: 20.0,
),
),
),
),
SizedBox(
height: 20.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.android, size: 80.0,color: Colors.white,)
],
),
],
),
),
);
}
} | 0 |
mirrored_repositories/SaregamaApp | mirrored_repositories/SaregamaApp/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:SaregamaApp/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(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/snake_game_app | mirrored_repositories/snake_game_app/lib/dashboard_screen.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:math';
import 'package:flutter/services.dart';
enum Direction { up, down, left, right }
class DashboardScreen extends StatefulWidget {
const DashboardScreen({Key? key}) : super(key: key);
@override
State<DashboardScreen> createState() => _DashboardScreenState();
}
class _DashboardScreenState extends State<DashboardScreen> {
static const int gridSize = 20;
static const int snakeSpeed = 300;
List<int> snake = [45, 65, 85];
int food = Random().nextInt(gridSize * gridSize);
Direction direction = Direction.right;
bool isPlaying = false;
bool isGameOver = false;
@override
void initState() {
super.initState();
startGame();
}
void startGame() {
setState(() {
snake = [45, 65, 85];
direction = Direction.right;
isPlaying = true;
isGameOver = false;
});
moveSnake();
}
/*void moveSnake() async {
while (isPlaying) {
await Future.delayed(Duration(milliseconds: snakeSpeed));
setState(() {
final snakeHead = snake.last;
if (direction == Direction.right) {
if (snakeHead % gridSize == gridSize - 1 ||
snake.contains(snakeHead + 1)) {
gameOver();
return;
}
snake.add(snakeHead + 1);
} else if (direction == Direction.left) {
if (snakeHead % gridSize == 0 || snake.contains(snakeHead - 1)) {
gameOver();
return;
}
snake.add(snakeHead - 1);
} else if (direction == Direction.up) {
if (snakeHead < gridSize || snake.contains(snakeHead - gridSize)) {
gameOver();
return;
}
snake.add(snakeHead - gridSize);
} else if (direction == Direction.down) {
if (snakeHead >= (gridSize * gridSize) - gridSize ||
snake.contains(snakeHead + gridSize)) {
gameOver();
return;
}
snake.add(snakeHead + gridSize);
}
if (snake.last == food) {
generateFood();
} else {
snake.removeAt(0);
}
});
}
}
*/
void moveSnake() async {
while (isPlaying) {
await Future.delayed(Duration(milliseconds: snakeSpeed));
setState(() {
final snakeHead = snake.last;
if (direction == Direction.right) {
if (snakeHead % gridSize == gridSize - 1) {
gameOver();
return;
}
snake.add(snakeHead + 1);
} else if (direction == Direction.left) {
if (snakeHead % gridSize == 0) {
gameOver();
return;
}
snake.add(snakeHead - 1);
} else if (direction == Direction.up) {
if (snakeHead < gridSize) {
gameOver();
return;
}
snake.add(snakeHead - gridSize);
} else if (direction == Direction.down) {
if (snakeHead >= (gridSize * gridSize) - gridSize) {
gameOver();
return;
}
snake.add(snakeHead + gridSize);
}
if (snake.last == food) {
generateFood();
} else {
snake.removeAt(0);
}
});
}
}
void generateFood() {
final random = Random();
food = random.nextInt(gridSize * gridSize);
if (snake.contains(food)) {
generateFood();
}
}
void gameOver() {
setState(() {
isPlaying = false;
isGameOver = true;
});
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Game Over'),
content: Text('You scored ${snake.length - 3} points.'),
actions: [
ElevatedButton(
child: Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
void handleKeyPress(LogicalKeyboardKey key) {
if (!isPlaying) return;
if (key == LogicalKeyboardKey.arrowUp && direction != Direction.down) {
setState(() {
direction = Direction.up;
});
} else if (key == LogicalKeyboardKey.arrowDown &&
direction != Direction.up) {
setState(() {
direction = Direction.down;
});
} else if (key == LogicalKeyboardKey.arrowLeft &&
direction != Direction.right) {
setState(() {
direction = Direction.left;
});
} else if (key == LogicalKeyboardKey.arrowRight &&
direction != Direction.left) {
setState(() {
direction = Direction.right;
});
}
}
void toggleGame() {
setState(() {
isPlaying = !isPlaying;
});
if (isPlaying) {
moveSnake();
}
}
void restartGame() {
startGame();
}
Widget buildSnakeCell(int index) {
final isSnakeHead = index == snake.last;
final isSnakeBody = snake.contains(index);
final isFood = index == food;
Color cellColor;
if (isSnakeHead) {
cellColor = Colors.green;
} else if (isSnakeBody) {
cellColor = Colors.lightGreen;
} else if (isFood) {
cellColor = Colors.red;
} else {
cellColor = Colors.grey;
}
Widget getSnakeWidget() {
if (isSnakeHead) {
return Container(
color: Colors.green,
);
} else if (isSnakeBody) {
return Container(
color: Colors.lightGreen,
);
} else if (isFood) {
return Container(
child: Container(
color: Colors.red,
));
} else {
return Container(
color: Colors.grey,
);
}
}
return Container(
child: getSnakeWidget(),
/*decoration: BoxDecoration(
color: cellColor,
// borderRadius: BorderRadius.circular(4),
),*/
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Snake Game'),
),
body: GestureDetector(
behavior: HitTestBehavior.opaque,
onVerticalDragUpdate: (details) {
setState(() {
if (details.delta.dy > 0 && direction != Direction.up) {
direction = Direction.down;
} else if (details.delta.dy < 0 && direction != Direction.down) {
direction = Direction.up;
}
});
},
onHorizontalDragUpdate: (details) {
setState(() {
if (details.delta.dx > 0 && direction != Direction.left) {
direction = Direction.right;
} else if (details.delta.dx < 0 && direction != Direction.right) {
direction = Direction.left;
}
});
},
child: Container(
color: Colors.black,
child: Column(
children: [
Flexible(
child: GridView.builder(
itemCount: gridSize * gridSize,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: gridSize,
),
itemBuilder: (context, index) {
return buildSnakeCell(index);
},
),
),
Container(
padding: const EdgeInsets.all(40),
child: Column(
children: [
TextButton(
onPressed: () {
setState(() {
direction = Direction.up;
});
},
child: const Icon(
CupertinoIcons.arrow_up,
color: Colors.white,
size: 40,
)),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
TextButton(
onPressed: () {
setState(() {
direction = Direction.left;
});
},
child: const Icon(
CupertinoIcons.arrow_left,
color: Colors.white,
size: 40,
)),
TextButton(
onPressed: () {
setState(() {
direction = Direction.right;
});
},
child: const Icon(
CupertinoIcons.arrow_right,
color: Colors.white,
size: 40,
)),
],
),
TextButton(
onPressed: () {
setState(() {
direction = Direction.down;
});
},
child: const Icon(
CupertinoIcons.down_arrow,
color: Colors.white,
size: 40,
)),
],
),
)
],
),
),
),
bottomNavigationBar: BottomAppBar(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: toggleGame,
child: isPlaying ? const Text('Pause') : const Text('Play'),
),
ElevatedButton(
onPressed: isGameOver ? restartGame : null,
child: const Text('Restart'),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/snake_game_app | mirrored_repositories/snake_game_app/lib/main.dart | import 'package:flutter/material.dart';
import 'dashboard_screen.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 MaterialApp(
title: 'Snake Game App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const DashboardScreen(),
);
}
}
| 0 |
mirrored_repositories/snake_game_app | mirrored_repositories/snake_game_app/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:snake_game_app/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/swift_chat | mirrored_repositories/swift_chat/lib/main.dart | import 'package:flutter/material.dart';
import 'package:swift_chat/config/functions.dart';
import 'package:swift_chat/pages/splash_screen.dart';
import 'package:swift_chat/themes/theme.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await setAppName();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Swift Chat',
debugShowCheckedModeBanner: false,
theme: theme,
home: const SplashScreen(),
);
}
}
| 0 |
mirrored_repositories/swift_chat/lib/widgets | mirrored_repositories/swift_chat/lib/widgets/chat/no_room_found_dialog.dart | import 'package:flutter/material.dart';
import 'package:swift_chat/pages/home.dart';
class NoRoomFoundDialog extends StatefulWidget {
const NoRoomFoundDialog({ Key? key }) : super(key: key);
@override
_NoRoomFoundDialogState createState() => _NoRoomFoundDialogState();
}
class _NoRoomFoundDialogState extends State<NoRoomFoundDialog> {
@override
Widget build(BuildContext context) {
return AlertDialog(
icon: const Icon(Icons.priority_high_outlined),
title: const Text("No room found"),
content: const Text(
"Unable to find a room with the provided Room ID. Please try again with the correct ID or try creating a new chat room.",
),
actions: [
TextButton(
onPressed: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => const Home(),
),
);
},
child: const Text(
"Go Back",
),
),
],
);
}
}
| 0 |
mirrored_repositories/swift_chat/lib/widgets | mirrored_repositories/swift_chat/lib/widgets/chat/leave_chat_dialog.dart | import 'package:flutter/material.dart';
import 'package:swift_chat/pages/home.dart';
class LeaveChatDialog extends StatefulWidget {
final Function() leaveChat;
const LeaveChatDialog({
Key? key,
required this.leaveChat,
}) : super(key: key);
@override
_LeaveChatDialogState createState() => _LeaveChatDialogState();
}
class _LeaveChatDialogState extends State<LeaveChatDialog> {
@override
Widget build(BuildContext context) {
return AlertDialog(
icon: const Icon(Icons.exit_to_app_outlined),
title: const Text("Leave Chat Room"),
content: const Text(
"Are you sure that you want to leave the chat? You will not be able to see the previous messages again.",
),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text(
"Cancel",
),
),
TextButton(
onPressed: () {
widget.leaveChat();
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => const Home(),
),
);
},
child: const Text(
"Leave",
),
),
],
);
}
}
| 0 |
mirrored_repositories/swift_chat/lib/widgets | mirrored_repositories/swift_chat/lib/widgets/chat/chat_info_dialog.dart | // ignore_for_file: use_build_context_synchronously
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
class ChatInfoDialog extends StatefulWidget {
final bool isChatCreated;
final String chatRoomId;
const ChatInfoDialog({
Key? key,
required this.isChatCreated,
required this.chatRoomId,
}) : super(key: key);
@override
_ChatInfoDialogState createState() => _ChatInfoDialogState();
}
class _ChatInfoDialogState extends State<ChatInfoDialog> {
@override
Widget build(BuildContext context) {
return AlertDialog(
icon: const Icon(Icons.info_outline),
title: Text(
widget.isChatCreated
? "Chat Room Created"
: "Chat Room Joined",
),
content: widget.isChatCreated
? Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text(
"Welcome to the chat room! Please be aware that anyone can join using the chat room's unique ID. For your safety and privacy, avoid sharing personal information or important credentials during conversations or share the chat room's unique ID with only the people you trust. Let's keep the chat respectful and fun!"
),
const SizedBox(
height: 10.0,
),
Row(
children: [
const Text(
"Chat Unique ID: "
),
TextButton.icon(
onPressed: () async {
await Clipboard.setData(ClipboardData(text: widget.chatRoomId));
Fluttertoast.showToast(
msg: "ID copied to clipboard",
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
fontSize: 16.0,
backgroundColor: Theme.of(context).colorScheme.outline,
);
},
icon: const Icon(Icons.copy_outlined),
label: Text(
widget.chatRoomId,
),
),
],
),
],
)
: const Text(
"Welcome to the chat room! Please note that when joining this chat room, you will not be able to view previous messages. The conversation starts fresh from this point forward.",
),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text("OK"),
),
],
);
}
}
| 0 |
mirrored_repositories/swift_chat/lib/widgets | mirrored_repositories/swift_chat/lib/widgets/chat/chat_members_dialog.dart | import 'package:flutter/material.dart';
class ChatMembersDialog extends StatefulWidget {
final List<dynamic> chatMembers;
const ChatMembersDialog({
Key? key,
required this.chatMembers,
}) : super(key: key);
@override
_ChatMembersDialogState createState() => _ChatMembersDialogState();
}
class _ChatMembersDialogState extends State<ChatMembersDialog> {
@override
Widget build(BuildContext context) {
return AlertDialog(
icon: const Icon(Icons.contacts_outlined),
title: const Text("Chat Members List"),
content: SizedBox(
width: MediaQuery.of(context).size.width*0.7,
height: MediaQuery.of(context).size.height*0.5,
child: ListView.builder(
shrinkWrap: true,
itemCount: widget.chatMembers.length,
itemBuilder: ((context, index) {
final member = widget.chatMembers[index];
return ListTile(
title: Text(
"${index + 1}. $member",
),
);
})
),
),
actions: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Members Count: ${widget.chatMembers.length}",
),
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text(
"OK",
),
),
],
),
],
);
}
}
| 0 |
mirrored_repositories/swift_chat/lib/widgets | mirrored_repositories/swift_chat/lib/widgets/home/social_media_buttons.dart | // ignore_for_file: use_build_context_synchronously
import 'package:flutter/material.dart';
import 'package:flutter_social_button/flutter_social_button.dart';
import 'package:swift_chat/config/globals.dart';
import 'package:url_launcher/url_launcher.dart';
class SocialMediaButtons extends StatefulWidget {
const SocialMediaButtons({ Key? key }) : super(key: key);
@override
_SocialMediaButtonsState createState() => _SocialMediaButtonsState();
}
class _SocialMediaButtonsState extends State<SocialMediaButtons> {
Future<void> _openMail() async {
String? encodeQueryParameters(Map<String, String> params) {
return params.entries
.map((MapEntry<String, String> e) => '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}')
.join('&');
}
final Uri emailLaunchUri = Uri(
scheme: 'mailto',
path: mailAddress,
query: encodeQueryParameters(<String, String>{
'subject': '$appName Feedback',
}),
);
if(await canLaunchUrl(emailLaunchUri)) {
launchUrl(emailLaunchUri);
}
else {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Error'),
content: const Text(
'Error while opening mail.',
),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('OK'),
),
],
),
);
}
}
Future<void> _openSocialProfile(Uri profileLink) async {
if(!await launchUrl(profileLink, mode: LaunchMode.externalApplication)) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('Error'),
content: const Text(
'Error while opening profile.',
),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('OK'),
),
],
),
);
}
}
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
FlutterSocialButton(
onTap: _openMail,
buttonType: ButtonType.email,
title: "Send us a feedback",
mini: true,
),
FlutterSocialButton(
onTap: () {
_openSocialProfile(linkedInUrl);
},
buttonType: ButtonType.linkedin,
title: "Connect on LinkedIn",
mini: true,
),
FlutterSocialButton(
onTap: () {
_openSocialProfile(gitHubUrl);
},
buttonType: ButtonType.github,
title: "Follow on GitHub",
mini: true,
),
],
);
}
}
| 0 |
mirrored_repositories/swift_chat/lib/widgets | mirrored_repositories/swift_chat/lib/widgets/home/home_menu.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:swift_chat/config/globals.dart';
import 'package:swift_chat/pages/chat.dart';
import 'package:swift_chat/widgets/home/social_media_buttons.dart';
class HomeMenu extends StatefulWidget {
const HomeMenu({ Key? key }) : super(key: key);
@override
_HomeMenuState createState() => _HomeMenuState();
}
class _HomeMenuState extends State<HomeMenu> {
final TextEditingController _chatJoiningDetailsController = TextEditingController();
// isChatCreating bool will help to show dialog on the Chat page and show the Text button accordingly
void _showChatNameInputDialog(bool isChatCreating) {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
icon: const Icon(Icons.group_add_outlined),
title: Text(
isChatCreating ? "Enter Room Name" : "Enter Room ID",
),
content: TextFormField(
controller: _chatJoiningDetailsController,
keyboardType: TextInputType.name,
textCapitalization: TextCapitalization.words,
maxLength: isChatCreating ? 20 : 6,
maxLengthEnforcement: MaxLengthEnforcement.enforced,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
),
labelText: isChatCreating ? "Room Name" : "Room ID",
prefixIcon: Icon(
isChatCreating ? Icons.badge_outlined : Icons.pin_outlined
),
),
),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
_chatJoiningDetailsController.clear();
},
child: const Text("Cancel"),
),
TextButton(
onPressed: () {
if(_chatJoiningDetailsController.text.isNotEmpty) {
Navigator.pop(context);
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => Chat(
isChatCreated: isChatCreating,
chatJoiningDetails: _chatJoiningDetailsController.text
),
),
);
}
},
child: Text(
isChatCreating ? "Create" : "Join",
),
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
"Welcome, $userName",
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(
height: 20.0,
),
SizedBox(
width: MediaQuery.of(context).size.width,
child: ElevatedButton(
onPressed: () {
_showChatNameInputDialog(true);
},
child: const Text("Create a Chat Room"),
),
),
const SizedBox(
height: 20.0,
),
SizedBox(
width: MediaQuery.of(context).size.width,
child: ElevatedButton(
onPressed: () {
_showChatNameInputDialog(false);
},
child: const Text("Join a Chat Room"),
),
),
const SizedBox(
height: 20.0,
),
const SocialMediaButtons(),
],
);
}
}
| 0 |
mirrored_repositories/swift_chat/lib/widgets | mirrored_repositories/swift_chat/lib/widgets/home/login.dart | // ignore_for_file: use_build_context_synchronously
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:rounded_loading_button/rounded_loading_button.dart';
import 'package:swift_chat/config/functions.dart';
import 'package:swift_chat/config/globals.dart';
import 'package:swift_chat/widgets/home/social_media_buttons.dart';
class Login extends StatefulWidget {
final Function(bool) onNameProvided;
const Login({
Key? key,
required this.onNameProvided,
}) : super(key: key);
@override
_LoginState createState() => _LoginState();
}
class _LoginState extends State<Login> {
final RoundedLoadingButtonController _btnController = RoundedLoadingButtonController();
final TextEditingController _nameController = TextEditingController();
void _setName() {
Timer(const Duration(seconds: 2), () async {
setUserName(_nameController.text);
userName = await getUserName();
_btnController.success();
widget.onNameProvided(true);
});
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
"Register",
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(
height: 20.0,
),
TextFormField(
controller: _nameController,
keyboardType: TextInputType.name,
textCapitalization: TextCapitalization.words,
maxLength: 20,
maxLengthEnforcement: MaxLengthEnforcement.enforced,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
),
labelText: "Name",
prefixIcon: const Icon(Icons.badge_outlined),
),
),
const SizedBox(
height: 20.0,
),
RoundedLoadingButton(
controller: _btnController,
animateOnTap: false,
color: Theme.of(context).colorScheme.primary,
onPressed: () {
if(_nameController.text.isNotEmpty) {
_btnController.start();
_setName();
}
},
child: const Text(
'Continue',
style: TextStyle(color: Colors.white)
),
),
const SizedBox(
height: 20.0,
),
const SocialMediaButtons(),
],
);
}
}
| 0 |
mirrored_repositories/swift_chat/lib | mirrored_repositories/swift_chat/lib/pages/chat.dart | // ignore_for_file: use_build_context_synchronously
import 'package:flutter/material.dart';
import 'package:flutter_chat_bubble/chat_bubble.dart';
import 'package:socket_io_client/socket_io_client.dart' as IO;
import 'package:swift_chat/config/globals.dart';
import 'package:swift_chat/models/message_model.dart';
import 'package:swift_chat/widgets/chat/chat_info_dialog.dart';
import 'package:swift_chat/widgets/chat/chat_members_dialog.dart';
import 'package:swift_chat/widgets/chat/leave_chat_dialog.dart';
import 'package:swift_chat/widgets/chat/no_room_found_dialog.dart';
class Chat extends StatefulWidget {
// to handle that is the chat created or joined to show info dialog accordingly
final bool isChatCreated;
// this will work as chat name in case of creating a chat room and a chat room id in case of joining a chat room
final String chatJoiningDetails;
const Chat({
Key? key,
required this.isChatCreated,
required this.chatJoiningDetails,
}) : super(key: key);
@override
_ChatState createState() => _ChatState();
}
class _ChatState extends State<Chat> {
final List<MessageModel> _messages = [];
List<dynamic> _chatMembers = [];
late IO.Socket socket;
final TextEditingController _messageController = TextEditingController();
final ScrollController _chatScrollController = ScrollController();
String _chatName = "";
String _chatRoomId = "";
bool _canDisplayInfoDialog = true;
@override
void initState() {
super.initState();
setState(() {
_chatName = widget.chatJoiningDetails;
});
_handleSocketConnection();
}
void _handleSocketConnection() {
socket = IO.io("$ipAddress:5000", <String, dynamic>{
"transports": ["websocket"],
"autoConnect": false,
});
socket.connect();
// if isChatCreating is true then create a new chat room
if(widget.isChatCreated) {
// widget.chatJoiningDetails is chat room name in this case
socket.emit("create-chat", [userName, widget.chatJoiningDetails]);
// add the creator as the first user in list
setState(() {
_chatMembers.add(userName);
});
}
// if isChatCreating is false then join the user to the chat room
else {
setState(() {
_chatRoomId = widget.chatJoiningDetails;
});
// widget.chatJoiningDetails is chat room ID in this case
socket.emit("join-chat", [userName, widget.chatJoiningDetails]);
}
socket.onConnect((data) {
// in case of chat room creation
socket.on("generated-roomId", (roomId) {
// get the generated room ID from socket server and store it
setState(() {
_chatRoomId = roomId;
});
if(_canDisplayInfoDialog) {
_showInfoDialog();
}
});
// in case of chat room joining
socket.on("chat-room-name", (chatName) {
// get the chat room name from socket server and store it
setState(() {
_chatRoomId = widget.chatJoiningDetails;
_chatName = chatName;
});
if(_canDisplayInfoDialog) {
_showInfoDialog();
}
});
socket.on("room-not-found", (data) {
_showRoomNotFoundDialog();
});
// in case of sending or receiving messages
socket.on("message", (msg) {
_setMessage("destination", msg);
});
socket.on("user-joined", (memberName) {
_setMessage("system", "$memberName has joined the chat");
setState(() {
_chatMembers.add(memberName);
});
});
socket.on("members-list", (members) {
// receive members list from socket server and store it
setState(() {
_chatMembers = members;
});
});
socket.on("user-left", (memberName) {
_setMessage("system", "$memberName has left the chat");
setState(() {
_chatMembers.remove(memberName);
});
});
});
}
void _sendMessage() {
socket.emit("message", [_chatRoomId, _messageController.text]);
_setMessage("source", _messageController.text);
_messageController.clear();
}
void _setMessage(String type, String message) {
MessageModel messageModel = MessageModel(
type: type,
message: message,
);
setState(() {
_messages.add(messageModel);
});
// scroll to the bottom of chat list after setting message
Future.delayed(const Duration(milliseconds: 100), () {
_chatScrollController.animateTo(
_chatScrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 300),
curve: Curves.easeIn,
);
});
}
void _leaveChat() {
socket.emit("leave-chat", [userName, _chatRoomId]);
}
void _showInfoDialog() {
setState(() {
_canDisplayInfoDialog = false;
});
showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context) {
return ChatInfoDialog(
isChatCreated: widget.isChatCreated,
chatRoomId: _chatRoomId,
);
}
);
}
void _showRoomNotFoundDialog() {
setState(() {
_canDisplayInfoDialog = false;
});
showDialog(
barrierDismissible: false,
context: context,
builder: (context) {
return const NoRoomFoundDialog();
},
);
}
void _showChatMembersDialog() {
showDialog(
barrierDismissible: false,
context: context,
builder: (context) {
return ChatMembersDialog(
chatMembers: _chatMembers,
);
},
);
}
void _showLeaveChatDialog() {
showDialog(
barrierDismissible: false,
context: context,
builder: (context) {
return LeaveChatDialog(
leaveChat: _leaveChat,
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
centerTitle: true,
title: Text(
_chatName,
),
leading: IconButton(
onPressed: () {
_showInfoDialog();
},
icon: const Icon(Icons.info_outlined),
),
actions: [
IconButton(
onPressed: _showChatMembersDialog,
icon: const Icon(Icons.contacts_outlined),
),
IconButton(
onPressed: _showLeaveChatDialog,
icon: const Icon(Icons.exit_to_app_outlined)
),
],
),
body: Column(
children: [
Expanded(
child: ListView.builder(
controller: _chatScrollController,
itemCount: _messages.length,
itemBuilder: (context, index) {
final message = _messages[index];
return message.type != "system"
// display if the message is not a system type message
? ChatBubble(
clipper: message.type == "source"
? ChatBubbleClipper4(type: BubbleType.sendBubble)
: ChatBubbleClipper4(type: BubbleType.receiverBubble),
alignment: message.type == "source"
? Alignment.topRight
: Alignment.topLeft,
margin: const EdgeInsets.fromLTRB(10.0, 5.0, 10.0, 5.0),
backGroundColor: message.type == "source"
? Colors.blue
: const Color(0xffE7E7ED),
child: Container(
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * 0.7,
),
child: Text(
message.message,
style: TextStyle(
color: message.type == "source"
? Colors.white
: Colors.black,
fontWeight: FontWeight.bold,
),
),
),
)
// display if the message is a system type message
: Chip(
label: Text(
message.message,
),
shape: const StadiumBorder(),
);
},
)
),
Padding(
padding: const EdgeInsets.all(10.0),
child: TextFormField(
controller: _messageController,
keyboardType: TextInputType.multiline,
textCapitalization: TextCapitalization.sentences,
maxLines: null,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(50.0)
),
hintText: "Send Message",
prefixIcon: const Icon(Icons.keyboard_outlined),
suffixIcon: IconButton(
onPressed: () {
if(_messageController.text.isNotEmpty) {
_sendMessage();
}
},
icon: const Icon(Icons.send_outlined),
),
),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/swift_chat/lib | mirrored_repositories/swift_chat/lib/pages/no_internet_page.dart | import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
class NoInternetPage extends StatefulWidget {
final VoidCallback callBackFunction;
const NoInternetPage({
Key? key,
required this.callBackFunction,
}) : super(key: key);
@override
_NoInternetPageState createState() => _NoInternetPageState();
}
class _NoInternetPageState extends State<NoInternetPage> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: SvgPicture.asset(
'assets/images/illustrations/no-internet.svg',
width: 350.0,
height: 350.0,
),
),
Center(
child: SizedBox(
width: MediaQuery.of(context).size.width,
child: ElevatedButton.icon(
onPressed: widget.callBackFunction,
label: const Text("Retry"),
icon: const Icon(Icons.refresh_outlined),
),
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/swift_chat/lib | mirrored_repositories/swift_chat/lib/pages/splash_screen.dart | // ignore_for_file: use_build_context_synchronously
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:swift_chat/config/globals.dart';
import 'package:swift_chat/pages/home.dart';
import 'package:swift_chat/pages/no_internet_page.dart';
class SplashScreen extends StatefulWidget {
const SplashScreen({ Key? key }) : super(key: key);
@override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
bool _isConnected = true;
@override
void initState() {
super.initState();
_checkConnectivityStatus();
}
Future<void> _checkConnectivityStatus() async {
final connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile || connectivityResult == ConnectivityResult.wifi) {
_toggleIsConnected(true);
Future.delayed(const Duration(seconds: 3), _navigateToHome);
}
else {
_toggleIsConnected(false);
Fluttertoast.showToast(
msg: "No internet connection",
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
fontSize: 16.0,
backgroundColor: Theme.of(context).colorScheme.outline,
);
}
}
void _toggleIsConnected(bool value) {
setState(() {
_isConnected = value;
});
}
void _navigateToHome() async {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => const Home(),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: _isConnected
? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: Align(
alignment: Alignment.bottomCenter,
child: LoadingAnimationWidget.beat(
color: Theme.of(context).colorScheme.primary,
size: 50.0,
),
),
),
Expanded(
child: Container(
padding: const EdgeInsets.only(bottom: 32.0),
alignment: Alignment.bottomCenter,
child: Text(
appName,
style: Theme.of(context).textTheme.displaySmall,
),
),
),
],
)
: NoInternetPage(
callBackFunction: _checkConnectivityStatus,
),
);
}
}
| 0 |
mirrored_repositories/swift_chat/lib | mirrored_repositories/swift_chat/lib/pages/home.dart | // ignore_for_file: use_build_context_synchronously
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:swift_chat/config/globals.dart';
import 'package:swift_chat/widgets/home/home_menu.dart';
import 'package:swift_chat/widgets/home/login.dart';
class Home extends StatefulWidget {
const Home({ Key? key }) : super(key: key);
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
late bool _showHome;
bool _isLoading = true;
@override
void initState() {
super.initState();
_checkForUserName();
}
Future<void> _checkForUserName() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
userName = prefs.getString(swiftChatUserName) ?? "";
if(userName.isEmpty) {
_changeShowHomeState(false);
_toggleLoadingState();
}
else {
_changeShowHomeState(true);
_toggleLoadingState();
}
}
void _changeShowHomeState(bool value) {
setState(() {
_showHome = value;
});
}
void _toggleLoadingState() {
setState(() {
_isLoading = !_isLoading;
});
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
SystemNavigator.pop();
return false;
},
child: Scaffold(
resizeToAvoidBottomInset: false,
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
appName,
style: Theme.of(context).textTheme.displaySmall,
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Card(
elevation: 5.0,
child: Container(
padding: const EdgeInsets.all(20.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20.0)
),
child: _isLoading
? const CircularProgressIndicator() // show if loading is true
: _showHome
? const HomeMenu() // show if user name is available
: Login( // show if user name is not available
onNameProvided: (value) {
_changeShowHomeState(value);
},
),
),
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/swift_chat/lib | mirrored_repositories/swift_chat/lib/models/message_model.dart | class MessageModel {
String type;
String message;
MessageModel({
required this.message,
required this.type
});
}
| 0 |
mirrored_repositories/swift_chat/lib | mirrored_repositories/swift_chat/lib/config/globals.dart | // shared preferences variables
const String swiftChatUserName = "swift-chat-user-name";
// variables
String userName = "";
String appName = "";
// my mail address
const String mailAddress = "[email protected]";
// my LinkedIn profile url
final Uri linkedInUrl = Uri.parse('https://www.linkedin.com/in/syed-abdul-qadir-gillani/');
// my GitHub profile url
final Uri gitHubUrl = Uri.parse('https://github.com/SAQG007');
// ip address of the user's network
const String ipAddress = "http://192.168.0.104";
| 0 |
mirrored_repositories/swift_chat/lib | mirrored_repositories/swift_chat/lib/config/functions.dart | import 'package:package_info_plus/package_info_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:swift_chat/config/globals.dart';
Future<void> setAppName() async {
PackageInfo packageInfo = await PackageInfo.fromPlatform();
appName = packageInfo.appName;
}
void setUserName(String name) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString(swiftChatUserName, name);
}
Future<String> getUserName() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString(swiftChatUserName) ?? "";
}
| 0 |
mirrored_repositories/swift_chat/lib | mirrored_repositories/swift_chat/lib/themes/theme.dart | import 'package:flutter/material.dart';
const fontFamily = "Quicksand Regular";
ThemeData theme = ThemeData(
useMaterial3: true,
fontFamily: fontFamily,
brightness: Brightness.light,
colorScheme: const ColorScheme.light(
primary: Color(0xff6750A4),
onPrimary: Color(0xffFFFFFF),
primaryContainer: Color(0xffEADDFF),
onPrimaryContainer: Color(0xff21005D),
secondary: Color(0xff625B71),
onSecondary: Color(0xffFFFFFF),
secondaryContainer: Color(0xffE8DEF8),
onSecondaryContainer: Color(0xff1D192B),
tertiary: Color(0xff7D5260),
onTertiary: Color(0xffFFFFFF),
tertiaryContainer: Color(0xffFFD8E4),
onTertiaryContainer: Color(0xff31111D),
error: Color(0xffB3261E),
onError: Color(0xffFFFFFF),
errorContainer: Color(0xffF9DEDC),
onErrorContainer: Color(0xff410E0B),
background: Color(0xffFFFBFE),
onBackground: Color(0xff1C1B1F),
surface: Color(0xffFFFBFE),
onSurface: Color(0xff1C1B1F),
outline: Color(0xff79747E),
surfaceVariant: Color(0xffE7E0EC),
onSurfaceVariant: Color(0xff49454F),
),
appBarTheme: const AppBarTheme(
titleTextStyle: TextStyle(
fontFamily: fontFamily,
fontSize: 22,
fontWeight: FontWeight.w600,
color: Colors.black,
),
),
textTheme: const TextTheme(
labelLarge: TextStyle(
fontWeight: FontWeight.bold,
),
labelMedium: TextStyle(
fontWeight: FontWeight.bold,
),
),
);
| 0 |
mirrored_repositories/swift_chat | mirrored_repositories/swift_chat/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:swift_chat/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/flutter_BLoC_Weather_App | mirrored_repositories/flutter_BLoC_Weather_App/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'dart:async';
import './simple_bloc_delegate.dart';
import './blocs/blocs.dart';
import './services/services.dart';
import './widgets/widgets.dart';
import './models/models.dart';
void main() {
BlocSupervisor.delegate = SimpleBlocDelegate();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final WeatherAPIClient weatherAPIClient = WeatherAPIClient();
@override
Widget build(BuildContext context) {
return BlocProvider<ThemeBloc>(
create: (context) => ThemeBloc(),
child: BlocBuilder<ThemeBloc, ThemeData>(
builder: (context, theme) => MaterialApp(
title: 'Weather App',
debugShowCheckedModeBanner: false,
theme: theme,
home: BlocProvider<WeatherBloc>(
create: (context) =>
WeatherBloc(weatherAPIClient: weatherAPIClient),
child: WeatherPage()),
),
),
);
}
}
class WeatherPage extends StatefulWidget {
@override
_WeatherPageState createState() => _WeatherPageState();
}
class _WeatherPageState extends State<WeatherPage> {
Completer<void> _refreshCompleter;
@override
void initState() {
_refreshCompleter = Completer<void>();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Weather App'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
onPressed: () async {
final city = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CitySelection(),
),
);
if (city != null) {
BlocProvider.of<WeatherBloc>(context)
.add(FetchWeather(city: city));
}
},
),
IconButton(
icon: Icon(Icons.wb_sunny),
onPressed: () => context.bloc<ThemeBloc>().add(ThemeEvent.toggle),
)
],
),
body: BlocConsumer<WeatherBloc, WeatherState>(
listener: (context, state) {
if (state is WeatherLoaded) {
_refreshCompleter?.complete();
}
},
builder: (context, state) {
if (state is WeatherEmpty) {
return Center(child: Text('Please Select a Location'));
}
if (state is WeatherLoading) {
return Center(child: CircularProgressIndicator());
}
if (state is WeatherError) {
return Center(
child: Text(
'Something went wrong!',
style: TextStyle(color: Colors.red),
),
);
}
if (state is WeatherLoaded) {
final Weather weather = state.weather;
return RefreshIndicator(
onRefresh: () {
if (_refreshCompleter.isCompleted) {
_refreshCompleter = Completer();
}
BlocProvider.of<WeatherBloc>(context).add(
RefreshWeather(city: weather.locationName),
);
return _refreshCompleter.future;
},
child: ListView(
children: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 100),
child: Center(
child: Column(
children: [
Text(
weather.locationName,
style: TextStyle(fontSize: 25),
),
SizedBox(
height: 10,
),
Text(
'Temperature: ${weather.temp} °C ${weather.iconString}',
style: TextStyle(fontSize: 20),
),
SizedBox(
height: 10,
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
Text('Min Temp: ${weather.minTemp} °C'),
SizedBox(
width: 30,
),
Text('Max Temp: ${weather.maxTemp} °C')
],
),
SizedBox(
height: 10,
),
Text("Last Updated at: ${weather.time}")
],
),
),
),
],
),
);
}
return Container();
},
),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Weather App'),
),
body: Center(
child: Text('This Weather App using BLoC'),
),
);
}
}
| 0 |
mirrored_repositories/flutter_BLoC_Weather_App | mirrored_repositories/flutter_BLoC_Weather_App/lib/simple_bloc_delegate.dart | import 'package:bloc/bloc.dart';
class SimpleBlocDelegate extends BlocDelegate {
@override
void onEvent(Bloc bloc, Object event) {
super.onEvent(bloc, event);
print('onEvent $event');
}
@override
onTransition(Bloc bloc, Transition transition) {
super.onTransition(bloc, transition);
print('onTransition $transition');
}
@override
void onError(Bloc bloc, Object error, StackTrace stacktrace) {
super.onError(bloc, error, stacktrace);
print('onError $error');
}
}
| 0 |
mirrored_repositories/flutter_BLoC_Weather_App/lib | mirrored_repositories/flutter_BLoC_Weather_App/lib/widgets/city_selection.dart | import 'package:flutter/material.dart';
class CitySelection extends StatefulWidget {
@override
State<CitySelection> createState() => _CitySelectionState();
}
class _CitySelectionState extends State<CitySelection> {
final TextEditingController _textController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('City'),
),
body: Form(
child: Row(
children: [
Expanded(
child: Padding(
padding: EdgeInsets.only(left: 10.0),
child: TextFormField(
controller: _textController,
decoration: InputDecoration(
labelText: 'City',
hintText: 'Chicago',
),
),
),
),
IconButton(
icon: Icon(Icons.search),
onPressed: () {
Navigator.pop(context, _textController.text);
},
)
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutter_BLoC_Weather_App/lib | mirrored_repositories/flutter_BLoC_Weather_App/lib/widgets/widgets.dart | export './city_selection.dart'; | 0 |
mirrored_repositories/flutter_BLoC_Weather_App/lib | mirrored_repositories/flutter_BLoC_Weather_App/lib/blocs/weather_bloc.dart | import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';
import '../models/models.dart';
import '../services/services.dart';
/*
There are two weather Event
1. Fetch Weather loads new weather data
2. Refresh Weather update the existing weather data
*/
abstract class WeatherEvent extends Equatable {
const WeatherEvent();
}
class FetchWeather extends WeatherEvent {
final String city;
const FetchWeather({@required this.city}) : assert(city != null);
//assert make sure that city must not be null
@override
List<Object> get props => [city];
}
class RefreshWeather extends WeatherEvent {
final String city;
const RefreshWeather({@required this.city}) : assert(city != null);
@override
List<Object> get props => [city];
}
/*
We have four state for Weather App
1. Empty : There is no weather data
2. Loading : App is loading the weather data currently doing the networking stuff
3. Loaded: We have loaded Weather data now pass it the scree
4. Error : We have error while loading the data
*/
abstract class WeatherState extends Equatable {
const WeatherState();
@override
List<Object> get props => [];
}
class WeatherEmpty extends WeatherState {}
class WeatherLoading extends WeatherState {}
class WeatherLoaded extends WeatherState {
final Weather weather;
const WeatherLoaded({@required this.weather}) : assert(weather != null);
@override
List<Object> get props => [weather];
}
class WeatherError extends WeatherState {}
// Here is our BLoC
class WeatherBloc extends Bloc<WeatherEvent, WeatherState> {
final WeatherAPIClient weatherAPIClient;
WeatherBloc({@required this.weatherAPIClient}):assert(weatherAPIClient != null);
//our initial state is empty
@override
WeatherState get initialState => WeatherEmpty();
//Event to State
@override
Stream<WeatherState> mapEventToState(WeatherEvent event) async* {
if (event is FetchWeather) {
yield* _mapFetchWeatherToState(event);
} else if (event is RefreshWeather) {
yield* _mapRefreshWeatherToState(event);
}
}
//if event is FetchEvent
Stream<WeatherState> _mapFetchWeatherToState(FetchWeather event) async* {
//set the state to loading the data
yield WeatherLoading();
//load the data
try {
final Weather weather = await weatherAPIClient.fetchData(event.city);
//data loading completed
//set the state to loading completed
yield WeatherLoaded(weather: weather);
} catch (error) {
print(error);
//if error occured then set the state to WeatherError
yield WeatherError();
}
}
//refresh Event
Stream<WeatherState> _mapRefreshWeatherToState(RefreshWeather event) async* {
try {
//fetch data
final Weather weather = await weatherAPIClient.fetchData(event.city);
//data is loaded so update the UI by WeatherLoaded State with new weather data
yield WeatherLoaded(weather: weather);
} catch (_) {
//if error occurs then simple returns the current state
//we do not want to change state
yield state;
}
}
}
| 0 |
mirrored_repositories/flutter_BLoC_Weather_App/lib | mirrored_repositories/flutter_BLoC_Weather_App/lib/blocs/blocs.dart | export './weather_bloc.dart';
export './theme_bloc.dart'; | 0 |
mirrored_repositories/flutter_BLoC_Weather_App/lib | mirrored_repositories/flutter_BLoC_Weather_App/lib/blocs/theme_bloc.dart | import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter/material.dart';
enum ThemeEvent { toggle }
class ThemeBloc extends Bloc<ThemeEvent, ThemeData> {
@override
ThemeData get initialState => ThemeData.light();
@override
Stream<ThemeData> mapEventToState(ThemeEvent event) async* {
switch (event) {
case ThemeEvent.toggle:
yield state == ThemeData.dark() ? ThemeData.light() : ThemeData.dark();
break;
}
}
} | 0 |
mirrored_repositories/flutter_BLoC_Weather_App/lib | mirrored_repositories/flutter_BLoC_Weather_App/lib/models/weather.dart | import 'package:equatable/equatable.dart';
class Weather extends Equatable{
final int id;
final String locationName;
final double minTemp;
final double temp;
final double maxTemp;
final String iconString;
final DateTime time;
const Weather({
this.id,
this.locationName,
this.temp,
this.minTemp,
this.maxTemp,
this.iconString,
this.time
});
@override
List<Object> get props => [id,locationName,temp,minTemp,maxTemp,iconString,time];
//convert the JSON to Weather Object
static Weather fromJson(dynamic weatherDataJSON) {
Weather weather=Weather(
id : weatherDataJSON['weather'][0]['id'].toInt(),
locationName: weatherDataJSON['name'],
temp: weatherDataJSON['main']['temp'].toDouble(),
minTemp: weatherDataJSON['main']['temp_min'].toDouble(),
maxTemp: weatherDataJSON['main']['temp_max'].toDouble(),
iconString: getWeatherIcon(weatherDataJSON['weather'][0]['id']),
time: DateTime.now()
);
return weather;
}
//get the icon according to the Condition
//Condition description is provided by API
static String getWeatherIcon(int condition) {
if (condition < 300) {
return '🌩';
} else if (condition < 400) {
return '🌧';
} else if (condition < 600) {
return '☔️';
} else if (condition < 700) {
return '☃️';
} else if (condition < 800) {
return '🌫';
} else if (condition == 800) {
return '☀️';
} else if (condition <= 804) {
return '☁️';
} else {
return '🤷';
}
}
} | 0 |
mirrored_repositories/flutter_BLoC_Weather_App/lib | mirrored_repositories/flutter_BLoC_Weather_App/lib/models/models.dart | export './weather.dart'; | 0 |
mirrored_repositories/flutter_BLoC_Weather_App/lib | mirrored_repositories/flutter_BLoC_Weather_App/lib/services/weather_api_client.dart | import 'dart:convert';
import 'package:http/http.dart' as http;
import '../app_Data.dart';
import '../models/models.dart' ;
class WeatherAPIClient{
Future<Weather> fetchData(String cityName)async{
final http.Client httpClient=http.Client();
final String weatherUrl='$openWeatherMapUrl?q=$cityName&appid=$apiKey&units=metric';
http.Response weatherResponse=await httpClient.get(weatherUrl);
if(weatherResponse.statusCode!=200){
print(weatherResponse.body);
throw Exception('error getting weather for location');
}
var weatherJSON=jsonDecode(weatherResponse.body);
var weatherObject= Weather.fromJson(weatherJSON);
return weatherObject;
}
} | 0 |
mirrored_repositories/flutter_BLoC_Weather_App/lib | mirrored_repositories/flutter_BLoC_Weather_App/lib/services/services.dart | export './weather_api_client.dart'; | 0 |
mirrored_repositories/flutter_BLoC_Weather_App | mirrored_repositories/flutter_BLoC_Weather_App/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:flutter_bloc_weather_app/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(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/Stay-safe-from-Corono-Virus | mirrored_repositories/Stay-safe-from-Corono-Virus/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'Constant/routes.dart';
import 'home.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.red,
),
debugShowCheckedModeBanner: false,
home: SplashScreen(),
routes: {
Routes.home : (context)=>Home()
},
);
}
}
class SplashScreen extends StatefulWidget {
@override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
super.initState();
Future.delayed(Duration(seconds: 4),(){
Navigator.pushReplacementNamed(context, Routes.home);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children:<Widget>[
Container(
height: MediaQuery.of(context).size.height/5,
child: Image.asset('assets/covid-virus.png')
),
Text("Stay Safe from Corona",style: TextStyle(fontSize:30,color: Colors.black54,fontWeight: FontWeight.bold),),
SpinKitSquareCircle(
color: Colors.red,
size: 50.0,
)
]
),
);
}
} | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.