repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
mirrored_repositories/note_keep_up/lib/core/util/constants
|
mirrored_repositories/note_keep_up/lib/core/util/constants/icons/app_icons.dart
|
import 'package:flutter/material.dart';
/// Icon ideentifiers for the app.
@immutable
class AppIcons {
const AppIcons._();
static const arrowBack = Icon(Icons.arrow_back_rounded);
//=> Darawer Icon
static const pen = Icon(Icons.mode_edit_outline_rounded);
static const archive = Icon(Icons.archive_rounded);
static const trash = Icon(Icons.delete);
static const setting = Icon(Icons.settings);
//=> SearchBar Icon
static const menu = Icon(Icons.menu_sharp);
static const grip = Icons.view_agenda_outlined;
static const gripVertical = Icons.grid_view_outlined;
static const searchNote = Icon(Icons.search);
//=> Home Page
static const add = Icon(Icons.add);
//=> Note Page
static const archiveNote = Icon(Icons.archive_outlined);
static const unarchiveNote = Icon(Icons.unarchive_outlined);
static const pin = Icons.push_pin_rounded;
static const unPin = Icons.push_pin_outlined;
static const rede = Icon(Icons.redo);
static const undo = Icon(Icons.undo);
static const more = Icon(Icons.more_vert_outlined);
static const drawColor = Icon(Icons.color_lens_outlined);
static const defuaulCheckColor = Icon(Icons.format_color_reset_outlined);
static const check = Icon(Icons.check_rounded, color: Colors.blueAccent);
static const trashNote = Icon(Icons.delete_outline_rounded);
static const sendNote = Icon(Icons.share_sharp);
static const deleteNote = Icon(Icons.delete_forever_outlined);
static const restoreNote = Icon(Icons.restore);
static const themes = Icon(Icons.color_lens_outlined);
// Empty Notes
static const emptySearch = Icon(Icons.search, size: 100);
static const emptyNote = Icon(Icons.landscape_outlined, size: 150);
static const emptyArchivesNote = Icon(Icons.archive_outlined, size: 150);
static const emptyTrashNote = Icon(Icons.delete_outline_rounded, size: 150);
// Error Notes
static const error = Icon(Icons.error_outline_outlined, size: 150);
static final List<String> profiles = [
'assets/image/profile_1.png',
'assets/image/profile_2.png',
'assets/image/profile_3.png',
'assets/image/profile_4.png',
'assets/image/profile_5.png',
];
}
| 0
|
mirrored_repositories/note_keep_up/lib/core/util
|
mirrored_repositories/note_keep_up/lib/core/util/device/app_device.dart
|
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class AppDevice {
static SystemUiOverlayStyle setStatusBartSilverAppBar() {
return SystemUiOverlayStyle.light.copyWith(
systemNavigationBarColor: Colors.transparent,
statusBarColor: Colors.transparent,
);
// }
}
// static void setNavigationBarColor(Color color) {
// return SystemChrome.setSystemUIOverlayStyle(
// SystemUiOverlayStyle(
// systemNavigationBarColor: color,
// systemNavigationBarDividerColor: color,
// ),
// );
// }
static void setStatusBart(BuildContext context) {
Brightness statusBarIconBrightness =
MediaQuery.of(context).platformBrightness == Brightness.dark
? Brightness.light
: Brightness.dark;
SystemUiOverlayStyle systemUiOverlayStyle =
const SystemUiOverlayStyle().copyWith(
statusBarColor: Colors.transparent,
statusBarIconBrightness: statusBarIconBrightness,
systemNavigationBarIconBrightness: statusBarIconBrightness,
systemNavigationBarColor: Colors.transparent,
systemNavigationBarDividerColor: Colors.transparent,
systemNavigationBarContrastEnforced: false,
systemStatusBarContrastEnforced: false,
);
SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
SystemChrome.setEnabledSystemUIMode(
SystemUiMode.manual,
overlays: [SystemUiOverlay.top, SystemUiOverlay.bottom],
);
SystemChrome.setEnabledSystemUIMode(
SystemUiMode.edgeToEdge,
overlays: [SystemUiOverlay.bottom],
);
SystemChrome.setEnabledSystemUIMode(
SystemUiMode.edgeToEdge,
);
}
}
| 0
|
mirrored_repositories/note_keep_up/lib/core/util
|
mirrored_repositories/note_keep_up/lib/core/util/device/device.dart
|
export 'app_device.dart';
| 0
|
mirrored_repositories/note_keep_up/lib/core/util
|
mirrored_repositories/note_keep_up/lib/core/util/extensions/app_extensions.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import '../../../features/data/datasources/local/hive/state_note_hive.dart';
import '../../../features/presentation/blocs/blocs.dart';
import '../../config/enum/enum.dart';
import '../util.dart';
extension BuildContextExtensions on BuildContext {
ThemeData get _theme => Theme.of(this);
TextTheme get textTheme => _theme.textTheme;
ColorScheme get colorScheme => _theme.colorScheme;
Size get deviceSize => MediaQuery.sizeOf(this);
}
extension StateGridViewIcon on GridStatus {
IconData get icon {
switch (this) {
case GridStatus.singleView:
return AppIcons.grip;
case GridStatus.multiView:
return AppIcons.gripVertical;
}
}
}
extension DrawerViewsExtensions on DrawerViews {
String get name {
switch (this) {
case DrawerViews.home:
return 'Notes';
case DrawerViews.archive:
return 'Archive';
case DrawerViews.trash:
return 'Trash';
case DrawerViews.setting:
return 'Setting';
}
}
Icon get icon {
switch (this) {
case DrawerViews.home:
return AppIcons.pen;
case DrawerViews.archive:
return AppIcons.archive;
case DrawerViews.trash:
return AppIcons.trash;
case DrawerViews.setting:
return AppIcons.setting;
}
}
void Function(BuildContext context) get onTapItemDrawer {
return (context) {
if (this != DrawerViews.setting) DrawerSelect.selectedDrawerView = this;
DrawerSelect.selectedDrawerSection = drawerSectionForView(this);
context.read<NoteBloc>().add(RefreshNotes(DrawerSelect.drawerSection));
final String? routerName = routerNameForView(this);
if (routerName != null) {
if (routerName == AppRouterName.setting.name) {
GoRouter.of(context).pushNamed(routerName);
} else {
GoRouter.of(context).goNamed(routerName);
}
}
Navigator.pop(context);
};
}
String? routerNameForView(DrawerViews view) {
switch (view) {
case DrawerViews.home:
return AppRouterName.home.name;
case DrawerViews.archive:
return AppRouterName.archive.name;
case DrawerViews.trash:
return AppRouterName.trash.name;
case DrawerViews.setting:
return AppRouterName.setting.name;
default:
return null;
}
}
DrawerSectionView drawerSectionForView(DrawerViews view) {
switch (view) {
case DrawerViews.home:
return DrawerSectionView.home;
case DrawerViews.archive:
return DrawerSectionView.archive;
case DrawerViews.trash:
return DrawerSectionView.trash;
default:
return DrawerSelect.drawerSection;
}
}
}
extension StatusNoteX on StatusNote {
StateNoteHive get stateNoteHive {
switch (this) {
case StatusNote.undefined:
return StateNoteHive.unspecified;
case StatusNote.pinned:
return StateNoteHive.pinned;
case StatusNote.archived:
return StateNoteHive.archived;
case StatusNote.trash:
return StateNoteHive.trash;
}
}
}
extension StatusHiveNoteX on StateNoteHive {
StatusNote get stateNote {
switch (this) {
case StateNoteHive.unspecified:
return StatusNote.undefined;
case StateNoteHive.pinned:
return StatusNote.pinned;
case StateNoteHive.archived:
return StatusNote.archived;
case StateNoteHive.trash:
return StatusNote.trash;
}
}
}
| 0
|
mirrored_repositories/note_keep_up/lib/core/util
|
mirrored_repositories/note_keep_up/lib/core/util/extensions/extensions.dart
|
export 'app_extensions.dart';
| 0
|
mirrored_repositories/note_keep_up/lib/core/util
|
mirrored_repositories/note_keep_up/lib/core/util/errors/exception.dart
|
class NoDataException implements Exception {}
class ConnectionException implements Exception {}
| 0
|
mirrored_repositories/note_keep_up/lib/core/util
|
mirrored_repositories/note_keep_up/lib/core/util/errors/failure.dart
|
import 'package:equatable/equatable.dart';
abstract class Failure extends Equatable {}
class NoDataFailure extends Failure {
@override
List<Object> get props => [];
}
class EmpytInputFailure extends Failure {
@override
List<Object> get props => [];
}
class DatabaseFailure extends Failure {
@override
List<Object> get props => [];
}
class RetrieveFailure extends Failure {
@override
List<Object> get props => [];
}
| 0
|
mirrored_repositories/note_keep_up/lib/core/util
|
mirrored_repositories/note_keep_up/lib/core/util/errors/errors.dart
|
export 'exception.dart';
export 'failure.dart';
| 0
|
mirrored_repositories/note_keep_up/lib/core/util
|
mirrored_repositories/note_keep_up/lib/core/util/alerts/alerts.dart
|
export 'app_alerts.dart';
| 0
|
mirrored_repositories/note_keep_up/lib/core/util
|
mirrored_repositories/note_keep_up/lib/core/util/alerts/app_alerts.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import '../../../features/domain/entities/note.dart';
import '../../../features/presentation/blocs/blocs.dart';
import '../../core.dart';
@immutable
class AppAlerts {
const AppAlerts._();
static void _displaySnackBar(
BuildContext context,
String message,
String? actionLabel,
void Function()? onPressed,
) {
ScaffoldMessenger.of(context)
..removeCurrentSnackBar()
..showSnackBar(
SnackBar(
content: Text(message, style: context.textTheme.bodyMedium),
duration: const Duration(seconds: 2),
behavior: SnackBarBehavior.floating,
backgroundColor: context.colorScheme.primaryContainer,
action: onPressed != null
? SnackBarAction(
textColor: context.colorScheme.onBackground,
label: actionLabel!,
onPressed: onPressed,
)
: null,
),
);
}
static void displaySnackbarMsg(BuildContext context, String message) {
_displaySnackBar(context, message, null, null);
}
static void displaySnackarUndoMove(BuildContext context, String message) {
_displaySnackBar(
context,
message,
'Undo',
() => context.read<NoteBloc>().add(UndoMoveNote()),
);
}
static void displaySnackarRecycle(BuildContext context, String message) {
_displaySnackBar(
context,
message,
'Recycle',
() {
final noteStatusState = context.read<StatusIconsCubit>().state;
if (noteStatusState is ReadOnlyState) {
final currentNote = noteStatusState.currentNote;
context
.read<NoteBloc>()
.add(MoveNote(currentNote, StatusNote.undefined));
}
},
);
}
static Future<void> showAlertDeleteDialog(
BuildContext context,
Note note,
) async {
Widget cancelButton = TextButton(
child: const Text('NO'),
onPressed: () {
context.pop();
context.pop();
},
);
Widget deleteButton = TextButton(
child: const Text('YES'),
onPressed: () {
context.pop();
context.pop();
context.read<NoteBloc>().add(DeleteNote(note.id));
context.read<NoteBloc>().add(RefreshNotes(DrawerSelect.drawerSection));
},
);
AlertDialog alert = AlertDialog(
backgroundColor: ColorNote.getColor(context, note.colorIndex),
content: const Text('Are you sure you want to delete this Note?'),
actions: [
deleteButton,
cancelButton,
],
);
await showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
}
| 0
|
mirrored_repositories/ATM-App-in-Flutter
|
mirrored_repositories/ATM-App-in-Flutter/lib/main.dart
|
import 'package:atmproject/configs/themes.dart';
import 'package:atmproject/screens/atm_number.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "ATM Project",
theme: defaultTheme,
debugShowCheckedModeBanner: false,
home: const AtmNumber(),
);
}
}
| 0
|
mirrored_repositories/ATM-App-in-Flutter/lib
|
mirrored_repositories/ATM-App-in-Flutter/lib/widgets/confirm_dialog.dart
|
import 'package:atmproject/utils/transaction.dart';
import 'package:flutter/material.dart';
void confirmDialog(
BuildContext context, String atmNo, int amount, String balType) {
showDialog(
context: context,
builder: (context) => AlertDialog(
actionsAlignment: MainAxisAlignment.spaceEvenly,
backgroundColor: const Color(0xFF223155),
title: const Text(
'Confirm Withdraw?',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.w600,
height: 1.11,
letterSpacing: -0.32,
),
),
content: Text(
'Are you sure you want to withdraw \n Rs. $amount?',
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.w400,
height: 1.5,
letterSpacing: -0.32,
),
),
actions: [
ElevatedButton(
onPressed: () {
transaction(context, atmNo, amount, balType);
Navigator.pop(context);
},
style: ButtonStyle(
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(27),
)),
backgroundColor:
MaterialStateProperty.all<Color>(const Color(0xFF00B8EE)),
),
child: const Text('Yes',
style: TextStyle(
color: Colors.white,
))),
ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
style: ButtonStyle(
shape: MaterialStateProperty.all<RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(27),
)),
backgroundColor:
MaterialStateProperty.all<Color>(const Color(0xFF00B8EE)),
),
child: const Text('No',
style: TextStyle(
color: Colors.white,
))),
],
),
);
}
| 0
|
mirrored_repositories/ATM-App-in-Flutter/lib
|
mirrored_repositories/ATM-App-in-Flutter/lib/widgets/success_dialog.dart
|
import 'package:flutter/material.dart';
void successDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) => const AlertDialog(
actionsAlignment: MainAxisAlignment.spaceEvenly,
backgroundColor: Color(0xFF223155),
title: Text(
'Withdraw Successful',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18,
color: Colors.white,
fontWeight: FontWeight.w600,
height: 1.11,
letterSpacing: -0.32,
),
),
icon: Icon(
Icons.check_circle,
color: Color(0xFF00B8EE),
size: 50,
),
),
);
}
| 0
|
mirrored_repositories/ATM-App-in-Flutter/lib
|
mirrored_repositories/ATM-App-in-Flutter/lib/configs/themes.dart
|
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
final ThemeData defaultTheme = ThemeData(
useMaterial3: false,
primaryColor: const Color(0xFF232938),
primarySwatch: Colors.grey,
scaffoldBackgroundColor: const Color(0xFF3c465c),
fontFamily: GoogleFonts.inter().fontFamily,
textTheme: const TextTheme(
bodyMedium: TextStyle(color: Colors.white),
bodySmall: TextStyle(color: Colors.white),
bodyLarge: TextStyle(color: Colors.white),
),
);
| 0
|
mirrored_repositories/ATM-App-in-Flutter/lib
|
mirrored_repositories/ATM-App-in-Flutter/lib/configs/default.dart
|
import 'dart:io';
import 'package:encrypt/encrypt.dart';
import 'package:path_provider/path_provider.dart';
defaultDir() async {
final Directory? jsonDir = await getDownloadsDirectory();
String jsonPath = '${jsonDir?.path}/atm.json';
File dfile = File(jsonPath);
return dfile;
}
String defaultJSON(String atmNo, String atmPIN) {
return '[{"atmNo":"$atmNo","atmPIN":"$atmPIN","chkBal":"25000","savBal":"25000"}]';
}
Map defaultMap(String atmNo, String atmPIN) {
return {
'atmNo': atmNo,
'atmPIN': atmPIN,
'chkBal': '25000',
'savBal': '25000'
};
}
final key = Key.fromUtf8('1234567891011121');
final iv = IV.fromLength(0);
final encrypter = Encrypter(AES(key, padding: null));
| 0
|
mirrored_repositories/ATM-App-in-Flutter/lib
|
mirrored_repositories/ATM-App-in-Flutter/lib/utils/transaction.dart
|
import 'dart:convert';
import 'dart:io';
import 'package:atmproject/configs/default.dart';
import 'package:atmproject/widgets/success_dialog.dart';
import 'package:encrypt/encrypt.dart';
import 'package:fluttertoast/fluttertoast.dart';
void transaction(context, String atmNo, amount, balType) async {
File file = await defaultDir();
String jsonRaw = await file.readAsString();
final jsonEncrypted = Encrypted.fromBase64(jsonRaw);
final decrypted = encrypter.decrypt(jsonEncrypted, iv: iv);
var jsonParsed = json.decode(decrypted);
var newJson = jsonParsed.map((e) {
if (e['atmNo'] == atmNo) {
int oldBal = int.parse(e[balType]);
if (oldBal >= amount) {
num newBal = oldBal - amount;
e[balType] = newBal.toString();
successDialog(context);
} else {
Fluttertoast.showToast(msg: 'Insufficient Balance');
}
}
return e;
}).toList();
final newJsonEncrypted = encrypter.encrypt(json.encode(newJson), iv: iv);
await file.writeAsString(newJsonEncrypted.base64);
}
| 0
|
mirrored_repositories/ATM-App-in-Flutter/lib
|
mirrored_repositories/ATM-App-in-Flutter/lib/utils/setup_json.dart
|
import 'dart:convert';
import 'dart:io';
import 'package:atmproject/configs/default.dart';
import 'package:encrypt/encrypt.dart';
Future<bool> setupJSON(String atmNo, String atmPIN) async {
bool accLogged = false;
File file = await defaultDir();
if (file.existsSync()) {
var jsonRaw = await file.readAsString();
var jsonEncrypted = Encrypted.fromBase64(jsonRaw);
var decrypted = encrypter.decrypt(jsonEncrypted, iv: iv);
List jsonList = json.decode(decrypted);
jsonList.map((e) {
if (e['atmNo'] == atmNo) {
return accLogged = true;
}
}).toList();
if (!accLogged) {
Map toAddMap = defaultMap(atmNo, atmPIN);
jsonList.add(toAddMap);
var jsonAdded = json.encode(jsonList);
final encrypted = encrypter.encrypt(jsonAdded, iv: iv);
file.writeAsString(encrypted.base64);
}
} else {
final encrypted = encrypter.encrypt(defaultJSON(atmNo, atmPIN), iv: iv);
file.writeAsString(encrypted.base64);
}
return accLogged;
}
| 0
|
mirrored_repositories/ATM-App-in-Flutter/lib
|
mirrored_repositories/ATM-App-in-Flutter/lib/screens/menu.dart
|
import 'package:atmproject/screens/balance_check.dart';
import 'package:atmproject/screens/withdraw/withdraw.dart';
import 'package:atmproject/utils/setup_json.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
class Menu extends StatefulWidget {
final String atmNo, atmPIN;
const Menu(this.atmNo, this.atmPIN, {super.key});
@override
State<Menu> createState() => _MenuState();
}
class _MenuState extends State<Menu> {
@override
void initState() {
super.initState();
_isAccLogged();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xFF101727), Color(0xFF111418)],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
const Spacer(flex: 4),
const Text(
'MENU',
style: TextStyle(
fontSize: 36,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 100),
const Spacer(),
SizedBox(
width: 266,
height: 52,
child: ElevatedButton(
onPressed: () {
_routetoBalanceCheck();
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF232938),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(85),
),
padding: const EdgeInsets.symmetric(
horizontal: 15, vertical: 18),
),
child: const Text(
'CHECK BALANCE',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
),
),
// const SizedBox(height: 40),
const Spacer(),
SizedBox(
width: 266,
height: 52,
child: ElevatedButton(
onPressed: () {
_routetoWithdraw();
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF232938),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(85),
),
padding: const EdgeInsets.symmetric(
horizontal: 15, vertical: 18),
),
child: const Text(
'WITHDRAW',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
),
),
// const SizedBox(height: 40),
const Spacer(),
SizedBox(
width: 266,
height: 52,
child: ElevatedButton(
onPressed: () {
SystemNavigator.pop();
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF232938),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(85),
),
padding: const EdgeInsets.symmetric(
horizontal: 15, vertical: 18),
),
child: const Text(
'EXIT',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
),
),
const Spacer(
flex: 5,
),
]),
),
),
);
}
void _routetoBalanceCheck() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => BalanceCheck(widget.atmNo)),
);
}
void _routetoWithdraw() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Withdraw(widget.atmNo, 0)),
);
}
void _isAccLogged() async {
Future<bool> accLogged = setupJSON(widget.atmNo, widget.atmPIN);
if (await accLogged) {
Fluttertoast.showToast(msg: 'Logged in');
} else {
Fluttertoast.showToast(msg: 'New Account Created');
}
}
}
| 0
|
mirrored_repositories/ATM-App-in-Flutter/lib
|
mirrored_repositories/ATM-App-in-Flutter/lib/screens/atm_pin.dart
|
import 'package:atmproject/screens/menu.dart';
import 'package:flutter/material.dart';
import 'package:pinput/pinput.dart';
class AtmPin extends StatelessWidget {
final String atmNo;
const AtmPin(this.atmNo, {super.key});
@override
Widget build(BuildContext context) {
var atmPIN = TextEditingController();
return GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(FocusNode());
},
child: Scaffold(
resizeToAvoidBottomInset: false,
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xFF101727), Color(0xFF111418)],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
const Spacer(flex: 1),
const Text(
'ATM PIN',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 30,
fontWeight: FontWeight.w200,
height: 1.17,
letterSpacing: 0.33,
),
),
const SizedBox(height: 10),
const Text(
'Enter your four-digit pin',
textAlign: TextAlign.center,
style: TextStyle(
color: Color(0xFF999999),
fontSize: 18,
fontWeight: FontWeight.w400,
height: 1.25,
letterSpacing: -0.32,
),
),
const SizedBox(height: 50),
Container(
height: 52,
width: 180,
padding: const EdgeInsets.only(left: 25, right: 25),
decoration: BoxDecoration(
color: const Color(0xFF232938),
borderRadius: BorderRadius.circular(100),
),
child: Pinput(
controller: atmPIN,
length: 4,
showCursor: false,
obscureText: true,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
defaultPinTheme: const PinTheme(
width: 15,
height: 15,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Color(0xFF999999),
),
),
onCompleted: (atmPIN) {
_routetoMenu(context, atmNo, atmPIN);
},
),
),
const Spacer(flex: 3),
],
),
),
),
),
);
}
void _routetoMenu(BuildContext context, String atmNo, String atmPIN) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => Menu(atmNo, atmPIN)),
);
}
}
| 0
|
mirrored_repositories/ATM-App-in-Flutter/lib
|
mirrored_repositories/ATM-App-in-Flutter/lib/screens/atm_number.dart
|
import 'package:atmproject/screens/atm_pin.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
class AtmNumber extends StatelessWidget {
const AtmNumber({super.key});
@override
Widget build(BuildContext context) {
var atmNo = TextEditingController();
return GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(FocusNode());
},
child: Scaffold(
resizeToAvoidBottomInset: false,
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xFF101727), Color(0xFF111418)],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Spacer(flex: 5),
const Text(
'Welcome to',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
),
),
const Text(
'ATM',
style: TextStyle(
fontSize: 60,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 120),
SizedBox(
height: 70,
width: 280,
child: TextField(
controller: atmNo,
keyboardType: TextInputType.number,
maxLength: 8,
decoration: InputDecoration(
filled: true,
fillColor: const Color(0xFF232938),
labelText: 'ATM Card Number',
contentPadding:
const EdgeInsets.symmetric(horizontal: 25.0),
labelStyle: const TextStyle(
color: Color(0xFF999999),
fontWeight: FontWeight.w400,
fontSize: 14,
),
border: const OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(80),
),
),
suffixIcon: IconButton(
icon: const Icon(Icons.arrow_forward),
color: const Color(0xFF999999),
onPressed: () {
_routeAtmPin(context, atmNo.text);
}),
),
style: const TextStyle(
color: Colors.white,
)),
),
const SizedBox(height: 100),
const Text(
'Insert your Card number to begin',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w400,
),
),
const SizedBox(height: 20),
const Image(
image: AssetImage('assets/images/atm.png'),
),
// const SizedBox(height: 138),
const Spacer(flex: 7),
const Text(
'Developed by sawongam',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w600,
color: Color.fromRGBO(255, 255, 255, 0.6)),
),
const Spacer(),
],
),
),
)),
);
}
_routeAtmPin(BuildContext context, String atmNo) {
if (atmNo.isEmpty) {
Fluttertoast.showToast(msg: 'Please enter your ATM Card Number');
} else {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => AtmPin(atmNo),
),
);
}
}
}
| 0
|
mirrored_repositories/ATM-App-in-Flutter/lib
|
mirrored_repositories/ATM-App-in-Flutter/lib/screens/balance_check.dart
|
import 'dart:convert';
import 'dart:io';
import 'package:atmproject/configs/default.dart';
import 'package:atmproject/screens/withdraw/withdraw.dart';
import 'package:encrypt/encrypt.dart';
import 'package:flutter/material.dart';
class BalanceCheck extends StatefulWidget {
final String atmNo;
const BalanceCheck(this.atmNo, {super.key});
@override
State<BalanceCheck> createState() => _BalanceCheckState();
}
class _BalanceCheckState extends State<BalanceCheck> {
int chkBal = 0;
int savBal = 0;
int initialChkIndex = 0;
int initialSavIndex = 1;
@override
void initState() {
super.initState();
_readInitJSON();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xFF101727), Color(0xFF111418)],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
const Spacer(flex: 4),
const Text(
'ACCOUNT BALANCE',
style: TextStyle(
fontSize: 36,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 100),
const Spacer(),
Container(
width: 335,
height: 150,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: const Color(0xFF232938),
borderRadius: BorderRadius.circular(7),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'ACCOUNT TYPE',
style: TextStyle(
color: Color(0xFF999999),
fontSize: 10,
fontWeight: FontWeight.w500,
letterSpacing: -0.24,
),
),
const SizedBox(height: 5),
const Text(
'CHECKING',
style: TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w400,
height: 1.29,
letterSpacing: -0.15,
),
),
const Spacer(),
const Text(
'BALANCE',
style: TextStyle(
color: Color(0xFF999999),
fontSize: 10,
fontWeight: FontWeight.w500,
letterSpacing: -0.24,
),
),
const SizedBox(height: 5),
Text(
'Rs. $chkBal',
style: const TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w400,
height: 1.29,
letterSpacing: -0.15,
),
),
const Spacer(),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
InkWell(
onTap: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => Withdraw(
widget.atmNo, initialChkIndex)),
);
},
child: Row(
children: [
Image.asset('assets/images/Share.png'),
const SizedBox(width: 5),
const Text(
'WITHDRAW',
style: TextStyle(
color: Color(0xFF999999),
fontSize: 16,
fontWeight: FontWeight.w400,
height: 1.25,
letterSpacing: -0.32,
),
),
],
),
),
],
),
],
),
),
const Spacer(),
Container(
width: 335,
height: 150,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: const Color(0xFF232938),
borderRadius: BorderRadius.circular(7),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'ACCOUNT TYPE',
style: TextStyle(
color: Color(0xFF999999),
fontSize: 10,
fontWeight: FontWeight.w500,
letterSpacing: -0.24,
),
),
const SizedBox(height: 5),
const Text(
'SAVING',
style: TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w400,
height: 1.29,
letterSpacing: -0.15,
),
),
const Spacer(),
const Text(
'BALANCE',
style: TextStyle(
color: Color(0xFF999999),
fontSize: 10,
fontWeight: FontWeight.w500,
letterSpacing: -0.24,
),
),
const SizedBox(height: 5),
Text(
'Rs. $savBal',
style: const TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w400,
height: 1.29,
letterSpacing: -0.15,
),
),
const Spacer(),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
InkWell(
onTap: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => Withdraw(
widget.atmNo, initialSavIndex)),
);
},
child: Row(
children: [
Image.asset('assets/images/Share.png'),
const SizedBox(width: 5),
const Text(
'WITHDRAW',
style: TextStyle(
color: Color(0xFF999999),
fontSize: 16,
fontWeight: FontWeight.w400,
height: 1.25,
letterSpacing: -0.32,
),
),
],
),
),
],
),
],
),
),
const Spacer(flex: 5),
]),
),
),
);
}
void _readInitJSON() async {
File file = await defaultDir();
String jsonRaw = await file.readAsString();
final jsonEncrypted = Encrypted.fromBase64(jsonRaw);
final decrypted = encrypter.decrypt(jsonEncrypted, iv: iv);
var jsonParsed = json.decode(decrypted);
Map atmMap =
jsonParsed.firstWhere((element) => element['atmNo'] == widget.atmNo);
setState(() {
chkBal = int.parse(atmMap['chkBal']);
savBal = int.parse(atmMap['savBal']);
});
}
}
| 0
|
mirrored_repositories/ATM-App-in-Flutter/lib/screens
|
mirrored_repositories/ATM-App-in-Flutter/lib/screens/withdraw/withdraw.dart
|
import 'package:atmproject/screens/withdraw/tabs_withdraw/checking_container.dart';
import 'package:atmproject/screens/withdraw/tabs_withdraw/saving_container.dart';
import 'package:flutter/material.dart';
class Withdraw extends StatelessWidget {
final String atmNo;
final int initialTabIndex;
const Withdraw(this.atmNo, this.initialTabIndex, {super.key});
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
initialIndex: initialTabIndex,
child: Scaffold(
resizeToAvoidBottomInset: false,
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xFF101727), Color(0xFF111418)],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
const SizedBox(height: 10),
const Text(
'WITHDRAW',
style: TextStyle(
fontSize: 36,
fontWeight: FontWeight.w500,
),
),
Container(
height: 480,
width: 369,
decoration: BoxDecoration(
color: const Color(0xFF232938),
borderRadius: BorderRadius.circular(23),
),
padding: const EdgeInsets.only(
left: 10, right: 10, bottom: 10, top: 10),
child: Column(
// mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(height: 15),
TabBar(
indicator: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: const Color(0xFF00B8EE),
),
tabs: const [
Tab(text: 'CHECKING'),
Tab(text: 'SAVING'),
]),
const SizedBox(height: 50),
Flexible(
child: TabBarView(children: [
CheckingContainer(atmNo),
SavingContainer(atmNo),
]),
),
],
),
),
],
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/ATM-App-in-Flutter/lib/screens/withdraw
|
mirrored_repositories/ATM-App-in-Flutter/lib/screens/withdraw/manual_withdraw/checking_manual.dart
|
import 'package:atmproject/widgets/confirm_dialog.dart';
import 'package:flutter/material.dart';
class CheckingManual extends StatelessWidget {
final String atmNo;
const CheckingManual(this.atmNo, {super.key});
@override
Widget build(BuildContext context) {
var manualAmount = TextEditingController();
return Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
width: 274,
// height: 50,
padding: const EdgeInsets.all(16),
decoration: ShapeDecoration(
color: const Color(0xFF232938),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(80),
),
),
child: TextField(
controller: manualAmount,
maxLength: 5,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
counterText: "",
filled: true,
fillColor: Color(0xFF12161C),
labelText: 'Enter Withdraw Amount',
contentPadding: EdgeInsets.symmetric(horizontal: 25.0),
labelStyle: TextStyle(
color: Color(0xFF999999),
fontWeight: FontWeight.w400,
fontSize: 14,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(80),
),
),
),
style: const TextStyle(
color: Colors.white,
)),
),
SizedBox(
height: 40,
width: 130,
child: ElevatedButton(
onPressed: () {
confirmDialog(
context, atmNo, int.parse(manualAmount.text), 'chkBal');
manualAmount.clear();
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF00B8EE),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(85),
)),
child: const Text(
'Withdraw →',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w400,
height: 1.25,
letterSpacing: -0.32,
),
),
),
),
],
);
}
}
| 0
|
mirrored_repositories/ATM-App-in-Flutter/lib/screens/withdraw
|
mirrored_repositories/ATM-App-in-Flutter/lib/screens/withdraw/manual_withdraw/manual_cash_withdraw.dart
|
import 'package:atmproject/screens/withdraw/manual_withdraw/checking_manual.dart';
import 'package:atmproject/screens/withdraw/manual_withdraw/saving_manual.dart';
import 'package:flutter/material.dart';
class ManualCashWithdraw extends StatelessWidget {
final String atmNo;
final int initialTabIndex;
const ManualCashWithdraw(this.atmNo, this.initialTabIndex, {super.key});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(FocusNode());
},
child: DefaultTabController(
length: 2,
initialIndex: initialTabIndex,
child: Scaffold(
resizeToAvoidBottomInset: false,
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xFF101727), Color(0xFF111418)],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// const SizedBox(height: 10),
const Text(
'WITHDRAW',
style: TextStyle(
fontSize: 36,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 69),
Container(
height: 260,
width: 369,
decoration: BoxDecoration(
color: const Color(0xFF232938),
borderRadius: BorderRadius.circular(23),
),
padding: const EdgeInsets.only(
left: 10, right: 10, bottom: 10, top: 10),
child: Column(
children: [
const SizedBox(height: 15),
TabBar(
indicator: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: const Color(0xFF00B8EE),
),
tabs: const [
Tab(text: 'CHECKING'),
Tab(text: 'SAVING'),
]),
Flexible(
child: TabBarView(children: [
CheckingManual(atmNo),
SavingManual(atmNo),
]),
),
],
),
),
const SizedBox(height: 200),
],
),
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/ATM-App-in-Flutter/lib/screens/withdraw
|
mirrored_repositories/ATM-App-in-Flutter/lib/screens/withdraw/manual_withdraw/saving_manual.dart
|
import 'package:atmproject/widgets/confirm_dialog.dart';
import 'package:flutter/material.dart';
class SavingManual extends StatelessWidget {
final String atmNo;
const SavingManual(this.atmNo, {super.key});
@override
Widget build(BuildContext context) {
var manualAmount = TextEditingController();
return Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
width: 274,
// height: 50,
padding: const EdgeInsets.all(16),
decoration: ShapeDecoration(
color: const Color(0xFF232938),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(80),
),
),
child: TextField(
controller: manualAmount,
maxLength: 5,
keyboardType: TextInputType.number,
decoration: const InputDecoration(
counterText: "",
filled: true,
fillColor: Color(0xFF12161C),
labelText: 'Enter Withdraw Amount',
contentPadding: EdgeInsets.symmetric(horizontal: 25.0),
labelStyle: TextStyle(
color: Color(0xFF999999),
fontWeight: FontWeight.w400,
fontSize: 14,
),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(80),
),
),
),
style: const TextStyle(
color: Colors.white,
)),
),
SizedBox(
height: 40,
width: 130,
child: ElevatedButton(
onPressed: () {
confirmDialog(
context, atmNo, int.parse(manualAmount.text), 'savBal');
manualAmount.clear();
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF00B8EE),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(85),
)),
child: const Text(
'Withdraw →',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w400,
height: 1.25,
letterSpacing: -0.32,
),
),
),
),
],
);
}
}
| 0
|
mirrored_repositories/ATM-App-in-Flutter/lib/screens/withdraw
|
mirrored_repositories/ATM-App-in-Flutter/lib/screens/withdraw/tabs_withdraw/saving_container.dart
|
import 'package:atmproject/screens/withdraw/manual_withdraw/manual_cash_withdraw.dart';
import 'package:atmproject/widgets/confirm_dialog.dart';
import 'package:flutter/material.dart';
class SavingContainer extends StatelessWidget {
final String atmNo;
final String balType = 'savBal';
const SavingContainer(this.atmNo, {super.key});
@override
Widget build(BuildContext context) {
return Column(children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
SizedBox(
height: 55,
width: 110,
child: ElevatedButton(
onPressed: () {
confirmDialog(context, atmNo, 1000, balType);
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xf000000ff),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(85),
side: const BorderSide(width: 0.69, color: Color(0xFF8FA0A1)),
),
padding:
const EdgeInsets.symmetric(horizontal: 15, vertical: 18),
),
child: const Text(
'Rs. 1000',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
),
),
SizedBox(
height: 55,
width: 110,
child: ElevatedButton(
onPressed: () {
confirmDialog(context, atmNo, 5000, balType);
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xf000000ff),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(85),
side: const BorderSide(width: 0.69, color: Color(0xFF8FA0A1)),
),
padding:
const EdgeInsets.symmetric(horizontal: 15, vertical: 18),
),
child: const Text(
'Rs. 5000',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
),
),
],
),
const SizedBox(height: 30),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
SizedBox(
height: 55,
width: 110,
child: ElevatedButton(
onPressed: () {
confirmDialog(context, atmNo, 10000, balType);
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xf000000ff),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(85),
side: const BorderSide(width: 0.69, color: Color(0xFF8FA0A1)),
),
padding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 13),
),
child: const Text(
'Rs. 10,000',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
),
),
SizedBox(
height: 55,
width: 110,
child: ElevatedButton(
onPressed: () {
confirmDialog(context, atmNo, 15000, balType);
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xf000000ff),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(85),
side: const BorderSide(width: 0.69, color: Color(0xFF8FA0A1)),
),
padding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 13),
),
child: const Text(
'Rs. 15,000',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
),
),
],
),
const SizedBox(height: 30),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
SizedBox(
height: 55,
width: 110,
child: ElevatedButton(
onPressed: () {
confirmDialog(context, atmNo, 20000, balType);
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xf000000ff),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(85),
side: const BorderSide(width: 0.69, color: Color(0xFF8FA0A1)),
),
padding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 13),
),
child: const Text(
'Rs. 20,000',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
),
),
SizedBox(
height: 55,
width: 110,
child: ElevatedButton(
onPressed: () {
confirmDialog(context, atmNo, 25000, balType);
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xf000000ff),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(85),
side: const BorderSide(width: 0.69, color: Color(0xFF8FA0A1)),
),
padding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 13),
),
child: const Text(
'Rs. 25,000',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
),
),
],
),
const SizedBox(height: 30),
SizedBox(
height: 55,
width: 110,
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ManualCashWithdraw(atmNo, 1)),
);
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xf000000ff),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(85),
side: const BorderSide(width: 0.69, color: Color(0xFF8FA0A1)),
),
padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 18),
),
child: const Text(
'Other',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
),
),
]);
}
}
| 0
|
mirrored_repositories/ATM-App-in-Flutter/lib/screens/withdraw
|
mirrored_repositories/ATM-App-in-Flutter/lib/screens/withdraw/tabs_withdraw/checking_container.dart
|
import 'package:flutter/material.dart';
import 'package:atmproject/widgets/confirm_dialog.dart';
import 'package:atmproject/screens/withdraw/manual_withdraw/manual_cash_withdraw.dart';
class CheckingContainer extends StatelessWidget {
final String atmNo;
final String balType = 'chkBal';
const CheckingContainer(this.atmNo, {super.key});
@override
Widget build(BuildContext context) {
return Column(children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
SizedBox(
height: 55,
width: 110,
child: ElevatedButton(
onPressed: () {
confirmDialog(context, atmNo, 1000, balType);
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xf000000ff),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(85),
side: const BorderSide(width: 0.69, color: Color(0xFF8FA0A1)),
),
padding:
const EdgeInsets.symmetric(horizontal: 15, vertical: 18),
),
child: const Text(
'Rs. 1000',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
),
),
SizedBox(
height: 55,
width: 110,
child: ElevatedButton(
onPressed: () {
confirmDialog(context, atmNo, 5000, balType);
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xf000000ff),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(85),
side: const BorderSide(width: 0.69, color: Color(0xFF8FA0A1)),
),
padding:
const EdgeInsets.symmetric(horizontal: 15, vertical: 18),
),
child: const Text(
'Rs. 5000',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
),
),
],
),
const SizedBox(height: 30),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
SizedBox(
height: 55,
width: 110,
child: ElevatedButton(
onPressed: () {
confirmDialog(context, atmNo, 10000, balType);
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xf000000ff),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(85),
side: const BorderSide(width: 0.69, color: Color(0xFF8FA0A1)),
),
padding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 13),
),
child: const Text(
'Rs. 10,000',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
),
),
SizedBox(
height: 55,
width: 110,
child: ElevatedButton(
onPressed: () {
confirmDialog(context, atmNo, 15000, balType);
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xf000000ff),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(85),
side: const BorderSide(width: 0.69, color: Color(0xFF8FA0A1)),
),
padding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 13),
),
child: const Text(
'Rs. 15,000',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
),
),
],
),
const SizedBox(height: 30),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
SizedBox(
height: 55,
width: 110,
child: ElevatedButton(
onPressed: () {
confirmDialog(context, atmNo, 20000, balType);
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xf000000ff),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(85),
side: const BorderSide(width: 0.69, color: Color(0xFF8FA0A1)),
),
padding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 13),
),
child: const Text(
'Rs. 20,000',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
),
),
SizedBox(
height: 55,
width: 110,
child: ElevatedButton(
onPressed: () {
confirmDialog(context, atmNo, 25000, balType);
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xf000000ff),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(85),
side: const BorderSide(width: 0.69, color: Color(0xFF8FA0A1)),
),
padding:
const EdgeInsets.symmetric(horizontal: 10, vertical: 13),
),
child: const Text(
'Rs. 25,000',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
),
),
],
),
const SizedBox(height: 30),
SizedBox(
height: 55,
width: 110,
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ManualCashWithdraw(atmNo, 0)),
);
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xf000000ff),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(85),
side: const BorderSide(width: 0.69, color: Color(0xFF8FA0A1)),
),
padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 18),
),
child: const Text(
'Other',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
),
),
]);
}
}
| 0
|
mirrored_repositories/frideos_flutter
|
mirrored_repositories/frideos_flutter/lib/frideos.dart
|
export 'src/animations/animations.dart';
export 'src/app_state_provider.dart';
export 'src/core/core.dart';
export 'src/effects/blur.dart';
export 'src/effects/transitions.dart';
export 'src/effects/waves.dart';
export 'src/extended_asyncwidgets.dart';
export 'src/interfaces/app_state.dart';
export 'src/receiver_widget.dart';
export 'src/scenes_object/scene.dart';
export 'src/scenes_object/scenes_object.dart';
export 'src/scenes_widget.dart';
export 'src/scrolling_text.dart';
export 'src/staged_object/stage.dart';
export 'src/staged_object/staged_object.dart';
export 'src/staged_widget.dart';
| 0
|
mirrored_repositories/frideos_flutter/lib
|
mirrored_repositories/frideos_flutter/lib/src/extended_asyncwidgets.dart
|
import 'dart:async';
import 'package:flutter/material.dart';
import 'core/core.dart';
///
///
///
typedef ErrorCallback = Widget Function(Object);
typedef WaitingCallback = Widget Function();
///
/// ValueBuilder extends the [StreamBuilder] widget providing
/// some callbacks to handle the state of the stream and returning a
/// [Container] if `noDataChild` is not provided, in order to avoid
/// checking `snapshot.hasData`.
///
/// N.B. To use when there is no need to receive a *null value*.
///
/// It takes as a `streamed` parameter an object implementing the
/// [StreamedObject] interface and triggers the rebuild of the widget
/// whenever the stream emits a new event.
///
///
/// #### Usage:
///
/// ```dart
/// ValueBuilder<String>(
/// streamed: streamedValue,
/// builder: (BuildContext context, snasphot) => Text(snasphot.data),
/// initialData: // Data to provide for the initial snapshot
/// noDataChild: // Widget to show when the stream has no data
/// onNoData: () => // or Callback
/// errorChild: // Widget to show on error
/// onError: (error) => // or Callback
/// )
/// ```
///
/// If no [noDataChild] widget or [onNoData] callback is provided then
/// a [Container] is returned.
///
/// If no [errorChild] widget or no [onError] callback is provided then
/// a [Container] is returned.
///
///
/// N.B. The callbacks are executed only if their respective child is
/// not provided.
///
///
class ValueBuilder<T> extends StreamBuilder<T> {
ValueBuilder(
{@required StreamedObject<T> streamed,
@required this.builder,
Key key,
T initialData,
this.noDataChild,
this.onNoData,
this.errorChild,
this.onError})
: assert(streamed != null, 'The streamed argument is null.'),
assert(builder != null, 'The builder argument is null.'),
super(
key: key,
initialData: initialData,
stream: streamed.outStream,
builder: builder);
final AsyncWidgetBuilder<T> builder;
///
/// If the snapshot has no data then this widget is returned
final Widget noDataChild;
///
/// If no [noDataChild] is provided then the [onNoData] callback is called
final WaitingCallback onNoData;
///
/// This widget is returned if there is an error
final Widget errorChild;
///
/// If no [errorChild] is provided then the [onError] callback is called
final ErrorCallback onError;
@override
Widget build(BuildContext context, AsyncSnapshot<T> currentSummary) {
if (currentSummary.hasData) {
return builder(context, currentSummary);
}
if (currentSummary.hasError) {
if (errorChild != null) {
return errorChild;
} else {
return onError != null ? onError(currentSummary.error) : Container();
}
}
if (noDataChild != null) {
return noDataChild;
} else {
return onNoData != null ? onNoData() : Container();
}
}
}
///
/// StreamedWidget extends the [StreamBuilder] widget providing
/// some callbacks to handle the state of the stream and returning a
/// [Container] if `noDataChild` is not provided, in order to avoid
/// checking `snapshot.hasData`.
///
/// N.B. To use when there is no need to receive a *null value*.
///
/// It takes as a `stream` parameter a [Stream] and triggers the rebuild
/// of the widget whenever the stream emits a new event.
///
///
///#### Usage
///
/// ```dart
/// StreamedWidget<String>(
/// stream: stream,
/// builder: (context, snasphot) => Text(snasphot.data),
/// initialData: // Data to provide for the initial snapshot
/// noDataChild: // Widget to show when the stream has no data
/// onNoData: () => // or Callback
/// errorChild: // Widget to show on error
/// onError: (error) => // or Callback
/// )
/// ```
///
/// In case of an object implementing the StreamedObject interface
/// (eg. StreamedValue, StreamedList etc.):
///
/// ```dart
/// StreamedWidget<String>(
/// stream: streamedObject.outStream, // outStream getter
/// builder: (context, snasphot) => Text(snasphot.data),
/// initialData: // Data to provide for the initial snapshot
/// noDataChild: // Widget to show when the stream has no data
/// onNoData: () => // or Callback
/// errorChild: // Widget to show on error
/// onError: (error) => // or Callback
/// )
/// ```
///
/// If no [noDataChild] widget or [onNoData] callback is provided then
/// a [Container] is returned.
///
/// If no [errorChild] widget or no [onError] callback is provided then
/// a [Container] is returned.
///
/// N.B. The callbacks are executed only if their respective child is
/// not provided.
///
///
class StreamedWidget<T> extends StreamBuilder<T> {
const StreamedWidget(
{@required Stream<T> stream,
@required this.builder,
Key key,
this.initialData,
this.noDataChild,
this.onNoData,
this.errorChild,
this.onError})
: assert(stream != null, 'The stream argument is null.'),
assert(builder != null, 'The builder argument is null.'),
super(key: key, stream: stream, builder: builder);
final AsyncWidgetBuilder<T> builder;
final T initialData;
///
/// If the snapshot has no data then this widget is returned
final Widget noDataChild;
///
/// If no [noDataChild] is provided then the [onNoData] callback is called
final WaitingCallback onNoData;
///
/// This widget is returned if there is an error
final Widget errorChild;
///
/// If no [errorChild] is provided then the [onError] callback is called
final ErrorCallback onError;
@override
Widget build(BuildContext context, AsyncSnapshot<T> currentSummary) {
if (currentSummary.hasData) {
return builder(context, currentSummary);
}
if (currentSummary.hasError) {
if (errorChild != null) {
return errorChild;
} else {
return onError != null ? onError(currentSummary.error) : Container();
}
}
if (noDataChild != null) {
return noDataChild;
} else {
return onNoData != null ? onNoData() : Container();
}
}
}
///
/// FuturedWidget is a wrapper for the [FutureBuilder] widget. It provides
/// some callbacks to handle the state of the future and returning a
/// [Container] if `onWaitingChild` is not provided, in order to avoid
/// checking `snapshot.hasData`.
///
///
/// #### Usage
///
/// ```dart
/// FuturedWidget<String>(
/// future: future,
/// builder: (BuildContext context, snasphot) => Text(snasphot.data),
/// initialData: // Data to provide if the snapshot is null or still not completed
/// waitingChild: // Widget to show on waiting
/// onWaiting: () => // or Callback
/// errorChild: // Widget to show on error
/// onError: (error) => // or Callback
/// )
/// ```
///
/// If no [onWaitingChild] widget or [onWaiting] callback is provided then
/// a [Container] is returned.
///
/// If no [errorChild] widget or no [onError] callback is provided then
/// a [Container] is returned.
///
/// N.B. The callbacks are executed only if their respective child is
/// not provided.
///
///
class FuturedWidget<T> extends StatelessWidget {
const FuturedWidget(
{@required this.future,
@required this.builder,
Key key,
this.initialData,
this.onWaitingChild,
this.onWaiting,
this.errorChild,
this.onError})
: assert(future != null, 'The future argument is null.'),
assert(builder != null, 'The builder argument is null.'),
super(key: key);
final T initialData;
final Future<T> future;
final AsyncWidgetBuilder<T> builder;
///
/// If the snapshot has no data then this widget is returned
final Widget onWaitingChild;
///
/// If no [onWaitingChild] is provided then the [onWaiting] callback is called
final WaitingCallback onWaiting;
///
/// This widget is returned if there is an error
final Widget errorChild;
///
/// If no [errorChild] is provided then the [onError] callback is called
final ErrorCallback onError;
@override
Widget build(BuildContext context) {
return FutureBuilder<T>(
initialData: initialData,
future: future,
builder: (context, snapshot) {
if (snapshot.hasData) {
return builder(context, snapshot);
}
if (snapshot.hasError) {
if (errorChild != null) {
return errorChild;
} else {
return onError != null ? onError(snapshot.error) : Container();
}
}
if (onWaitingChild != null) {
return onWaitingChild;
} else {
return onWaiting != null ? onWaiting() : Container();
}
});
}
}
| 0
|
mirrored_repositories/frideos_flutter/lib
|
mirrored_repositories/frideos_flutter/lib/src/staged_widget.dart
|
import 'package:flutter/material.dart';
import 'package:frideos/frideos.dart';
///
///
/// This widget uses a [StagedObject] for the timing of the widgets
/// visualization.
///
/// It takes as a parameter a Map<int, Stage> and plays every [Stage].
///
/// By default to change the stage is used the relative time, so the time
/// parameter of the [Stage] indicates how much time the stage will lasts.
/// Instead, to specify the absolute time, set to true the [absoluteTiming]
/// flag, in this case the time parameter indicates the absolute time when
/// to show the widget.
///
/// The [onStart] is used to call a function when the StagesObject begins
/// to play the stages.
///
/// The [onEnd] callback is called at the end of the last stage when the timeing
/// is relative (the [absoluteTiming] flag is set to false).
///
///
class StagedWidget extends StatefulWidget {
const StagedWidget(
{@required this.stagesMap,
Key key,
this.absoluteTiming = false,
this.onStart,
this.onEnd})
: assert(stagesMap != null, 'The stagesMap argument is null.'),
super(key: key);
final Map<int, Stage> stagesMap;
final bool absoluteTiming;
final Function onStart;
final Function onEnd;
@override
_StagedWidgetState createState() {
return _StagedWidgetState();
}
}
class _StagedWidgetState extends State<StagedWidget> {
final StagedObject staged = StagedObject();
@override
void initState() {
super.initState();
if (widget.onStart != null) {
staged.setCallback(widget.onStart);
}
if (widget.onEnd != null) {
staged.setOnEndCallback(widget.onEnd);
}
staged
..setStagesMap(widget.stagesMap)
..startStages();
}
@override
void dispose() {
staged.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final stage = staged.getStage(0);
assert(stage != null);
return ValueBuilder(
streamed: staged, builder: (context, snapshot) => snapshot.data);
}
}
| 0
|
mirrored_repositories/frideos_flutter/lib
|
mirrored_repositories/frideos_flutter/lib/src/scenes_widget.dart
|
import 'package:flutter/material.dart';
import 'package:frideos/frideos.dart';
import 'package:frideos/src/scenes_object/scene.dart';
import 'package:frideos/src/scenes_object/scenes_object.dart';
///
///
/// This widget uses a [ScenesObject] for the timing of the widgets
/// visualization.
///
/// It takes as a parameter a List<Scene> and plays every [Scene].
///
/// By default to change the stage is used the relative time, so the time
/// parameter of the [Scene] indicates how much time the stage will lasts.
/// Instead, to specify the absolute time, set to true the [absoluteTiming]
/// flag, in this case the time parameter indicates the absolute time when
/// to show the scene.
///
/// The [onStart] is used to call a function when the ScenesObject begins
/// to play the stages.
///
/// The [onEnd] callback is called at the end of the last stage when the timeing
/// is relative (the [absoluteTiming] flag is set to false).
///
/// #### Usage
/// From the ScenesObject example:
///
/// ```dart
///ScenesCreate(
/// scenes: [
/// Scene(
/// widget: SingleScene(
/// color: Colors.white,
/// text: 'Scene 1',
/// ),
/// time: 3500,
/// onShow: () {
/// print('Showing scene 1');
/// }),
/// Scene(
/// widget: SingleScene(
/// color: Colors.blue,
/// text: 'Scene 2',
/// ),
/// time: 3500,
/// onShow: () {
/// print('Showing scene 2');
/// }),
/// Scene(
/// widget: SingleScene(
/// color: Colors.brown,
/// text: 'Scene 3',
/// ),
/// time: 3500,
/// onShow: () {
/// print('Showing scene 3');
/// }),
/// ],
/// onStart: () => print('Start playing scenes!'),
/// onEnd: () => print('End playing scenes!'),
///),
///
///
///// The singleScene widget:
///
/// class SingleScene extends StatelessWidget {
/// const SingleScene({Key key, this.text, this.color}) : super(key: key);
///
/// final String text;
/// final Color color;
///
/// @override
/// Widget build(BuildContext context) {
/// return Container(
/// alignment: Alignment.center,
/// color: color,
/// child: Text(text),
/// );
/// }
/// }
/// ```
class ScenesCreate extends StatefulWidget {
const ScenesCreate(
{@required this.scenes,
Key key,
this.absoluteTiming = false,
this.onStart,
this.onEnd})
: assert(scenes != null, 'The scenes argument is null.'),
super(key: key);
final List<Scene> scenes;
final bool absoluteTiming;
final Function onStart;
final Function onEnd;
@override
_ScenesCreateState createState() {
return _ScenesCreateState();
}
}
class _ScenesCreateState extends State<ScenesCreate> {
final ScenesObject scenesObject = ScenesObject();
@override
void initState() {
super.initState();
if (widget.onStart != null) {
scenesObject.setCallback(widget.onStart);
}
if (widget.onEnd != null) {
scenesObject.setOnEndCallback(widget.onEnd);
}
scenesObject
..setScenesList(widget.scenes)
..startScenes();
}
@override
void dispose() {
scenesObject.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final stage = scenesObject.getScene(0);
assert(stage != null);
return ValueBuilder(
streamed: scenesObject, builder: (context, snapshot) => snapshot.data);
}
}
| 0
|
mirrored_repositories/frideos_flutter/lib
|
mirrored_repositories/frideos_flutter/lib/src/scrolling_text.dart
|
import 'dart:async';
import 'package:flutter/material.dart';
import 'core/core.dart';
import 'extended_asyncwidgets.dart';
///
/// A simple widget that animates a input string making a scrolling text
/// over a given time.
///
class ScrollingText extends StatefulWidget {
const ScrollingText(
{@required this.text,
@required this.scrollingDuration,
Key key,
this.style})
: assert(text != null, 'The text argument is null.'),
assert(
scrollingDuration != null, 'The scrollDuration argument is null.'),
super(key: key);
final String text;
final int scrollingDuration;
final TextStyle style;
@override
_ScrollingTextState createState() {
return _ScrollingTextState();
}
}
class _ScrollingTextState extends State<ScrollingText> {
final StreamedValue<String> textStream = StreamedValue<String>();
Timer timer;
void showText(String str) {
if (timer != null) {
if (timer.isActive) {
} else {
startShowingText(str);
}
} else {
startShowingText(str);
}
}
void startShowingText(String str) {
timer = Utils.sendText(str, textStream, null, widget.scrollingDuration);
}
@override
void initState() {
super.initState();
showText(widget.text);
}
@override
void dispose() {
if (timer != null) {
timer.cancel();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(12.0),
child: StreamedWidget<String>(
initialData: '',
stream: textStream.outStream,
builder: (context, snapshot) {
return Text(snapshot.data, style: widget.style);
},
noDataChild: const Text('NO DATA'),
),
);
}
}
///
/// A simple widget that animates a input string making a scrolling text
/// over a given time.
///
| 0
|
mirrored_repositories/frideos_flutter/lib
|
mirrored_repositories/frideos_flutter/lib/src/receiver_widget.dart
|
import 'dart:async';
import 'package:flutter/material.dart';
import 'extended_asyncwidgets.dart';
///
/// Used with a [Stream] when the type is a widget to
/// directly stream a widget to the view. Under the hood
/// a [StreamedWidget] handles the stream and shows
/// the widget.
///
///
class ReceiverWidget extends StatelessWidget {
const ReceiverWidget({Key key, this.stream})
: assert(stream != null, 'The strean argument is null.'),
super(key: key);
final Stream<Widget> stream;
@override
Widget build(BuildContext context) {
return StreamedWidget<Widget>(
stream: stream, builder: (context, snapshot) => snapshot.data);
}
}
| 0
|
mirrored_repositories/frideos_flutter/lib
|
mirrored_repositories/frideos_flutter/lib/src/app_state_provider.dart
|
import 'package:flutter/material.dart';
import 'interfaces/app_state.dart';
/// Simple state provider that extends a StatefulWidget and use
/// an InheritedWidget to share the state with the widgets on the tree.
///
/// Used along with streams, it is possibile for the widgets the access
/// this data to modify it and propagates the changes to the entire widgets
/// tree.
///
class AppStateProvider<T extends AppStateModel> extends StatefulWidget {
const AppStateProvider(
{@required this.appState, @required this.child, this.initAppState = true})
: assert(appState != null, 'The appState argument is null.'),
assert(child != null, 'The child argument is null.');
final T appState;
final Widget child;
final bool initAppState;
@override
_AppStateProviderState createState() => _AppStateProviderState();
static T of<T extends AppStateModel>(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<_InheritedState>().state;
}
class _AppStateProviderState extends State<AppStateProvider> {
@override
void initState() {
super.initState();
if (widget.initAppState) {
widget.appState.init();
}
}
@override
void dispose() {
widget.appState.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) =>
_InheritedState(state: widget.appState, child: widget.child);
}
class _InheritedState extends InheritedWidget {
const _InheritedState({
@required this.state,
@required Widget child,
Key key,
}) : super(key: key, child: child);
final AppStateModel state;
@override
bool updateShouldNotify(_InheritedState old) => state != old.state;
}
| 0
|
mirrored_repositories/frideos_flutter/lib/src
|
mirrored_repositories/frideos_flutter/lib/src/scenes_object/scene.dart
|
import 'package:flutter/material.dart';
///
/// This class is used to handle the scenes:
///
class Scene {
Scene({this.widget, this.time, this.onShow});
Widget widget;
int time; // milliseconds
Function onShow;
}
///
/// Class used in the cross fading between two scenes
///
class SceneBridge {
SceneBridge(this.currentStage, this.old, this.next);
int currentStage;
Scene old;
Scene next;
}
| 0
|
mirrored_repositories/frideos_flutter/lib/src
|
mirrored_repositories/frideos_flutter/lib/src/scenes_object/scenes_object.dart
|
import 'dart:async';
import 'package:flutter/material.dart';
import '../core/core.dart';
import 'scene.dart';
///
/// Enum to handle the Status of the ScenesObject
///
enum SceneStatus { active, stop }
///
/// Interval in millisecond to check for the next scene
///
const int updateTimeScenes = 100;
/// A complex class to hadle the rendering of scenes over the time.
/// It takes a collection of "Scenes" and triggers the visualization of
/// the widgets at a given time (relative o absolute timing).
/// For example to make a demostration on how to use an application,
/// showing the widgets and pages along with explanations.
///
/// Every scene is handled by using the Scene class:
///
///```dart
/// class Scene {
/// Widget widget;
/// int time; // milliseconds
/// Function onShow = () {};
/// Scene({this.widget, this.time, this.onShow});
/// }
/// ```
///
/// ##### N.B. The onShow callback is used to trigger an action when the scene shows
///
/// #### Usage
/// From the ScenesObject example:
///
/// #### 1 - Declare a list of scenes
///
/// ```dart
/// final ScenesObject scenesObject = ScenesObject();
/// ```
///
/// #### 2 - Add some scenes
///
/// ```dart
/// scenes.addAll([
/// Scene(
/// time: 4000,
/// widget: SingleScene(text: 'Scene 1', color: Colors.blueGrey),
/// onShow: () => print('Showing scene 1'),
/// ),
/// Scene(
/// time: 4000,
/// widget: SingleScene(text: 'Scene 2', color: Colors.orange),
/// onShow: () => print('Showing scene 1'),
/// )
/// ]);
///
///
/// // The singleScene widget:
///
/// class SingleScene extends StatelessWidget {
/// const SingleScene({Key key, this.text, this.color}) : super(key: key);
///
/// final String text;
/// final Color color;
///
/// @override
/// Widget build(BuildContext context) {
/// return Container(
/// alignment: Alignment.center,
/// color: color,
/// child: Text(text),
/// );
/// }
/// }
/// ```
/// #### 3 - Setup the ScenesObject and play the scenes
///
/// ```dart
/// scenesObject
/// ..setScenesList(scenes)
/// ..setCallback(() => print('Called on start'))
/// ..setOnEndCallback(scenesObject.startScenes); // Replay the scenes at the end
///
/// // For e.g. on tap on a button:
/// scenesObject.startScenes();
/// ```
///
///
class ScenesObject implements StreamedObject {
// Default constructor
ScenesObject({this.absoluteTiming = false, this.callbackOnStart = true}) {
if (absoluteTiming) {
periodic = checkAbsolute;
} else {
periodic = checkRelative;
}
}
ScenesObject.withList(List<Scene> scenes,
{this.absoluteTiming = false, this.callbackOnStart = true}) {
if (absoluteTiming) {
periodic = checkAbsolute;
} else {
periodic = checkRelative;
}
_scenes = scenes;
// Extract the times
scenes.forEach((scene) => _stages.add(scene.time));
// Buffering the list
_scenesBuffer.addAll(_stages);
// Status of the object at the beginning
_status.value = SceneStatus.stop;
}
///
/// Scene status
///
final _status = StreamedValue<SceneStatus>(initialData: SceneStatus.stop);
/// Getters for the stream of status
Stream<SceneStatus> get statusStream => _status.outStream;
/// Status of the ScenedObject
StreamedValue<SceneStatus> get getStatus => _status;
///
/// Used for timing the scenes
///
final _timerObject = TimerObject();
///
/// Scenes, every value is a relative or an absolute time
///
final List<int> _stages = [];
/// The list is buffered to let the original one inalterated
///
final List<int> _scenesBuffer = [];
/// The scene to show
///
int sceneIndex = 0;
/// To check if the widget shown is the last
///
bool isLastScene = false;
/// Used in relative timing to calculate the time passed
/// between two scenes
///
int lastSceneTime = 0;
/// Time margin error between the current time and the time
/// set for the scene
///
int sceneTimeMargin = 100;
/// List of scenes
///
List<Scene> _scenes;
/// Every widget is sent to this stream
///
final _widgetStream = StreamedValue<Widget>();
/// WidgetStream getter
///
/// Implementation of the getter outStream for the [StreamedObject]
/// interface. Used as default by the `ValueBuilder`.
@override
Stream<Widget> get outStream => _widgetStream.outStream;
/// Getter
Widget get value => _widgetStream.value;
/// This callback it is not scene specific and it is called
/// everytime the scene changes. Setting the [callbackOnStart]
/// to false, the callback it is not called at the scene 0.
///
Function _callback = () {};
/// By default the callback it is called at the beginning
/// and on every scene change, set to false to disable the
/// call of the callback at the scene 0. Default is true.
bool callbackOnStart = true;
/// This callback is called at the end.
Function _onEnd = () {};
/// Type of timing, absolute or relative
///
bool absoluteTiming;
/// By this function is set the type of timing: absolute or relative
Function(Timer t) periodic;
void clearList() {
_scenes.clear();
}
/// To set the list of the scenes
void setScenesList(List<Scene> scenes) {
_scenes = scenes;
// Extract the times
if (_stages.isNotEmpty) {
_stages.clear();
}
scenes.forEach((scene) => _stages.add(scene.time));
}
/// To set the callback non widget specific (this is called
/// on every scene change and at the beginning if the flag [callbackOnStart]
/// it is not set to false, default is true).
void setCallback(Function callback) {
_callback = callback;
}
void setOnEndCallback(Function callback) {
_onEnd = callback;
}
int getListLength() => _scenes.length;
Scene getCurrentScene() => _scenes[sceneIndex];
int getSceneIndex() => sceneIndex;
Scene getNextScene() {
final nextScene = sceneIndex + 1;
if (nextScene < _scenes.length) {
return _scenes[nextScene];
} else {
return null;
}
}
Scene getScene(int index) {
assert(_scenes[index] != null);
return _scenes[index];
}
void startScenes() {
if (_scenes != null) {
if (!_timerObject.isTimerActive && _scenes.isNotEmpty) {
// Buffer the list
if (_scenesBuffer.isNotEmpty) {
_scenesBuffer.clear();
}
_scenesBuffer.addAll(_stages);
// Show the first element of the list of widgets
_widgetStream.value = _scenes[0].widget;
// Set the scene index to the first element
sceneIndex = 0;
final interval = Duration(milliseconds: updateTimeScenes);
// The implementation of the periodic function is set by setting
// the absoluteTiming flag to true (absolute) or false (relative).
_timerObject.startPeriodic(interval, periodic);
_status.value = SceneStatus.active;
// Call the onShow function
if (_scenes[sceneIndex].onShow != null) {
_scenes[sceneIndex].onShow();
}
// Calling the callback on start if the flag isn't set to false
if (callbackOnStart) {
_callback();
}
}
}
}
void resetScenes() {
// print('Reset scenes');
// Refresh the buffer with the original list
_scenesBuffer
..clear()
..addAll(_stages);
// Set the scene to the first element
sceneIndex = 0;
_widgetStream.value = _scenes[0].widget;
isLastScene = false;
}
void stopScenes() {
// print('Stop scenes');
_timerObject.stopTimer();
lastSceneTime = 0;
_status.value = SceneStatus.stop;
// Calling the onEnd callback if the timing is relative
if (!absoluteTiming) {
final time = _scenes[sceneIndex].time;
Timer(Duration(milliseconds: time), _onEnd);
}
}
// check for absolute time position
void checkAbsolute(Timer t) {
if (_scenesBuffer.isNotEmpty) {
// Updating the timer
_timerObject.updateTime(t);
final currentTime = _timerObject.time;
// Time in milliseconds of the current scene
final scene = _scenesBuffer.first;
// If the current time is between +/- 100ms of an item of the scenes
if (currentTime >= scene - sceneTimeMargin &&
currentTime <= scene + sceneTimeMargin) {
// Send to stream the new widget
_widgetStream.value = _scenes[sceneIndex].widget;
// To call the general callback and the onShow callback
// of the single windget
_callCallbacks();
// Remove the current item
_scenesBuffer.removeAt(0);
// Set the new index so the next time is shown the next scene
// on the list
sceneIndex++;
}
} else {
isLastScene = true;
stopScenes();
}
}
void checkRelative(Timer t) {
// Check if there are items in the scenes list
// and go on until
if (_scenesBuffer.length > 1) {
// Updating the timer
_timerObject.updateTime(t);
final currentTime = _timerObject.time;
// Time in milliseconds of the current scene
final scene = _scenesBuffer.first;
// Being relative time the cutoff is the time passed
// from the time of the last scene and the current one
//
final timePassed = currentTime - lastSceneTime;
// If the current time is between +/- 100ms of an item of the scenes
if (timePassed >= scene - sceneTimeMargin &&
timePassed <= scene + sceneTimeMargin) {
// Set the new index so the next time is shown the next widget
// on the list
sceneIndex++;
// Send to stream the new widget
_widgetStream.value = _scenes[sceneIndex].widget;
// To call the general callback and the onShow callback
// of the single windget
_callCallbacks();
// Remove the current item
_scenesBuffer.removeAt(0);
// The next time the current scene will be used to calculate
// the time passed.
lastSceneTime = currentTime;
}
} else {
isLastScene = true;
stopScenes();
}
}
void _callCallbacks() {
// Call the onShow function
if (_scenes[sceneIndex].onShow != null) {
_scenes[sceneIndex].onShow();
}
// Calling the callback
// If no callback is set then this is -> () {}
_callback();
}
void dispose() {
_timerObject.dispose();
_widgetStream.dispose();
_status.dispose();
}
}
| 0
|
mirrored_repositories/frideos_flutter/lib/src
|
mirrored_repositories/frideos_flutter/lib/src/staged_object/staged_object.dart
|
import 'dart:async';
import 'package:flutter/material.dart';
import '../core/core.dart';
import 'stage.dart';
///
/// Enum to handle the Status of the StagedObject
///
enum StageStatus { active, stop }
///
/// Interval in millisecond to check for the next stage
///
const int updateTimeStaged = 100;
/// A complex class to hadle the rendering of widgets over the time.
/// It takes a collection of "Stages" and triggers the visualization of
/// the widgets at a given time (relative o absolute timing).
/// For example to make a demostration on how to use an application,
/// showing the widgets and pages along with explanations.
///
///
/// Every stage is handled by using the Stage class:
///
/// class Stage {
/// Widget widget;
/// int time; // milliseconds
/// Function onShow = () {};
/// Stage({this.widget, this.time, this.onShow});
/// }
/// ```
///
/// ##### N.B. The onShow callback is used to trigger an action when the
/// stage shows
///
/// #### Usage
///
/// From the StagedObject example:
///
/// 1. #### Declare a map <int, Stage>
/// Here the map is in the view and is set in the BLoC class by the
/// setStagesMap.
///
/// ```dart
/// Map<int, Stage> get stagesMap => <int, Stage>{
/// 0: Stage(
/// widget: Container(
/// width: 200.0,
/// height: 200.0,
/// color: Colors.indigo[200],
/// alignment: Alignment.center,
/// key: Key('0'),
/// child: ScrollingText(
/// text:
/// 'This stage will last 8 seconds. By the onShow call back it is possibile to assign an action when the widget shows.',
/// scrollingDuration: 2000,
/// style: TextStyle(
/// color: Colors.blue,
/// fontSize: 18.0,
/// fontWeight: FontWeight.w500)),
/// ),
/// time: 8000,
/// onShow: () {}),
/// 1: Stage(
/// widget: Container(
/// width: 200.0,
/// height: 200.0,
/// color: Colors.indigo[200],
/// alignment: Alignment.center,
/// key: Key('00'),
/// child: ScrollingText(
/// text: 'The next widgets will cross fade.',
/// scrollingDuration: 2000,
/// ),
/// ),
/// time: 8000,
/// onShow: () {}),
///
/// }
/// ```
/// 2. #### In the BLoC
///
/// ```dart
/// final text = StreamedValue<String>();
/// final staged = StagedObject();
///
/// // The map can be set through the constructor of the StagedObject
/// // or by the setStagesMap method like in this case.
/// setMap(Map<int, Stage> stagesMap) {
/// staged.setStagesMap(stagesMap);
/// }
///
/// start() {
/// if (staged.getMapLength() > 0) {
/// staged.setCallback(sendNextStageText);
/// staged.startStages();
/// }
/// }
///
///
/// sendNextStageText() {
/// var nextStage = staged.getNextStage();
/// if (nextStage != null) {
/// text.value = "Next stage:";
/// widget.value = nextStage.widget;
/// stage.value = StageBridge(
/// staged.getStageIndex(), staged.getCurrentStage(), nextStage);
/// } else {
/// text.value = "This is the last stage";
/// widget.value = Container();
/// }
/// }
/// ```
///
/// 3. #### In the view:
///
/// ```dart
/// // Setting the map in the build method
/// StagedObjectBloc bloc = BlocProvider.of(context);
/// bloc.setMap(stagesMap);
///
///
/// // To show the current widget on the view using the ReceiverWidget.
/// // As an alternative it can be used the ValueBuilder/StreamBuilder.
/// ReceiverWidget(
/// stream: bloc.staged.widgetStream,
/// ),
/// ```
///
///
class StagedObject implements StreamedObject {
// Default constructor
StagedObject({this.absoluteTiming = false, this.callbackOnStart = true}) {
if (absoluteTiming) {
periodic = checkAbsolute;
} else {
periodic = checkRelative;
}
}
StagedObject.withMap(Map<int, Stage> stagesMap,
{this.absoluteTiming = false, this.callbackOnStart = true}) {
if (absoluteTiming) {
periodic = checkAbsolute;
} else {
periodic = checkRelative;
}
_stagesMap = stagesMap;
// Extract the times
stagesMap.forEach((k, v) => _stages.add(v.time));
// Buffering the list
_stagesBuffer.addAll(_stages);
// Status of the object at the beginning
_status.value = StageStatus.stop;
}
///
/// Stage status
///
final _status = StreamedValue<StageStatus>(initialData: StageStatus.stop);
/// Getters for the stream of status
Stream<StageStatus> get statusStream => _status.outStream;
/// Status of the StagedObject
StreamedValue<StageStatus> get getStatus => _status;
///
/// Used for timing the stages
///
final _timerObject = TimerObject();
///
/// Stages, every value is a relative or an absolute time
///
final List<int> _stages = [];
/// The list is buffered to let the original one inalterated
///
final List<int> _stagesBuffer = [];
/// The stage to show
///
int stageIndex = 0;
/// To check if the widget shown is the last
///
bool isLastStage = false;
/// Used in relative timing to calculate the time passed
/// between two stages
///
int lastStageTime = 0;
/// Time margin error between the current time and the time
/// set for the stage
///
int stageTimeMargin = 100;
/// Map of widgets
///
Map<int, Stage> _stagesMap;
/// Every widget is sent to this stream
///
final _widgetStream = StreamedValue<Widget>();
/// WidgetStream getter
///
/// Implementation of the getter outStream for the [StreamedObject]
/// interface. Used as default by the `ValueBuilder`.
@override
Stream<Widget> get outStream => _widgetStream.outStream;
/// Getter
Widget get value => _widgetStream.value;
/// This callback it is not stage specific and it is called
/// everytime the stage changes. Setting the [callbackOnStart]
/// to false, the callback it is not called at the stage 0.
///
Function _callback = () {};
/// By default the callback it is called at the beginning
/// and on every stage change, set to false to disable the
/// call of the callback at the stage 0. Default is true.
bool callbackOnStart = true;
/// This callback is called at the end.
Function _onEnd = () {};
/// Type of timing, absolute or relative
///
bool absoluteTiming;
/// By this function is set the type of timing: absolute or relative
Function(Timer t) periodic;
void clearMap() {
_stagesMap.clear();
}
/// To se the map of the stages
void setStagesMap(Map<int, Stage> stagesMap) {
_stagesMap = stagesMap;
// Extract the times
if (_stages.isNotEmpty) {
_stages.clear();
}
stagesMap.forEach((k, v) => _stages.add(v.time));
}
int getMapLength() {
return _stagesMap.length;
}
/// To set the callback non widget specific (this is called
/// on every stage change and at the beginning if the flag [callbackOnStart]
/// it is not set to false, default is true).
void setCallback(Function callback) {
_callback = callback;
}
void setOnEndCallback(Function callback) {
_onEnd = callback;
}
Stage getCurrentStage() {
return _stagesMap[stageIndex];
}
int getStageIndex() {
return stageIndex;
}
Stage getNextStage() {
final nextStage = stageIndex + 1;
if (_stagesMap.containsKey(nextStage)) {
return _stagesMap[nextStage];
} else {
return null;
}
}
Stage getStage(int index) {
assert(_stagesMap[index] != null);
return _stagesMap[index];
}
void startStages() {
if (_stagesMap != null) {
if (!_timerObject.isTimerActive && _stagesMap.isNotEmpty) {
// Buffer the list
if (_stagesBuffer.isNotEmpty) {
_stagesBuffer.clear();
}
_stagesBuffer.addAll(_stages);
// Show the first element of the list of widgets
_widgetStream.value = _stagesMap[0].widget;
// Set the stage index to the first element
stageIndex = 0;
final interval = Duration(milliseconds: updateTimeStaged);
// The implementation of the periodic function is set by setting
// the absoluteTiming flag to true (absolute) or false (relative).
_timerObject.startPeriodic(interval, periodic);
_status.value = StageStatus.active;
// Call the onShow function
if (_stagesMap[stageIndex].onShow != null) {
_stagesMap[stageIndex].onShow();
}
// Calling the callback on start if the flag isn't set to false
if (callbackOnStart) {
_callback();
}
}
}
}
void resetStages() {
// print('Reset stages');
// Refresh the buffer with the original list
_stagesBuffer
..clear()
..addAll(_stages);
// Set the stage to the first element
stageIndex = 0;
_widgetStream.value = _stagesMap[0].widget;
isLastStage = false;
}
void stopStages() {
// print('Stop stages');
_timerObject.stopTimer();
lastStageTime = 0;
_status.value = StageStatus.stop;
// Calling the onEnd callback if the timing is relative
if (!absoluteTiming) {
final time = _stagesMap[stageIndex].time;
Timer(Duration(milliseconds: time), _onEnd);
}
}
// check for absolute time position
void checkAbsolute(Timer t) {
if (_stagesBuffer.isNotEmpty) {
// Updating the timer
_timerObject.updateTime(t);
final currentTime = _timerObject.time;
// Time in milliseconds of the current stage
final stage = _stagesBuffer.first;
// If the current time is between +/- 100ms of an item of the stages
if (currentTime >= stage - stageTimeMargin &&
currentTime <= stage + stageTimeMargin) {
// Send to stream the new widget
_widgetStream.value = _stagesMap[stageIndex].widget;
// To call the general callback and the onShow callback
// of the single windget
_callCallbacks();
// Remove the current item
_stagesBuffer.removeAt(0);
// Set the new index so the next time is shown the next widget
// on the list
stageIndex++;
}
} else {
isLastStage = true;
stopStages();
}
}
void checkRelative(Timer t) {
// Check if there are items in the stages list
// and go on until
if (_stagesBuffer.length > 1) {
// Updating the timer
_timerObject.updateTime(t);
final currentTime = _timerObject.time;
// Time in milliseconds of the current stage
final stage = _stagesBuffer.first;
// Being relative time the cutoff is the time passed
// from the time of the last stage and the current one
//
final timePassed = currentTime - lastStageTime;
// If the current time is between +/- 100ms of an item of the stages
if (timePassed >= stage - stageTimeMargin &&
timePassed <= stage + stageTimeMargin) {
// Set the new index so the next time is shown the next widget
// on the list
stageIndex++;
// Send to stream the new widget
_widgetStream.value = _stagesMap[stageIndex].widget;
// To call the general callback and the onShow callback
// of the single windget
_callCallbacks();
// Remove the current item
_stagesBuffer.removeAt(0);
// The next time the current stage will be used to calculate
// the time passed.
lastStageTime = currentTime;
}
} else {
isLastStage = true;
stopStages();
}
}
void _callCallbacks() {
// Call the onShow function
if (_stagesMap[stageIndex].onShow != null) {
_stagesMap[stageIndex].onShow();
}
// Calling the callback
// If no callback is set then this is -> () {}
_callback();
}
void dispose() {
_timerObject.dispose();
_widgetStream.dispose();
_status.dispose();
}
}
| 0
|
mirrored_repositories/frideos_flutter/lib/src
|
mirrored_repositories/frideos_flutter/lib/src/staged_object/stage.dart
|
import 'package:flutter/material.dart';
///
/// This class is used to handle the stages:
///
class Stage {
Stage({this.widget, this.time, this.onShow});
Widget widget;
int time; // milliseconds
Function onShow;
}
///
/// Class used in the cross fading between two stages
///
class StageBridge {
StageBridge(this.currentStage, this.old, this.next);
int currentStage;
Stage old;
Stage next;
}
| 0
|
mirrored_repositories/frideos_flutter/lib/src
|
mirrored_repositories/frideos_flutter/lib/src/core/core.dart
|
export 'src/animated_object.dart';
export 'src/streamed_list.dart';
export 'src/streamed_map.dart';
export 'src/streamed_value.dart';
export 'src/tunnel_pattern.dart';
export 'src/utils.dart';
export 'src/interfaces/streamed_object.dart';
| 0
|
mirrored_repositories/frideos_flutter/lib/src/core
|
mirrored_repositories/frideos_flutter/lib/src/core/src/animated_object.dart
|
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'interfaces/streamed_object.dart';
import 'streamed_value.dart';
///
/// Enum to handle the status of the animation.
///
enum AnimatedStatus { active, stop, pause }
///
/// Enum to specify the behavior of the animation for
/// the `startAnimation` method.
///
enum AnimatedType { increment, decrement }
///
///
/// This class is used to update a value over a period of time.
/// Useful to handle animations using the BLoC pattern.
///
/// From the AnimatedObject example:
///
/// #### Usage
///
/// #### In the BLoC:
///
/// ```dart
/// //Initial value 0.5, updating interval 20 milliseconds
/// final scaleAnimation =
/// AnimatedObject<double>(initialValue: 0.5, interval: 20);
///
/// start() {
/// scaleAnimation.start(updateScale);
/// }
///
/// updateScale(Timer t) {
/// scaleAnimation.animation.value += 0.02;
///
/// if (scaleAnimation.animation.value > 5.0) {
/// scaleAnimation.reset();
/// }
/// }
///
/// stop() {
/// scaleAnimation.stop();
/// }
///
/// reset() {
/// scaleAnimation.reset();
/// }
///```
///
///- #### In the view:
///
///```dart
/// Container(
/// color: Colors.blueGrey[100],
/// child: Column(
/// children: <Widget>[
/// Container(height: 20.0,),
/// ValueBuilder<AnimatedStatus>(
/// streamed: bloc.scaleAnimation.status,
/// builder: (context, snapshot) {
/// return Row(
/// mainAxisAlignment: MainAxisAlignment.center,
/// children: <Widget>[
/// snapshot.data == AnimatedStatus.active
/// ? RaisedButton(
/// color: Colors.lightBlueAccent,
/// child: Text('Reset'),
/// onPressed: () {
/// bloc.reset();
/// })
/// : Container(),
/// snapshot.data == AnimatedStatus.stop
/// ? RaisedButton(
/// color: Colors.lightBlueAccent,
/// child: Text('Start'),
/// onPressed: () {
/// bloc.start();
/// })
/// : Container(),
/// snapshot.data == AnimatedStatus.active
/// ? RaisedButton(
/// color: Colors.lightBlueAccent,
/// child: Text('Stop'),
/// onPressed: () {
/// bloc.stop();
/// })
/// : Container(),
/// ],
/// );
/// },
/// ),
/// Expanded(
/// child: ValueBuilder<double>(
/// streamed: bloc.scaleAnimation,
/// builder: (context, snapshot) {
/// return Transform.scale(
/// scale: snapshot.data, child: FlutterLogo());
/// }),
/// )
/// ],
/// ),
/// ),
///```
///
///
class AnimatedObject<T> implements StreamedObject<T> {
AnimatedObject({@required this.initialValue, @required this.interval})
: assert(initialValue != null, 'The initialValue argument is null.'),
assert(interval != null, 'The interval argument is null.') {
status.value = AnimatedStatus.stop;
}
/// It is the [StreamedValue] object that holds the animation value
final StreamedValue<T> animation = StreamedValue<T>();
/// Getter for stream of the [StreamedValue] that holds the animation
/// value.
@override
Stream<T> get outStream => animation.outStream;
/// Deprecated. use [outStream] instead, this is used by [ValueBuilder].
///
/// Getter for stream of the [StreamedValue] that holds the animation
/// value.
@Deprecated('Used the outStream getter instead.')
Stream<T> get animationStream => animation.outStream;
/// Getter for the AnimatedObject value
@override
T get value => animation.value;
/// Setter for the AnimatedObject value
set value(T value) => animation.value = value;
/// The initial value of the animation
T initialValue;
/// Timer to handle the timing
final TimerObject timer = TimerObject();
/// Interval in milliseconds
int interval;
///
/// AnimatedObject status
///
final StreamedValue<AnimatedStatus> status = StreamedValue<AnimatedStatus>();
/// Getter for the stream of the status of the animation
Stream<AnimatedStatus> get statusStream => status.outStream;
/// Status getter
AnimatedStatus get getStatus => status.value;
/// Method to check if the animation is playing or not.
bool isAnimating() {
if (getStatus == AnimatedStatus.active) {
return true;
} else {
return false;
}
}
/// In the callback increase the animation.value!
void start(Function(Timer t) callback) {
if (!timer.isTimerActive) {
animation.value = initialValue;
timer.startPeriodic(Duration(milliseconds: interval), callback);
status.value = AnimatedStatus.active;
}
}
///
/// Method to start animating the value.
///
/// - `type`: with this parameter specify if the the value
/// has to be incremented or decremented
///
///
/// - `velocity`: entity of the increment/decrement
///
///
/// - `minValue` and `maxValue`: if an [AnimatedType] of value `increment`
/// is set, then a `maxValue` parameter must be given. If `decrement`, a
/// `minValue` must be set. Once reached a min or a max value, the
/// animation stops.
///
void startAnimation(
{@required AnimatedType type,
@required dynamic velocity,
dynamic minValue,
dynamic maxValue}) {
assert(type != null && velocity != null,
'type and velocity parameters must be not null.');
dynamic valueTmp = initialValue;
switch (type) {
case AnimatedType.increment:
assert(maxValue != null, 'The parameter maxValue must be not null.');
start((t) {
if (valueTmp < maxValue) {
valueTmp += velocity;
value = valueTmp;
}
if (valueTmp >= maxValue) {
value = maxValue;
stop();
}
});
break;
case AnimatedType.decrement:
assert(minValue != null, 'The parameter maxValue must be not null.');
start((t) {
if (valueTmp > minValue) {
valueTmp -= velocity;
value = valueTmp;
}
if (valueTmp <= minValue) {
value = minValue;
stop();
}
});
break;
default:
break;
}
}
/// Method to stop the animation-
void stop() {
timer.stopTimer();
status.value = AnimatedStatus.stop;
}
/// Method to reset the animation. It doesn't stop the animation, it just
/// sets the animation.value to the [initialValue].
void reset() {
animation.value = initialValue;
}
/// Method to pause the animation
void pause() {
status.value = AnimatedStatus.pause;
}
void dispose() {
animation.dispose();
timer.dispose();
}
}
| 0
|
mirrored_repositories/frideos_flutter/lib/src/core
|
mirrored_repositories/frideos_flutter/lib/src/core/src/streamed_value.dart
|
import 'dart:async';
import 'package:rxdart/rxdart.dart';
import 'streamed_list.dart';
import 'interfaces/streamed_object.dart';
/// It's the simplest class that implements the [StreamedObject] interface.
///
/// Every time a new value is set, this is compared to the oldest one and if
/// it is different, it is sent to stream.
///
/// Used in tandem with `ValueBuilder` it automatically triggers the rebuild
/// of the widgets returned by its builder.
///
///
/// So for example, instead of:
///
///
/// ```dart
/// counter += 1;
/// stream.sink.add(counter);
/// ```
///
///
/// It becomes just:
///
///
/// ```dart
/// counter.value += 1;
/// ```
///
/// It can be used even with `StreamedWidget` and `StreamBuilder` by using its
/// stream getter `outStream`.
///
/// N.B. when the type is not a basic type (e.g int, double, String etc.) and
/// the value of a property of the object is changed, it is necessary to call
/// the [refresh] method to update the stream.
///
///
/// #### Usage
///
/// ```dart
/// // In the BLoC
/// final counter = StreamedValue<int>();
///
/// incrementCounter() {
/// counter.value += 2.0;
/// }
///
///
/// // View
/// ValueBuilder<int>(
/// streamed: bloc.count, // no need of the outStream getter with ValueBuilder
/// builder: (context, snapshot) => Text('Value: ${snapshot.data}'),
/// noDataChild: Text('NO DATA'),
/// ),
/// RaisedButton(
/// color: buttonColor,
/// child: Text('+'),
/// onPressed: () {
/// bloc.incrementCounter();
/// },
/// ),
///
/// // As an alternative:
/// //
/// // StreamedWidget<int>(
/// // stream: bloc.count.outStream,
/// // builder: (context, snapshot) => Text('Value: ${snapshot.data}'),
/// // noDataChild: Text('NO DATA'),
/// //,
///
/// ```
///
///
/// On update the [timesUpdated] increases showing how many times the
/// value has been updated.
///
///
/// N.B. For collections use [StreamedList] and [StreamedMap] instead.
///
///
class StreamedValue<T> implements StreamedObject<T> {
StreamedValue({this.initialData, this.onError}) {
stream = BehaviorSubject<T>()
..stream.listen((e) {
_lastValue = e;
if (_onChange != null) {
_onChange(e);
}
}, onError: onError);
if (initialData != null) {
_lastValue = initialData;
stream.sink.add(_lastValue);
}
}
/// Stream of type [BehaviorSubject] in order to emit
/// the last event to every new listener.
BehaviorSubject<T> stream;
/// Callback to handle the errors
final Function onError;
/// Stream getter
@override
Stream<T> get outStream => stream;
/// Sink for the stream
Function get inStream => stream.sink.add;
/// Last value emitted by the stream
T _lastValue;
/// The initial event of the stream
T initialData;
/// timesUpdate shows how many times the stream got updated
int timesUpdated = 0;
/// Debug mode (Default: false)
bool _debugMode = false;
/// This function will be called every time the stream updates.
Function(T data) _onChange;
/// Getter for the last value emitted by the stream
@override
T get value => _lastValue;
/// To send to stream a new event
set value(T value) {
_lastValue = value;
stream.sink.add(value);
if (_debugMode) {
timesUpdated++;
}
}
/// To set a function that will be called every time the stream updates.
void onChange(Function(T data) onDataChanged) => _onChange = onDataChanged;
/// Method to refresh the stream (e.g to use when the type it is not
/// a basic type, and a property of an object has changed).
void refresh() {
stream.sink.add(value);
if (_debugMode) {
timesUpdated++;
}
}
/// To enable the debug mode
void debugMode() {
_debugMode = true;
}
void dispose() {
if (_debugMode) {
print('---------- Closing Stream ------ type: $T');
print('Value: $value');
print('Updated times: $timesUpdated');
}
stream.close();
}
}
///
///
///
/// The MemoryObject has a property to preserve the previous value.
///
/// The setter checks for the new value, if it is different from the one
/// already stored, this one is given [oldValue] before storing and streaming
/// the new one.
///
///
///
class MemoryValue<T> extends StreamedValue<T> {
MemoryValue({T initialData, Function onError})
: super(initialData: initialData, onError: onError);
T _oldValue;
T get oldValue => _oldValue;
@override
set value(T value) {
if (_lastValue != value) {
_oldValue = _lastValue;
_lastValue = value;
stream.add(value);
if (_debugMode) {
timesUpdated++;
}
}
}
}
///
///
///
///
///
/// HistoryObject extends the [MemoryValue] class, adding a [StreamedList].
///
/// When the current value needs to be stored, the [saveValue] function
/// is called to send it to the [_historyStream].
///
class HistoryObject<T> extends MemoryValue<T> {
HistoryObject({T initialData, Function onError})
: super(initialData: initialData, onError: onError);
final _historyStream = StreamedList<T>(initialData: []);
@override
set value(T value) {
if (_lastValue != value) {
_oldValue = _lastValue;
inStream(value);
if (_debugMode) {
timesUpdated++;
}
}
}
///
/// Getter for the list
///
List<T> get history => _historyStream.value;
///
/// Getter for the stream
///
StreamedValue<List<T>> get historyStream => _historyStream.stream;
///
/// Function to store the current value to a collection and
/// sending it to stream
///
void saveValue() {
_historyStream.addElement(value);
}
/// To enable the debug mode
@override
void debugMode() {
_debugMode = true;
_historyStream.debugMode();
}
@override
void dispose() {
super.dispose();
_historyStream.dispose();
}
}
///
///
/// Timer refresh time
const int updateTimerMilliseconds = 17;
///
///
/// An object that embeds a timer and a stopwatch.
///
///
/// #### Usage
///
/// ```dart
/// final timerObject = TimerObject();
///
/// startTimer() {
/// timerObject.startTimer();
/// }
///
/// stopTimer() {
/// timerObject.stopTimer();
/// }
///
/// getLapTime() {
/// timerObject.getLapTime();
/// }
///
/// incrementCounter(Timer t) {
/// counter.value += 2.0;
/// }
///
/// startPeriodic() {
/// var interval = Duration(milliseconds: 1000);
/// timerObject.startPeriodic(interval, incrementCounter);
/// }
///
///```
///
class TimerObject extends StreamedValue<int> {
Timer _timer;
Duration _interval = Duration(milliseconds: updateTimerMilliseconds);
bool isTimerActive = false;
int _time = 0; // milliseconds
/// STOPWATCH
final _stopwatch = Stopwatch();
final _stopwatchStreamed = StreamedValue<int>();
bool isStopwatchActive = false;
@override
set value(int value) {
if (_lastValue != value) {
inStream(value);
if (_debugMode) {
timesUpdated++;
}
}
}
/// GETTERS
///
int get time => _time;
/// Getter for the stream of the stopwatch
Stream<int> get stopwatchStream => _stopwatchStreamed.outStream;
/// Getter for the stopwatch object
StreamedValue<int> get stopwatch => _stopwatchStreamed;
/// Start timer and stopwatch only if they aren't active
///
void startTimer() {
if (!isTimerActive) {
_timer = Timer.periodic(_interval, updateTime);
isTimerActive = true;
}
if (!isStopwatchActive) {
_stopwatch.start();
isStopwatchActive = true;
}
}
/// Update the time and send it to stream
///
void updateTime(Timer t) {
_time = _interval.inMilliseconds * t.tick;
inStream(_time);
}
/// Method to start a periodic function and set the isTimerActive to true
///
void startPeriodic(Duration interval, Function(Timer) callback) {
if (!isTimerActive) {
_timer = Timer.periodic(interval, callback);
_interval = interval;
isTimerActive = true;
}
}
/// Method to get the lap time
void getLapTime() {
if (isStopwatchActive) {
final milliseconds = _stopwatch.elapsedMilliseconds;
_stopwatchStreamed.value = milliseconds;
_stopwatch
..reset()
..start();
}
}
/// Stop timer and stopwatch, and set to false the booleans
void stopTimer() {
if (isTimerActive) {
_timer.cancel();
_time = 0;
inStream(null);
isTimerActive = false;
}
if (isStopwatchActive) {
_stopwatch
..reset()
..stop();
isStopwatchActive = false;
}
}
/// Method to reset the timer
void resetTimer() {
_time = 0;
inStream(_time);
}
/// Method to cancel the current timer
void pauseTimer() {
_timer.cancel();
}
@override
void dispose() {
super.dispose();
if (_timer != null) {
_timer.cancel();
}
_stopwatchStreamed.dispose();
_stopwatch.stop();
}
}
///
///
/// A particular class the implement the [StreamedObject] interface, to use when
/// there is the need of a StreamTransformer (e.g. stream transformation,
/// validation of input fields, etc.).
///
///
/// #### Usage
///
/// From the StreamedMap example:
///
/// ```dart
/// // In the BLoC class
/// final streamedKey = StreamedTransformed<String, int>();
///
///
/// // In the constructor of the BLoC class
/// streamedKey.setTransformer(validateKey);
///
///
/// // Validation (e.g. in the BLoC or in a mixin class)
/// final validateKey =
/// StreamTransformer<String, int>.fromHandlers(handleData: (key, sink) {
/// var k = int.tryParse(key);
/// if (k != null) {
/// sink.add(k);
/// } else {
/// sink.addError('The key must be an integer.');
/// }
/// });
///
///
/// // In the view:
/// StreamBuilder<int>(
/// stream: bloc.streamedKey.outTransformed,
/// builder: (context, snapshot) {
/// return Column(
/// children: <Widget>[
/// Padding(
/// padding: const EdgeInsets.symmetric(
/// vertical: 12.0,
/// horizontal: 20.0,
/// ),
/// child: TextField(
/// style: TextStyle(
/// fontSize: 18.0,
/// color: Colors.black,
/// ),
/// decoration: InputDecoration(
/// labelText: 'Key:',
/// hintText: 'Insert an integer...',
/// errorText: snapshot.error,
/// ),
/// // To avoid the user could insert text use the TextInputType.number
/// // Here is commented to show the error msg.
/// //keyboardType: TextInputType.number,
/// onChanged: bloc.streamedKey.inStream,
/// ),
/// ),
/// ],
/// );
/// }),
/// ```
///
///
///
class StreamedTransformed<T, S> implements StreamedObject<T> {
StreamedTransformed({this.initialData, this.onError}) {
stream = BehaviorSubject<T>()
..listen((e) {
_lastValue = e;
if (_onChange != null) {
_onChange(e);
}
}, onError: onError);
if (initialData != null) {
_lastValue = initialData;
stream.sink.add(_lastValue);
}
}
/// Last value emitted by the stream
T _lastValue;
/// The initial event of the stream
T initialData;
/// Value of the last event transformed
S transformed;
/// timesUpdate shows how many times the stream got updated
int timesUpdated = 0;
/// Debug mode (Default: false)
bool _debugMode = false;
BehaviorSubject<T> stream;
/// Callback to handle the errors
final Function onError;
/// Sink for the stream
Function get inStream => stream.sink.add;
/// Stream getter
@override
Stream<T> get outStream => stream.stream;
/// Streamtransformer
StreamTransformer _transformer;
/// Getter for the stream transformed
Stream<S> get outTransformed => stream.stream.transform(_transformer);
/// Value getter
@override
T get value => _lastValue;
/// Value setter
set value(T value) => inStream(value);
/// This function will be called every time the stream updates.
Function(T data) _onChange;
/// This function will be called every time the stream updates.
void onChange(Function(T data) onDataChanged) {
_onChange = onDataChanged;
}
/// To set a function that will be called every time the stream updates.
void setTransformer(StreamTransformer<T, S> transformer) {
assert(transformer != null, 'Invalid transformer.');
_transformer = transformer;
}
/// To enable the debug mode
void debugMode() {
_debugMode = true;
}
/// Method to refresh the stream (e.g to use when the type it is not
/// a basic type, and a property of an object has changed).
void refresh() {
inStream(value);
if (_debugMode) {
timesUpdated++;
}
}
/// Dispose the stream.
void dispose() {
if (_debugMode) {
print('---------- Closing Stream ------ type: $T');
print('Value: $value');
print('Updated times: $timesUpdated');
}
stream.close();
}
}
| 0
|
mirrored_repositories/frideos_flutter/lib/src/core
|
mirrored_repositories/frideos_flutter/lib/src/core/src/streamed_list.dart
|
import 'dart:async';
import '../core.dart';
///
///
/// Used when T is a list, it works like [StreamedValue].
///
/// To modify the list (e.g. adding items) and update the stream automatically
/// use these methods:
///
/// - [addAll]
/// - [addElement]
/// - [clear]
/// - [removeAt]
/// - [removeElement]
/// - [replace]
/// - [replaceAt]
///
/// For other direct actions on the list, to update the stream call
/// the [refresh] method instead.
///
/// #### Usage
///
/// e.g. adding an item:
///
/// ```dart
/// streamedList.addElement(item);
/// ```
///
/// it is the same as:
///
/// ```dart
/// streamedList.value.add(item);
/// streamedList.refresh();
/// ```
///
/// From the StreamedList example:
///
/// ```dart
/// final streamedList = StreamedList<String>();
///
///
/// // Add to the streamed list the string from the textfield
/// addText() {
/// streamedList.addElement(streamedText.value);
///
/// // Or, as an alternative:
/// // streamedList.value.add(streamedText.value);
/// // streamedList.refresh(); // To refresh the stream with the new value
/// }
/// ```
///
///
class StreamedList<T> implements StreamedObject<List<T>> {
StreamedList({List<T> initialData, this.onError}) {
stream = StreamedValue<List<T>>()
..stream.listen((data) {
if (_onChange != null) {
_onChange(data);
}
}, onError: onError);
if (initialData != null) {
stream.value = initialData;
}
}
StreamedValue<List<T>> stream;
/// Callback to handle the errors
final Function onError;
/// Sink for the stream
Function(List<T>) get inStream => stream.inStream;
/// Stream getter
@override
Stream<List<T>> get outStream => stream.outStream;
/// The initial event of the stream
List<T> initialData;
/// Last value emitted by the stream
List<T> lastValue;
/// timesUpdated shows how many times the stream got updated
int timesUpdated = 0;
@override
List<T> get value => stream.value;
int get length => stream.value.length;
/// This function will be called every time the stream updates.
void Function(List<T> data) _onChange;
/// Set the new value and update the stream
set value(List<T> list) {
stream.value = list;
if (_debugMode) {
timesUpdated++;
}
}
/// Debug mode (Default: false)
bool _debugMode = false;
/// To enable the debug mode
void debugMode() {
_debugMode = true;
}
/// To set a function that will be called every time the stream updates.
void onChange(Function(List<T>) onDataChanged) {
_onChange = onDataChanged;
}
/// Used to add an item to the list and update the stream.
void addElement(T element) {
stream.value.add(element);
refresh();
}
/// Used to add a List of item to the list and update the stream.
///
void addAll(Iterable<T> elements) {
stream.value.addAll(elements);
refresh();
}
/// Used to remove an item from the list and update the stream.
bool removeElement(T element) {
final result = value.remove(element);
refresh();
return result;
}
/// Used to remove an item from the list and update the stream.
T removeAt(int index) {
final removed = value.removeAt(index);
refresh();
return removed;
}
/// To replace an element at a given index
void replaceAt(int index, T element) {
stream.value[index] = element;
refresh();
}
/// To replace an element
void replace(T oldElement, T newElement) {
final index = stream.value.indexOf(oldElement);
replaceAt(index, newElement);
}
/// Used to clear the list and update the stream.
void clear() {
value.clear();
refresh();
}
/// To refresh the stream when the list is modified without using the
/// methods of this class.
void refresh() {
inStream(value);
if (_debugMode) {
timesUpdated++;
}
}
/// Dispose the stream.
void dispose() {
if (_debugMode) {
print('---------- Closing Stream ------ type: List<$T>');
print('Value: $value');
print('Updated times: $timesUpdated');
}
stream.dispose();
}
}
| 0
|
mirrored_repositories/frideos_flutter/lib/src/core
|
mirrored_repositories/frideos_flutter/lib/src/core/src/utils.dart
|
import 'dart:async';
import 'streamed_value.dart';
class Utils {
static String lorem =
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi feugiat quis massa at tincidunt. Proin lacus sapien, ullamcorper sed diam a, varius ornare ligula. Maecenas vitae velit ac orci lacinia convallis in vel nisl. Mauris lacinia, nisi ut porttitor finibus, metus est mattis metus, in laoreet metus lacus nec risus. Nunc porttitor lorem ac interdum imperdiet. Mauris finibus ante ex, ac pellentesque ante lacinia quis. In in maximus lacus. Duis fringilla nulla sem, eget elementum tellus tincidunt id. Nunc at ante id turpis consequat feugiat. Aliquam consequat, ipsum sit amet ullamcorper posuere, leo lectus tincidunt sapien, in feugiat neque nisi feugiat elit. Nulla porta eget libero vel accumsan. Integer cursus ipsum id ultrices faucibus. Nam vel ex tempor, cursus dui vel, auctor augue. Vestibulum viverra lectus at quam bibendum sagittis. Phasellus gravida suscipit nisi vulputate tempor. Proin vitae ultricies nulla.';
static String loremLight =
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi feugiat quis massa at tincidunt. Proin lacus sapien, ullamcorper sed diam a, varius ornare ligula. Maecenas vitae velit ac orci lacinia convallis in vel nisl. Mauris lacinia, nisi ut porttitor finibus, metus est mattis metus, in laoreet metus lacus nec risus.';
static Timer sendText(String text, StreamedValue stream, int milliseconds,
[int duration]) {
int index = 0;
Timer timer;
final int refresh =
duration != null ? (duration ~/ text.length).toInt() : milliseconds;
timer = Timer.periodic(Duration(milliseconds: refresh), (Timer t) {
if (index <= text.length - 1) {
final toShow = text.substring(0, index + 1);
stream.value = toShow;
index++;
} else {
timer.cancel();
}
});
return timer;
}
static Timer sendTextTo(
Timer timer, String text, int milliseconds, Function(String) callback) {
int index = 0;
Timer timer;
timer = Timer.periodic(Duration(milliseconds: milliseconds), (Timer t) {
if (index <= text.length - 1) {
final toShow = text.substring(0, index + 1);
callback(toShow);
index++;
} else {
timer.cancel();
}
});
return timer;
}
static Timer sendParagraph(
String text, StreamedValue stream, int milliseconds,
[int duration]) {
int index = 0;
Timer timer;
final int refresh =
duration != null ? (duration ~/ text.length).toInt() : milliseconds;
final words = text.split(' ');
timer = Timer.periodic(Duration(milliseconds: refresh), (Timer t) {
if (index <= words.length - 1) {
final toShow = words.take(index + 1);
stream.value = toShow;
index++;
} else {
timer.cancel();
}
});
return timer;
}
static double convertRange(
double _min, double _max, double min, double max, double value) {
final deltaValue = value - _min;
final newRange = max - min;
final oldRange = _max - _min;
return ((deltaValue * newRange) / oldRange) + min;
}
}
| 0
|
mirrored_repositories/frideos_flutter/lib/src/core
|
mirrored_repositories/frideos_flutter/lib/src/core/src/tunnel_pattern.dart
|
import 'streamed_list.dart';
import 'streamed_map.dart';
import 'streamed_value.dart';
/// Used to make a one-way tunnel beetween two blocs (from blocA to
/// a StremedValue on blocB).
///
/// #### Usage:
///
/// 1 - Define a streamed object (e.g. [StreamedValue]) in the blocB
///
/// ```dart
/// final receiverStr = StreamedValue<String>();
/// ```
///
/// 2 - Define a [StreamedSender] in the blocA
///
/// ```dart
/// final tunnelSenderStr = StreamedSender<String>();
/// ```
///
///
/// 3 - Set the receiver in the sender on the class the holds the instances
/// of the blocs
///
/// ```dart///
/// blocA.tunnelSenderStr.setReceiver(blocB.receiverStr);
/// ```
///
/// 4 - To send data from blocA to bloc B then:
///
/// ```dart
/// tunnelSenderStr.send("Text from blocA to blocB");
/// ```
class StreamedSender<T> {
StreamedSender();
StreamedSender.setReceiver(StreamedValue<T> receiver)
: assert(receiver != null, 'The receiver argument is null.') {
_receiver = receiver;
}
StreamedValue<T> _receiver;
void setReceiver(StreamedValue<T> receiver) {
assert(receiver != null, 'The receiver argument is null.');
_receiver = receiver;
}
void send(T data) {
_receiver.value = data;
if (T is List || T is Map) {
_receiver.refresh();
}
}
}
/// Like the StreamedSender, but used with lists.
///
/// #### Usage
///
/// 1 - Define a [StreamedList] object in the blocB
///
/// ```dart
/// final receiverList = StreamedList<int>();
/// ```
///
/// 2 - Define a [ListSender] in the blocA
///
/// ```dart
/// final tunnelList = ListSender<int>();
/// ```
///
/// 3 - Set the receiver in the sender on the class the holds
/// the instances of the blocs
///
/// ```dart
/// blocA.tunnelList.setReceiver(blocB.receiverList);
/// ```
///
/// 4 - To send data from blocA to bloc B then:
///
/// ```dart
/// tunnelList.send(list);
/// ```
///
class ListSender<T> {
ListSender();
ListSender.setReceiver(StreamedList<T> receiver)
: assert(receiver != null, 'The receiver argument is null.') {
_receiver = receiver;
}
StreamedList<T> _receiver;
void setReceiver(StreamedList<T> receiver) {
assert(receiver != null, 'The receiver argument is null.');
_receiver = receiver;
}
void send(List<T> data) {
_receiver.value = data;
}
}
/// Like the StreamedList, but used with maps.
///
/// #### Usage
///
/// 1 - Define a [StreamedMap]object in the blocB
///
/// ```dart
/// final receiverMap = StreamedMap<int, String>();
/// ```
///
/// 2 - Define a [MapSender] in the blocA
///
/// ```dart
/// final tunnelMap = MapSender<int, String>();
/// ```
///
/// 3 - Set the receiver in the sender on the class the holds
/// the instances of the blocs
///
/// ```dart
/// blocA.tunnelMap.setReceiver(blocB.receiverMap);
/// ```
///
/// 4 - To send data from blocA to bloc B then:
///
/// ```dart
/// tunnelMap.send(map);
/// ```
///
class MapSender<K, V> {
MapSender();
MapSender.setReceiver(StreamedMap<K, V> receiver)
: assert(receiver != null, 'The receiver argument is null.') {
_receiver = receiver;
}
StreamedMap<K, V> _receiver;
/// Method to set the [StreamedMap] on the other bloc where
/// to send the data
void setReceiver(StreamedMap<K, V> receiver) {
assert(receiver != null, 'The receiver argument is null.');
_receiver = receiver;
}
/// Method to send the data to the StreamedMap set by the [setReceiver]
/// method.
void send(Map<K, V> data) {
_receiver.value = data;
}
}
| 0
|
mirrored_repositories/frideos_flutter/lib/src/core
|
mirrored_repositories/frideos_flutter/lib/src/core/src/streamed_map.dart
|
import 'dart:async';
import '../core.dart';
///
///
/// Used when T is a map, it works like [StreamedValue].
///
/// To modify the list (e.g. adding items) and update the stream automatically
/// use these methods:
///
/// - [addKey]
/// - [clear]
/// - [removeKey]
///
/// For other direct actions on the map, to update the stream call
/// the [refresh] method instead.
///
/// #### Usage
///
/// e.g. adding a key/value pair:
///
/// ```dart
/// streamedMap.addKey(1, 'first');
/// ```
///
/// it is the same as:
///
/// ```dart
/// streamedMap.value[1] = 'first';
/// streamedList.refresh();
/// ```
///
///
/// From the streamed map example:
///
/// ```dart
/// final streamedMap = StreamedMap<int, String>();
///
///
/// // Add to the streamed map the key/value pair put by the user
/// addText() {
/// var key = int.parse(streamedKey.value);
/// var value = streamedText.value;
///
/// streamedMap.addKey(key, value);
///
/// // Or, as an alternative:
/// //streamedMap.value[key] = value;
/// //streamedMap.refresh();
/// }
/// ```
///
///
class StreamedMap<K, V> implements StreamedObject<Map<K, V>> {
StreamedMap({Map<K, V> initialData, this.onError}) {
stream = StreamedValue<Map<K, V>>()
..stream.stream.listen((data) {
if (_onChange != null) {
_onChange(data);
}
}, onError: onError);
if (initialData != null) {
stream.value = initialData;
}
}
StreamedValue<Map<K, V>> stream;
/// Callback to handle the errors
final Function onError;
/// Sink for the stream
Function(Map<K, V>) get inStream => stream.inStream;
/// Stream getter
@override
Stream<Map<K, V>> get outStream => stream.outStream;
/// The initial event of the stream
Map<K, V> initialData;
/// Last value emitted by the stream
Map<K, V> lastValue;
/// timesUpdate shows how many times the got updated
int timesUpdated = 0;
@override
Map<K, V> get value => stream.value;
int get length => stream.value.length;
/// This function will be called every time the stream updates.
void Function(Map<K, V> data) _onChange;
/// Clear the map, add all the key/value pairs of the map passed
/// and update the stream
set value(Map<K, V> map) {
stream.value = map;
if (_debugMode) {
timesUpdated++;
}
}
/// Debug mode (Default: false)
bool _debugMode = false;
/// To enable the debug mode
void debugMode() {
_debugMode = true;
}
/// To set a function that will be called every time the stream updates.
void onChange(Function(Map<K, V>) onDataChanged) {
_onChange = onDataChanged;
}
/// Used to add key/value pair to the map and update the stream.
void addKey(K key, V val) {
value[key] = val;
refresh();
}
/// Used to remove a key from the map and update the stream.
V removeKey(K key) {
final removed = value.remove(key);
refresh();
return removed;
}
/// Used to clear the map and update the stream.
void clear() {
value.clear();
refresh();
}
/// To refresh the stream when the map is modified without using the
/// methods of this class.
void refresh() {
inStream(value);
if (_debugMode) {
timesUpdated++;
}
}
/// Dispose the stream.
void dispose() {
if (_debugMode) {
print('---------- Closing Stream ------ type: Map<$K, $V>');
print('Value: $value');
print('Updated times: $timesUpdated');
}
stream.dispose();
}
}
| 0
|
mirrored_repositories/frideos_flutter/lib/src/core/src
|
mirrored_repositories/frideos_flutter/lib/src/core/src/interfaces/streamed_object.dart
|
import 'dart:async';
///
/// Interface for all the StreamedObjects
///
abstract class StreamedObject<T> {
/// Getter for the stream exposed by the classes that implement
/// the StreamedObject interface.
Stream<T> get outStream;
/// Getter for the last value emitted by the stream
T get value;
}
| 0
|
mirrored_repositories/frideos_flutter/lib/src
|
mirrored_repositories/frideos_flutter/lib/src/effects/transitions.dart
|
import 'dart:async';
import 'package:flutter/material.dart';
import '../core/core.dart';
import '../extended_asyncwidgets.dart';
///
///
/// Fade out transition widget.
///
///
class FadeOutWidget extends StatefulWidget {
const FadeOutWidget(
{@required this.child,
@required this.duration,
Key key,
this.curve = Curves.linear})
: assert(child != null, 'The child argument is null.'),
assert(duration != null, 'The duration argument is null.'),
super(key: key);
final Widget child;
final int duration;
final Curve curve;
@override
_FadeOutWidgetState createState() {
return _FadeOutWidgetState();
}
}
class _FadeOutWidgetState extends State<FadeOutWidget>
with SingleTickerProviderStateMixin {
AnimationController controller;
CurvedAnimation animationCurve;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: Duration(milliseconds: widget.duration), vsync: this);
animationCurve = CurvedAnimation(parent: controller, curve: widget.curve)
..addListener(() {
setState(() {});
});
controller.forward();
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
child: Stack(
children: <Widget>[
Opacity(
opacity: 1.0 - animationCurve.value,
child: widget.child,
),
],
));
}
}
///
///
/// Fade in transition widget.
///
///
class FadeInWidget extends StatefulWidget {
const FadeInWidget(
{@required this.child,
@required this.duration,
Key key,
this.curve = Curves.linear})
: assert(child != null, 'The child argument is null.'),
assert(duration != null, 'The duration argument is null.'),
super(key: key);
final Widget child;
final int duration;
final Curve curve;
@override
_FadeInWidgetState createState() {
return _FadeInWidgetState();
}
}
class _FadeInWidgetState extends State<FadeInWidget>
with SingleTickerProviderStateMixin {
AnimationController controller;
CurvedAnimation animationCurve;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: Duration(milliseconds: widget.duration), vsync: this);
animationCurve = CurvedAnimation(parent: controller, curve: widget.curve)
..addListener(() {
setState(() {});
});
controller.forward();
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
child: Stack(
children: <Widget>[
Opacity(
opacity: animationCurve.value,
child: widget.child,
),
],
));
}
}
///
///
/// Linear cross fading transition between two widgets, it can be used
/// with the `StagedObject`.
///
///
class LinearTransition extends StatefulWidget {
const LinearTransition({
@required this.firstWidget,
@required this.secondWidget,
@required this.transitionDuration,
Key key,
}) : assert(firstWidget != null, 'The firstWidget argument is null.'),
assert(secondWidget != null, 'The secondWidget argument is null.'),
assert(transitionDuration != null,
'The transitionDuration argument is null.'),
super(key: key);
final Widget firstWidget;
final Widget secondWidget;
final int transitionDuration;
@override
_LinearTransitionState createState() {
return _LinearTransitionState();
}
}
class _LinearTransitionState extends State<LinearTransition> {
final StreamedValue<double> opacity = StreamedValue<double>();
Timer timer;
int interval;
double opacityVel;
void _updateOpacity(Timer t) {
var newOpacity = opacity.value + opacityVel;
if (newOpacity > 1.0) {
newOpacity = 1.0;
timer.cancel();
}
opacity.value = newOpacity;
}
@override
void initState() {
super.initState();
opacity.value = 0.0;
interval = 20;
opacityVel = 1.0 / (widget.transitionDuration / interval);
timer = Timer.periodic(Duration(milliseconds: interval), _updateOpacity);
}
@override
void dispose() {
if (timer != null) {
timer.cancel();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
child: ValueBuilder<double>(
streamed: opacity,
builder: (context, snapshot) {
return Stack(
children: <Widget>[
Opacity(
opacity: 1.0 - snapshot.data,
child: widget.firstWidget,
),
Opacity(
opacity: snapshot.data,
child: widget.secondWidget,
),
],
);
},
noDataChild: widget.firstWidget,
),
);
}
}
///
///
/// Cross fading transition between two widgets. This uses the Flutter
/// way to make an animation.
///
///
class CurvedTransition extends StatefulWidget {
const CurvedTransition(
{@required this.firstWidget,
@required this.secondWidget,
@required this.transitionDuration,
Key key,
this.curve})
: assert(firstWidget != null, 'The firstWidget argument is null.'),
assert(secondWidget != null, 'The secondWidget argument is null.'),
assert(transitionDuration != null,
'The transitionDuration argument is null.'),
super(key: key);
final Widget firstWidget;
final Widget secondWidget;
final int transitionDuration;
final Curve curve;
@override
_CurvedTransitionState createState() {
return _CurvedTransitionState();
}
}
class _CurvedTransitionState extends State<CurvedTransition>
with SingleTickerProviderStateMixin {
AnimationController controller;
CurvedAnimation animationCurve;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: Duration(milliseconds: widget.transitionDuration),
vsync: this);
animationCurve = CurvedAnimation(parent: controller, curve: widget.curve)
..addListener(() {
setState(() {});
});
controller.forward();
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
child: Stack(
children: <Widget>[
Opacity(
opacity: 1.0 - animationCurve.value,
child: widget.firstWidget,
),
Opacity(
opacity: animationCurve.value,
child: widget.secondWidget,
),
],
));
}
}
| 0
|
mirrored_repositories/frideos_flutter/lib/src
|
mirrored_repositories/frideos_flutter/lib/src/effects/waves.dart
|
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../core/core.dart';
import '../extended_asyncwidgets.dart';
const double strokeWidth = 25;
const double baseHeight = 15;
///
/// Waves animation
///
class WavesWidget extends StatefulWidget {
const WavesWidget({
@required this.child,
Key key,
this.width,
this.height,
this.color,
this.refreshTime = 20,
}) : assert(child != null, 'The child argument is null.'),
super(key: key);
final double width;
final double height;
final MaterialColor color;
final Widget child;
///
/// Refresh time in milliseconds (default: 20)
///
final int refreshTime;
@override
_WavesWidgetState createState() {
return _WavesWidgetState();
}
}
class _WavesWidgetState extends State<WavesWidget> {
AnimatedObject<int> frame;
@override
void initState() {
super.initState();
frame = AnimatedObject<int>(initialValue: 1, interval: widget.refreshTime);
frame.animation.value = 1;
frame.start((t) {
frame.animation.value += 10;
});
}
@override
void dispose() {
frame.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) => ValueBuilder<int>(
streamed: frame.animation,
builder: (context, snapshot) {
return Stack(
children: <Widget>[
Container(
alignment: Alignment.center,
height: widget.height,
child: widget.child,
),
CustomPaint(
painter:
_WavesPainter(frame: snapshot.data, color: widget.color),
child: Container(
height: widget.height,
),
),
],
);
}),
);
}
}
class _WavesPainter extends CustomPainter {
_WavesPainter({this.frame, this.color});
final int frame;
MaterialColor color;
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = color[700]
..strokeWidth = strokeWidth
..strokeCap = StrokeCap.round
..blendMode = BlendMode.softLight
..style = PaintingStyle.stroke;
final height = size.height - paint.strokeWidth / 2;
final width = size.width;
final path = Path()
..moveTo(0, height + baseHeight)
..lineTo(width, height + baseHeight)
..moveTo(0, height + baseHeight);
for (int i = 0; i < size.width.toInt(); i += 6) {
final x = i * 1.0;
final sin = math.sin((frame + i) * math.pi / 180.0);
path.lineTo(x, height - sin * 5.0);
}
canvas.drawPath(path, paint);
paint
..color = color[300]
..strokeWidth = strokeWidth
..strokeCap = StrokeCap.round
..blendMode = BlendMode.softLight
..style = PaintingStyle.stroke;
path
..reset()
..moveTo(0, height + baseHeight)
..lineTo(width, height + baseHeight)
..moveTo(0, height + baseHeight);
for (int i = 0; i < size.width.toInt(); i += 3) {
final x = i * 1.0;
final sin = math.sin((frame + i + 90.0) * math.pi / 180.0);
path.lineTo(x, height - sin * 8.0);
}
canvas.drawPath(path, paint);
paint
..color = color[300]
..strokeWidth = strokeWidth
..strokeCap = StrokeCap.round
..blendMode = BlendMode.softLight
..style = PaintingStyle.stroke;
path
..reset()
..moveTo(0, height + baseHeight)
..lineTo(width, height + baseHeight)
..moveTo(0, height + baseHeight);
for (int i = 0; i < size.width.toInt(); i += 3) {
final x = i * 1.0;
final sin = math.sin((frame + i + 180.0) * math.pi / 180.0);
path.lineTo(x, height - sin * 6.0);
}
canvas.drawPath(path, paint);
paint
..color = color[500]
..strokeWidth = strokeWidth
..strokeCap = StrokeCap.round
..blendMode = BlendMode.softLight
..style = PaintingStyle.stroke;
path
..reset()
..moveTo(0, height + baseHeight)
..lineTo(width, height + baseHeight)
..moveTo(0, height + baseHeight);
for (int i = 0; i < size.width.toInt(); i += 3) {
final x = i * 1.0;
final sin = math.sin((frame + i + 135.0) * math.pi / 180.0);
path.lineTo(x, height - sin * 8.0);
}
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => true;
}
| 0
|
mirrored_repositories/frideos_flutter/lib/src
|
mirrored_repositories/frideos_flutter/lib/src/effects/blur.dart
|
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import '../core/core.dart';
import '../extended_asyncwidgets.dart';
const double initialBlurVel = 0.1;
const int blurRefreshTime = 20;
///
/// Fixed Blur
///
class BlurWidget extends StatelessWidget {
const BlurWidget({
@required this.child,
@required this.sigmaX,
@required this.sigmaY,
Key key,
}) : assert(child != null, 'The child argument is null.'),
assert(sigmaX != null, 'The sigmaX argument is null.'),
assert(sigmaY != null, 'The sigmaY argument is null.'),
super(key: key);
///
/// Child to blur
///
final Widget child;
///
/// Vvalue of the sigmaX parameter of the blur
///
final double sigmaX;
///
/// Value of the sigmaY parameter of the blur
///
final double sigmaY;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) => Stack(
children: <Widget>[
Container(
height: constraints.maxHeight,
width: constraints.maxWidth,
child: child),
ClipRect(
child: BackdropFilter(
filter: ui.ImageFilter.blur(sigmaX: sigmaX, sigmaY: sigmaY),
child: Container(
height: constraints.maxHeight,
width: constraints.maxWidth,
color: Colors.transparent,
)),
),
],
),
);
}
}
///
/// Animated blur
///
class AnimatedBlurWidget extends StatefulWidget {
const AnimatedBlurWidget(
{@required this.child,
Key key,
this.initialSigmaX = 0.0,
this.initialSigmaY = 0.0,
this.finalSigmaX = 4.0,
this.finalSigmaY = 8.0,
this.duration = 5000,
this.reverseAnimation = true,
this.loop = true,
this.refreshTime = blurRefreshTime})
: assert(child != null, 'The child argument is null.'),
super(key: key);
///
/// Child to blur
///
final Widget child;
///
/// Initial value of the sigmaX parameter of the blur
///
final double initialSigmaX;
///
/// Initial value of the sigmaY parameter of the blur
///
final double initialSigmaY;
///
/// Final value of the sigmaX parameter of the blur
///
final double finalSigmaX;
///
/// Final value of the sigmaY parameter of the blur
///
final double finalSigmaY;
///
/// Time for the blur to reach the final values
///
final int duration;
///
/// Looping animation (default: false)
///
final bool loop;
///
/// Refresh time in milliseconds (default: 20)
///
final int refreshTime;
///
/// If set to true (default: true), when the max values are reached
/// the animation reverses until the values reaches their initial value
///
final bool reverseAnimation;
@override
_AnimatedBlurWidgetState createState() {
return _AnimatedBlurWidgetState();
}
}
class _AnimatedBlurWidgetState extends State<AnimatedBlurWidget> {
AnimatedObject<double> blur;
double blurSigmaY;
@override
void initState() {
super.initState();
blur = AnimatedObject(
initialValue: widget.initialSigmaX, interval: widget.refreshTime);
//blur.animation.value = widget.initialSigmaX;
blurSigmaY = widget.initialSigmaY;
// Calculate the step of the blur
//
var blurVelX = (widget.finalSigmaX - widget.initialSigmaX) /
(widget.duration / widget.refreshTime);
var blurVelY = (widget.finalSigmaY - widget.initialSigmaY) /
(widget.duration / widget.refreshTime);
blur.start((t) {
// Update the blur.
//
blur.value += blurVelX;
blurSigmaY += blurVelY;
// Check if limit reached.
//
if (blur.value > widget.finalSigmaX) {
// If the reverseAnimation flag is set to true (default)
// then invert the direction.
//
if (widget.reverseAnimation) {
blurVelX = -blurVelX;
blurVelY = -blurVelY;
} else {
// If the loop flag is set true (default: false)
// then reset the blur values
//
if (widget.loop) {
blur.value = 0.0;
blurSigmaY = 0.0;
}
// Otherwise, stop the animation.
//
else {
blur.stop();
}
}
}
// Check if the value is below the initialValue.
//
if (blur.animation.value < widget.initialSigmaX) {
// If the loop flag is set to true, invert the direction
// of the animation.
//
if (widget.loop) {
blurVelX = -blurVelX;
blurVelY = -blurVelY;
}
// Otherwise, stop the animation.
//
else {
blur.stop();
}
}
});
}
@override
void dispose() {
blur.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) => ValueBuilder<double>(
streamed: blur.animation,
builder: (context, snapshot) {
return Stack(
children: <Widget>[
Container(
height: constraints.maxHeight,
width: constraints.maxWidth,
child: widget.child),
ClipRect(
child: BackdropFilter(
filter: ui.ImageFilter.blur(
sigmaX: snapshot.data, sigmaY: blurSigmaY),
child: Container(
height: constraints.maxHeight,
width: constraints.maxWidth,
color: Colors.transparent,
)),
),
],
);
}),
);
}
}
///
/// Blur in
///
class BlurInWidget extends StatefulWidget {
const BlurInWidget(
{@required this.child,
Key key,
this.initialSigmaX = 4.0,
this.initialSigmaY = 6.0,
this.duration = 5000,
this.refreshTime = blurRefreshTime})
: assert(child != null, 'The child argument is null.'),
super(key: key);
///
/// Child to blur
///
final Widget child;
///
/// Initial value of the sigmaX parameter of the blur
///
final double initialSigmaX;
///
/// Initial value of the sigmaY parameter of the blur
///
final double initialSigmaY;
///
/// Time for the blur to reach the final values
///
final int duration;
///
/// Refresh time in milliseconds (default: 20)
///
final int refreshTime;
@override
_BlurInWidgetState createState() {
return _BlurInWidgetState();
}
}
class _BlurInWidgetState extends State<BlurInWidget> {
AnimatedObject<double> blur;
double blurSigmaY;
@override
void initState() {
super.initState();
blur = AnimatedObject(
initialValue: widget.initialSigmaX, interval: blurRefreshTime);
blur.value = widget.initialSigmaX;
blurSigmaY = widget.initialSigmaY;
// Calculate the step of the blur
//
var blurVelX = widget.initialSigmaX / (widget.duration / blurRefreshTime);
final blurVelY = widget.initialSigmaY / (widget.duration / blurRefreshTime);
blur.start((t) {
blur.value -= blurVelX;
blurSigmaY -= blurVelY;
if (blur.value < 0.0) {
blurVelX = 0.0;
blurSigmaY = 0.0;
blur.stop();
}
});
}
@override
void dispose() {
blur.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) => ValueBuilder<double>(
streamed: blur.animation,
builder: (context, snapshot) {
return Stack(
children: <Widget>[
Container(
height: constraints.maxHeight,
width: constraints.maxWidth,
child: widget.child),
ClipRect(
child: BackdropFilter(
filter: ui.ImageFilter.blur(
sigmaX: snapshot.data, sigmaY: blurSigmaY),
child: Container(
height: constraints.maxHeight,
width: constraints.maxWidth,
color: Colors.transparent,
)),
),
],
);
}),
);
}
}
///
/// Blur out
///
class BlurOutWidget extends StatefulWidget {
const BlurOutWidget(
{@required this.child,
Key key,
this.finalSigmaX = 4.0,
this.finalSigmaY = 6.0,
this.duration = 5000,
this.refreshTime = blurRefreshTime})
: assert(child != null, 'The child argument is null.'),
super(key: key);
///
/// Child to blur
///
final Widget child;
///
/// Final value of the sigmaX parameter of the blur
///
final double finalSigmaX;
///
/// Final value of the sigmaY parameter of the blur
///
final double finalSigmaY;
///
/// Time for the blur to reach the final values
///
final int duration;
///
/// Refresh time in milliseconds (default: 20)
///
final int refreshTime;
@override
_BlurOutWidgetState createState() {
return _BlurOutWidgetState();
}
}
class _BlurOutWidgetState extends State<BlurOutWidget> {
AnimatedObject<double> blur;
double blurSigmaY = 0;
@override
void initState() {
super.initState();
blur = AnimatedObject(initialValue: 0, interval: blurRefreshTime);
// Calculate the step of the blur
//
var blurVelX = widget.finalSigmaX / (widget.duration / blurRefreshTime);
final blurVelY = widget.finalSigmaY / (widget.duration / blurRefreshTime);
blur.start((t) {
blur.value += blurVelX;
blurSigmaY += blurVelY;
if (blur.value > widget.finalSigmaX) {
blurVelX = widget.finalSigmaX;
blurSigmaY = widget.finalSigmaY;
blur.stop();
}
});
}
@override
void dispose() {
blur.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) => ValueBuilder<double>(
streamed: blur.animation,
builder: (context, snapshot) {
return Stack(
children: <Widget>[
Container(
height: constraints.maxHeight,
width: constraints.maxWidth,
child: widget.child),
ClipRect(
child: BackdropFilter(
filter: ui.ImageFilter.blur(
sigmaX: snapshot.data, sigmaY: blurSigmaY),
child: Container(
height: constraints.maxHeight,
width: constraints.maxWidth,
color: Colors.transparent,
)),
),
],
);
}),
);
}
}
| 0
|
mirrored_repositories/frideos_flutter/lib/src
|
mirrored_repositories/frideos_flutter/lib/src/interfaces/app_state.dart
|
/// Interface to extend to define the own app state model
/// to use along with the [AppStateProvider]
///
abstract class AppStateModel {
/// This method is called in the `initState` method of the `State` class
/// associated to the [AppStateProvider].
void init();
void dispose();
}
| 0
|
mirrored_repositories/frideos_flutter/lib/src
|
mirrored_repositories/frideos_flutter/lib/src/animations/animations.dart
|
import 'package:flutter/material.dart';
///
///
///
typedef AnimationStatusCallback = Function(AnimationStatus status);
///
/// AnimationBaseClass
///
///
///
///
class AnimationBaseClass {
AnimationBaseClass({
this.duration,
this.setState,
this.tickerProvider,
this.onAnimating,
});
final Duration duration;
final dynamic setState;
final TickerProvider tickerProvider;
final AnimationStatusCallback onAnimating;
// Controller and getters
AnimationController baseController;
AnimationStatus get status => baseController.status;
bool get isAnimating => baseController.isAnimating;
bool get isCompleted => baseController.isCompleted;
bool get isDismissed => baseController.isDismissed;
double get controllerValue => baseController.value;
double get progress => controllerValue * 100.0;
void init() {
baseController = AnimationController(
duration: duration,
vsync: tickerProvider,
);
if (onAnimating != null) {
baseController.addListener(() {
setState(() {});
onAnimating(status);
});
} else {
baseController.addListener(() {
setState(() {});
});
}
}
void forward() {
baseController.forward();
}
void reverse() {
baseController.reverse();
}
void dispose() {
baseController.dispose();
}
void stop({bool canceled}) {
baseController.stop(canceled: canceled);
}
void reset() {
baseController.reset();
}
}
///
/// AnimationTween
///
///
///
///
class AnimationTween<T> extends AnimationBaseClass {
AnimationTween({
@required this.begin,
@required this.end,
dynamic setState,
TickerProvider tickerProvider,
Duration duration,
this.controller,
AnimationStatusCallback onAnimating,
}) : assert(begin != null && end != null),
super(
duration: duration,
setState: setState,
tickerProvider: tickerProvider,
onAnimating: onAnimating,
) {
// If a controller is not provided, then is
// called the `init` method of the AnimationBaseClass to initialize
// its `baseController`
if (controller == null) {
super.init();
}
animation =
Tween<T>(begin: begin, end: end).animate(controller ?? baseController);
}
final T begin;
final T end;
final AnimationController controller;
Animation<T> animation;
T get value => animation.value;
}
///
/// AnimationCurved
///
///
///
///
class AnimationCurved<T> extends AnimationBaseClass {
AnimationCurved({
this.controller,
@required this.begin,
@required this.end,
@required this.curve,
this.reverseCurve,
dynamic setState,
TickerProvider tickerProvider,
Duration duration,
AnimationStatusCallback onAnimating,
}) : assert(begin != null && end != null && curve != null),
super(
duration: duration,
setState: setState,
tickerProvider: tickerProvider,
onAnimating: onAnimating,
) {
// If a controller is not provided, then is
// called the `init` method of the AnimationBaseClass to initialize
// its `baseController`
if (controller == null) {
super.init();
}
animation = Tween<T>(begin: begin, end: end).animate(CurvedAnimation(
parent: controller ?? baseController,
curve: curve,
reverseCurve: reverseCurve));
}
final T begin;
final T end;
final Curve curve;
final Curve reverseCurve;
final AnimationController controller;
Animation<T> animation;
T get value => animation.value;
}
///
///
///
typedef AnimationCreateBuilder = Widget Function(
BuildContext context, AnimationCurved animation);
///
/// AnimationCreate
///
///
///
///
class AnimationCreate<T> extends StatefulWidget {
const AnimationCreate({
Key key,
@required this.begin,
@required this.end,
this.curve = Curves.linear,
this.reverseCurve = Curves.linear,
this.duration = 1000,
this.repeat = false,
this.reverse = false,
this.onAnimating,
this.onStart,
this.onCompleted,
this.builder,
}) : super(key: key);
final T begin;
final T end;
final Curve curve;
final Curve reverseCurve;
final int duration;
final Function onAnimating;
final Function onCompleted;
final Function onStart;
final AnimationCreateBuilder builder;
final bool repeat;
final bool reverse;
@override
_AnimationCreateState<T> createState() => _AnimationCreateState<T>();
}
class _AnimationCreateState<T> extends State<AnimationCreate<T>>
with SingleTickerProviderStateMixin {
AnimationCurved<T> animation;
@override
void initState() {
super.initState();
animation = AnimationCurved(
begin: widget.begin,
end: widget.end,
curve: widget.curve,
reverseCurve: widget.reverseCurve,
duration: Duration(milliseconds: widget.duration),
setState: setState,
tickerProvider: this,
onAnimating: _onAnimating,
)..forward();
if (widget.onStart != null) {
widget.onStart();
}
}
@override
@override
void dispose() {
animation.dispose();
super.dispose();
}
void _onAnimating(AnimationStatus status) {
if (widget.repeat) {
if (animation.status == AnimationStatus.completed) {
if (widget.reverse) {
animation.reverse();
} else {
animation.reset();
}
if (widget.onCompleted != null) {
widget.onCompleted();
}
} else if (animation.status == AnimationStatus.dismissed) {
animation.forward();
if (widget.onStart != null) {
widget.onStart();
}
}
} else {
if (animation.status == AnimationStatus.completed) {
if (widget.reverse) {
animation.reverse();
}
if (widget.onCompleted != null) {
widget.onCompleted();
}
}
}
if (widget.onAnimating != null) {
widget.onAnimating();
}
}
@override
Widget build(BuildContext context) {
return widget.builder(context, animation);
}
}
///
/// CompositeItem
///
///
///
///
class CompositeItem<T> {
CompositeItem({
@required this.begin,
@required this.end,
this.curve,
this.reverseCurve,
}) : assert(begin != null && end != null);
final T begin;
final T end;
final Curve curve;
final Curve reverseCurve;
Animation<dynamic> animation;
}
///
/// CompositeAnimation
///
///
///
///
class CompositeAnimation extends AnimationBaseClass {
CompositeAnimation({
@required this.composite,
@required dynamic setState,
@required TickerProvider tickerProvider,
@required Duration duration,
AnimationStatusCallback onAnimating,
}) : assert(
composite != null &&
composite.isNotEmpty &&
setState != null &&
tickerProvider != null &&
duration != null,
),
super(
duration: duration,
setState: setState,
tickerProvider: tickerProvider,
onAnimating: onAnimating,
) {
// Init the AnimationBaseClass
super.init();
composite.values.forEach((tween) {
if (tween.curve == null) {
if (tween.begin.runtimeType == MaterialColor) {
tween.animation = ColorTween(begin: tween.begin, end: tween.end)
.animate(baseController);
} else {
tween.animation = Tween<dynamic>(begin: tween.begin, end: tween.end)
.animate(baseController);
}
} else {
if (tween.begin.runtimeType == MaterialColor) {
tween.animation = ColorTween(begin: tween.begin, end: tween.end)
.animate(baseController);
} else {
tween.animation = Tween<dynamic>(begin: tween.begin, end: tween.end)
.animate(CurvedAnimation(
parent: baseController,
curve: tween.curve,
reverseCurve: tween.reverseCurve));
}
}
});
}
final Map<dynamic, CompositeItem<dynamic>> composite;
dynamic value(dynamic key) => composite[key].animation.value;
int valueInt(dynamic key) => composite[key].animation.value.toInt();
dynamic animation(dynamic key) => composite[key].animation;
AnimationStatus animationStatus(dynamic key) =>
composite[key].animation.status;
}
///
///
///
///
typedef CompositeCreateBuilder = Widget Function(
BuildContext context, CompositeAnimation compositeAnimation);
///
/// CompositeCreate
///
///
///
///
class CompositeCreate extends StatefulWidget {
const CompositeCreate({
Key key,
this.duration = 1000,
this.compositeMap,
this.repeat = false,
this.onAnimating,
this.onStart,
this.onCompleted,
this.builder,
}) : super(key: key);
final int duration;
final Map<dynamic, CompositeItem> compositeMap;
final Function onAnimating;
final Function onCompleted;
final Function onStart;
final CompositeCreateBuilder builder;
final bool repeat;
@override
_CompositeCreateState createState() => _CompositeCreateState();
}
class _CompositeCreateState extends State<CompositeCreate>
with TickerProviderStateMixin {
CompositeAnimation compositeAnimation;
@override
void initState() {
super.initState();
compositeAnimation = CompositeAnimation(
duration: Duration(milliseconds: widget.duration),
setState: setState,
tickerProvider: this,
onAnimating: _onAnimating,
composite: widget.compositeMap,
)..forward();
if (widget.onStart != null) {
widget.onStart();
}
}
@override
@override
void dispose() {
compositeAnimation.dispose();
super.dispose();
}
void _onAnimating(AnimationStatus status) {
if (widget.repeat) {
if (compositeAnimation.status == AnimationStatus.completed) {
compositeAnimation.reverse();
if (widget.onCompleted != null) {
widget.onCompleted();
}
} else if (compositeAnimation.status == AnimationStatus.dismissed) {
compositeAnimation.forward();
if (widget.onStart != null) {
widget.onStart();
}
}
} else {
if (compositeAnimation.status == AnimationStatus.completed) {
if (widget.onCompleted != null) {
widget.onCompleted();
}
}
}
if (widget.onAnimating != null) {
widget.onAnimating();
}
}
@override
Widget build(BuildContext context) {
return widget.builder(context, compositeAnimation);
}
}
| 0
|
mirrored_repositories/frideos_flutter
|
mirrored_repositories/frideos_flutter/test/transitions_test.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter/rendering.dart';
import 'package:frideos/frideos.dart';
void main() {
testWidgets('FadeOutWidget', (WidgetTester tester) async {
final key = GlobalKey();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: FadeOutWidget(
key: key,
child: Text('test'),
duration: 1000,
),
),
),
);
expect(find.text('test'), findsOneWidget);
RenderOpacity renderOpacity = tester
.renderObject(find.byKey(key))
.debugDescribeChildren()
.first
.value;
expect(renderOpacity.opacity, 1.0);
print(renderOpacity.opacity);
await tester.pump(new Duration(milliseconds: 500));
renderOpacity = tester
.renderObject(find.byKey(key))
.debugDescribeChildren()
.first
.value;
print(renderOpacity.opacity);
await tester.pump(new Duration(milliseconds: 500));
renderOpacity = tester
.renderObject(find.byKey(key))
.debugDescribeChildren()
.first
.value;
print(renderOpacity.opacity);
expect(renderOpacity.opacity, 0.0);
});
testWidgets('FadeInWidget', (WidgetTester tester) async {
final key = GlobalKey();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: FadeInWidget(
key: key,
child: Text('test'),
duration: 1000,
),
),
),
);
expect(find.text('test'), findsOneWidget);
RenderOpacity renderOpacity = tester
.renderObject(find.byKey(key))
.debugDescribeChildren()
.first
.value;
expect(renderOpacity.opacity, 0.0);
print(renderOpacity.opacity);
await tester.pump(new Duration(milliseconds: 500));
renderOpacity = tester
.renderObject(find.byKey(key))
.debugDescribeChildren()
.first
.value;
print(renderOpacity.opacity);
await tester.pump(new Duration(milliseconds: 500));
renderOpacity = tester
.renderObject(find.byKey(key))
.debugDescribeChildren()
.first
.value;
print(renderOpacity.opacity);
expect(renderOpacity.opacity, 1.0);
});
}
| 0
|
mirrored_repositories/frideos_flutter
|
mirrored_repositories/frideos_flutter/test/staged_widget_test.dart
|
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:frideos/frideos.dart';
void main() {
testWidgets('StagedWidget', (WidgetTester tester) async {
var onShow = '';
var onStart = '';
var onEnd = '';
var stagesMap = <int, Stage>{
0: Stage(
widget: Container(
key: Key('0'),
child: Text('Stage 0'),
),
time: 2000,
onShow: () {
onShow = 'Stage 0';
//tester.pump();
}),
1: Stage(
widget: Container(
key: Key('1'),
child: Text('Stage 1'),
),
time: 2000,
onShow: () {
onShow = 'Stage 1';
}),
2: Stage(
widget: Container(
key: Key('2'),
child: Text('Stage 2'),
),
time: 2000,
onShow: () {
onShow = 'Stage 2';
}),
};
await tester.runAsync(() async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: StagedWidget(
stagesMap: stagesMap,
onStart: () {
onStart = 'onStart';
},
onEnd: () {
onEnd = 'onEnd';
}),
),
),
);
await tester.pump();
expect(find.text('Stage 0'), findsOneWidget);
expect(onShow, 'Stage 0');
expect(onStart, 'onStart');
// TODO: fixing test error after using tick in TimerObject
/*
await tester.pump(new Duration(milliseconds: 2200));
expect(find.text('Stage 1'), findsOneWidget);
expect(onShow, 'Stage 1');
await tester.pump(new Duration(milliseconds: 2200));
expect(find.text('Stage 2'), findsOneWidget);
expect(onShow, 'Stage 2');
await tester.pump(new Duration(milliseconds: 2200));
expect(onEnd, 'onEnd');
*/
});
});
}
| 0
|
mirrored_repositories/frideos_flutter
|
mirrored_repositories/frideos_flutter/test/extended_asyncwidgets_test.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:frideos/frideos.dart';
void main() {
//
// StreamedWidget
//
testWidgets('StreamedWidget NoDataChild', (WidgetTester tester) async {
final streamedValue = StreamedValue<Widget>();
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: StreamedWidget(
stream: streamedValue.outStream,
builder: (context, snapshot) {
return snapshot.data;
},
noDataChild: Text('NoData'),
),
),
));
expect(find.text('testwidget'), findsNothing);
expect(find.text('NoData'), findsOneWidget);
streamedValue.value = Text('testwidget');
await tester.pumpAndSettle();
expect(find.text('testwidget'), findsOneWidget);
streamedValue.dispose();
});
testWidgets('StreamedWidget onNoData callback', (WidgetTester tester) async {
final streamedValue = StreamedValue<Widget>();
var str = '';
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: StreamedWidget(
stream: streamedValue.outStream,
builder: (context, snapshot) {
return snapshot.data;
},
onNoData: () {
str = 'callback';
return Text('NoData');
},
),
),
));
expect(find.text('testwidget'), findsNothing);
expect(str, 'callback');
expect(find.text('NoData'), findsOneWidget);
streamedValue.value = Text('testwidget');
await tester.pumpAndSettle();
expect(find.text('testwidget'), findsOneWidget);
streamedValue.dispose();
});
//
// ValueBuilder
//
testWidgets('ValueBuilder widget', (WidgetTester tester) async {
final streamedValue = StreamedValue<String>(initialData: 'initialData');
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: ValueBuilder<String>(
streamed: streamedValue,
builder: (context, snapshot) {
return Text(snapshot.data);
}),
),
));
await tester.pump();
expect(find.text('initialData'), findsOneWidget);
streamedValue.value = 'ValueBuilder';
await tester.pumpAndSettle();
expect(find.text('ValueBuilder'), findsOneWidget);
streamedValue.value = 'Text changed';
await tester.pumpAndSettle();
expect(find.text('Text changed'), findsOneWidget);
});
}
| 0
|
mirrored_repositories/frideos_flutter
|
mirrored_repositories/frideos_flutter/test/receiver_widget_test.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:frideos/frideos.dart';
void main() {
testWidgets('StreamedWidget NoDataChild', (WidgetTester tester) async {
final streamedValue = StreamedValue<Widget>();
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: ReceiverWidget(
stream: streamedValue.outStream,
),
),
));
expect(find.text('testwidget'), findsNothing);
streamedValue.value = Text('testwidget');
await tester.pumpAndSettle();
expect(find.text('testwidget'), findsOneWidget);
streamedValue.dispose();
});
}
| 0
|
mirrored_repositories/frideos_flutter
|
mirrored_repositories/frideos_flutter/test/scrolling_text_test.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:frideos/frideos.dart';
void main() {
testWidgets('StreamedWidget NoDataChild', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: ScrollingText(
text: 'scrolling',
scrollingDuration: 1000,
)),
));
expect(find.text('scrolling'), findsNothing);
await tester.pump(new Duration(milliseconds: 1500));
expect(find.text('scrolling'), findsOneWidget);
});
}
| 0
|
mirrored_repositories/frideos_flutter
|
mirrored_repositories/frideos_flutter/test/appstate_provider_test.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:frideos/frideos.dart';
class Model {
Model({this.counter, this.text});
int counter;
String text;
}
class AppState extends AppStateModel {
AppState() {
print('-------APP STATE INIT--------');
}
final model = StreamedValue<Model>();
@override
void init() {
model.value = Model(counter: 33, text: 'Lorem ipsum');
}
@override
void dispose() {
model.dispose();
}
}
class App extends StatelessWidget {
final AppState appState;
App({@required this.appState});
@override
Widget build(BuildContext context) {
return AppStateProvider<AppState>(
appState: appState,
child: MaterialPage(),
);
}
}
class MaterialPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final model = AppStateProvider.of<AppState>(context).model;
return ValueBuilder<Model>(
streamed: model,
builder: (context, snapshot) {
return MaterialApp(
home: Container(
child: Column(
children: <Widget>[
Text(snapshot.data.text),
Text(snapshot.data.counter.toString()),
],
),
),
);
});
}
}
void main() {
testWidgets('AppStateProvider', (WidgetTester tester) async {
final appState = AppState();
await tester.pumpWidget(App(
appState: appState,
));
await tester.pump();
expect(find.text('Lorem ipsum'), findsOneWidget);
expect(find.text('33'), findsOneWidget);
});
}
| 0
|
mirrored_repositories/frideos_flutter/test
|
mirrored_repositories/frideos_flutter/test/core/streamed_value_test.dart
|
import 'dart:async';
import 'package:test/test.dart';
import 'package:frideos/frideos.dart';
void main() {
group('StreamedObjects', () {
//
// StreamedValue test
//
test('StreamedValue', () async {
final streamedValue = StreamedValue<int>();
Timer.run(() {
streamedValue.value = 1;
streamedValue.value = 2;
streamedValue.value = 8;
});
expect(
streamedValue.outStream,
emitsInOrder(<int>[1, 2, 8]),
);
});
test('StreamedValue initialData', () async {
final streamedValue = StreamedValue<int>(initialData: 99);
Timer.run(() {
streamedValue.value = 2;
streamedValue.value = 8;
});
expect(
streamedValue.outStream,
emitsInOrder(<int>[99, 2, 8]),
);
});
test('onChange', () {
final streamedValue = StreamedValue<int>();
streamedValue.value = 123;
streamedValue.onChange((value) {
expect(value, 123);
});
});
//
// StreamedTransformed test
//
test('StreamedTransformed', () {
final streamedTransformed = StreamedTransformed<String, int>();
final validateKey =
StreamTransformer<String, int>.fromHandlers(handleData: (key, sink) {
final k = int.tryParse(key);
if (k != null) {
sink.add(k);
} else {
sink.addError('The key must be an integer.');
}
});
streamedTransformed.setTransformer(validateKey);
streamedTransformed.inStream('157');
streamedTransformed.outTransformed.listen((value) {
expect(value, 157);
});
streamedTransformed.onChange((value) {
expect(value, '157');
});
});
test('StreamedTransformed initialValue', () {
final streamedTransformed =
StreamedTransformed<String, int>(initialData: '159');
final validateKey =
StreamTransformer<String, int>.fromHandlers(handleData: (key, sink) {
final k = int.tryParse(key);
if (k != null) {
sink.add(k);
} else {
sink.addError('The key must be an integer.');
}
});
streamedTransformed.setTransformer(validateKey);
streamedTransformed.outTransformed.listen((value) {
expect(value, 159);
});
streamedTransformed.onChange((value) {
expect(value, '159');
});
});
//
// MemoryValue test
//
test('MemoryValue', () async {
final memoryValue = MemoryValue<int>();
Timer.run(() {
memoryValue.value = 111;
memoryValue.value = 121;
});
expect(memoryValue.outStream, emitsInOrder([111, 121]));
memoryValue.outStream.listen((memory) {
print(memory);
if (memory == 121) {
expect(memoryValue.oldValue, 111);
}
});
});
//
// HistoryObject test
//
test('HistoryObject', () {
final historyObject = HistoryObject<String>();
Timer.run(() {
historyObject.value = 'Frideos';
historyObject.saveValue();
historyObject.value = 'Dart';
historyObject.saveValue();
historyObject.value = 'Flutter';
historyObject.saveValue();
expect(historyObject.history.length, 3);
});
expect(
historyObject.outStream,
emitsInOrder(['Frideos', 'Dart', 'Flutter']),
);
});
//
// TimerObject test
//
test('TimerObject', () {
final timerObject = TimerObject();
int counter = 0;
void incrementCounter(Timer t) {
counter += 1;
if (counter == 10) {
timerObject.stopTimer();
}
}
timerObject.startPeriodic(Duration(milliseconds: 10), incrementCounter);
void checkCounter() {
expect(counter, 10);
timerObject.dispose();
}
Timer(Duration(milliseconds: 1000), expectAsync0(checkCounter));
});
});
}
| 0
|
mirrored_repositories/frideos_flutter/test
|
mirrored_repositories/frideos_flutter/test/core/tunnel_pattern_test.dart
|
import 'package:test/test.dart';
import 'package:frideos/frideos.dart';
class BlocsHolder {
BlocsHolder() {
blocA.streamedSender.setReceiver(blocB.streamedValue);
blocA.listSender.setReceiver(blocB.streamedList);
blocA.mapSender.setReceiver(blocB.streamedMap);
}
final blocA = BlocA();
final blocB = BlocB();
void dispose() {
blocB.dispose();
}
}
class BlocA {
final streamedSender = StreamedSender<String>();
final listSender = ListSender<String>();
final mapSender = MapSender<int, String>();
}
class BlocB {
final streamedValue = StreamedValue<String>();
final streamedList = StreamedList<String>();
final streamedMap = StreamedMap<int, String>();
void dispose() {
streamedValue.dispose();
streamedList.dispose();
streamedMap.dispose();
}
}
void main() {
group('Tunnel Pattern', () {
test('streamedSender', () async {
final bloc = BlocsHolder();
bloc.blocA.streamedSender.send('SENDING FROM BLOCA TO BLOCB');
await expectLater(bloc.blocB.streamedValue.outStream,
emits('SENDING FROM BLOCA TO BLOCB'));
});
test('listSender', () async {
final bloc = BlocsHolder();
bloc.blocA.listSender.send(['a', 'b', 'c']);
await expectLater(
bloc.blocB.streamedList.outStream, emits(['a', 'b', 'c']));
});
test('mapSender', () async {
final bloc = BlocsHolder();
bloc.blocA.mapSender.send({1: 'a', 2: 'b', 3: 'c'});
await expectLater(
bloc.blocB.streamedMap.outStream, emits({1: 'a', 2: 'b', 3: 'c'}));
});
});
}
| 0
|
mirrored_repositories/frideos_flutter/test
|
mirrored_repositories/frideos_flutter/test/core/streamed_map_test.dart
|
import 'package:test/test.dart';
import 'package:frideos/frideos.dart';
void main() {
group('StreamedMap', () {
test('addKey', () async {
final streamedMap = StreamedMap<int, String>();
streamedMap.value = {};
streamedMap..addKey(1, 'first')..addKey(2, 'second')..addKey(3, 'third');
await expectLater(
streamedMap.outStream,
emits({1: 'first', 2: 'second', 3: 'third'}),
);
});
test('addKey with initialData', () async {
final streamedMap =
StreamedMap<int, String>(initialData: {33: '33', 66: '66'});
streamedMap..addKey(1, 'first')..addKey(2, 'second')..addKey(3, 'third');
await expectLater(
streamedMap.outStream,
emits({33: '33', 66: '66', 1: 'first', 2: 'second', 3: 'third'}),
);
});
test('Clear, removeKey, length', () {
final streamedMap = StreamedMap<int, String>();
streamedMap.value = {};
streamedMap.addKey(1, 'first');
expect(streamedMap.value[1], 'first');
streamedMap.addKey(1, 'first');
expect(streamedMap.removeKey(1), 'first');
streamedMap.addKey(1, 'first');
streamedMap.addKey(2, 'second');
expect(streamedMap.length, 2);
streamedMap.clear();
expect(streamedMap.length, 0);
expect(streamedMap.value.length, 0);
streamedMap.dispose();
});
test('onChange', () {
final streamedMap = StreamedMap<int, String>();
streamedMap.value = {1: 'a', 3: 'b', 5: 'c'};
streamedMap.onChange((map) {
expect(map, {1: 'a', 3: 'b', 5: 'c'});
});
});
});
}
| 0
|
mirrored_repositories/frideos_flutter/test
|
mirrored_repositories/frideos_flutter/test/core/streamed_list_test.dart
|
import 'package:test/test.dart';
import 'package:frideos/frideos.dart';
void main() {
group('StreamedList', () {
test('addElement', () async {
final streamedList = StreamedList<int>();
streamedList.value = [1, 3, 5];
streamedList..addElement(2)..addElement(4);
await expectLater(
streamedList.outStream,
emits([1, 3, 5, 2, 4]),
);
});
test('addElement with initialData', () async {
final streamedList = StreamedList<int>(initialData: [33, 66, 99]);
await expectLater(
streamedList.outStream,
emits([33, 66, 99]),
);
streamedList..addElement(2)..addElement(4);
await expectLater(
streamedList.outStream,
emits([33, 66, 99, 2, 4]),
);
});
test('addAll', () async {
final streamedList = StreamedList<int>();
streamedList.value = [];
streamedList.addAll([1, 2, 3, 4, 5]);
await expectLater(
streamedList.outStream,
emits([1, 2, 3, 4, 5]),
);
});
test('Clear, removeAt, removeElement length', () {
final streamedList = StreamedList<int>();
streamedList.value = [];
streamedList.addElement(99);
expect(streamedList.value.first, 99);
expect(streamedList.value.remove(99), true);
expect(streamedList.value.remove(99), false);
streamedList
..addElement(99)
..removeAt(0);
expect(streamedList.value.length, 0);
streamedList
..addElement(99)
..clear();
expect(streamedList.length, 0);
expect(streamedList.value.length, 0);
streamedList
..addElement(99)
..removeElement(99);
expect(streamedList.value.length, 0);
});
test('Replace, replaceAt', () {
final streamedList = StreamedList<int>(initialData: [1, 3, 45, 78, 87]);
streamedList.replace(3, 4);
expect(streamedList.value.where((e) => e == 5), isNotNull);
streamedList.replaceAt(0, 2);
expect(streamedList.value.first, 2);
});
test('onChange', () {
final streamedList = StreamedList<int>();
streamedList.value = [1, 3, 5];
streamedList.onChange((list) {
expect(list, [1, 3, 5]);
});
});
});
}
| 0
|
mirrored_repositories/frideos_flutter/example
|
mirrored_repositories/frideos_flutter/example/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:frideos/frideos.dart';
void main() => runApp(MyApp());
class AppState extends AppStateModel {
factory AppState() => _singletonAppState;
AppState._internal();
static final AppState _singletonAppState = AppState._internal();
// STREAM
final counter = StreamedValue<int>();
void incrementCounter() {
counter.value++;
}
@override
void init() {
counter.value = 0;
}
@override
void dispose() {
counter.dispose();
}
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
AppState appState;
@override
void initState() {
super.initState();
appState = AppState();
}
@override
void dispose() {
appState.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AppStateProvider<AppState>(
appState: appState,
child: MaterialApp(
title: 'Counter',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final appState = AppStateProvider.of<AppState>(context);
return Scaffold(
appBar: AppBar(
title: const Text('Main page'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('Counter:'),
Container(width: 30),
ValueBuilder<int>(
streamed: appState.counter,
builder: (context, snapshot) => Text('${snapshot.data}'),
noDataChild: const Text('null'),
),
],
),
Container(height: 30),
RaisedButton(
child: const Text('Second page'),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => SecondPage()));
}),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: appState.incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
class SecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final appState = AppStateProvider.of<AppState>(context);
return Scaffold(
appBar: AppBar(
title: const Text('Other page'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('Counter:'),
Container(width: 30),
ValueBuilder<int>(
streamed: appState.counter,
builder: (context, snapshot) => Text('${snapshot.data}'),
noDataChild: const Text('null'),
),
],
),
Container(height: 30),
RaisedButton(
child: const Text('Other page'),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => SecondPage()));
}),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: appState.incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
| 0
|
mirrored_repositories/firebase_cloud_messaging_flutter
|
mirrored_repositories/firebase_cloud_messaging_flutter/lib/main.dart
|
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
print('Handling a background message ${message.messageId}');
}
const AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
'This channel is used for important notifications.', // description
importance: Importance.high,
);
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter FCM Demo',
home: MyHomePage(),
debugShowCheckedModeBanner: false,
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
void initState() {
super.initState();
var initialzationSettingsAndroid =
AndroidInitializationSettings('@mipmap/ic_launcher');
// var initializationSettings =
InitializationSettings(android: initialzationSettingsAndroid);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
RemoteNotification notification = message.notification;
AndroidNotification android = message.notification?.android;
if (notification != null && android != null) {
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
NotificationDetails(
android: AndroidNotificationDetails(
channel.id, channel.name, channel.description,
icon: '@mipmap/ic_launcher')),
);
}
});
getToken();
}
// Get Token of the Current User;
getToken() async {
String token = await FirebaseMessaging.instance.getToken();
print('Token: $token');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'FCM',
style: TextStyle(color: Colors.white, fontSize: 21.0),
),
elevation: 8.0,
backgroundColor: Colors.blue,
centerTitle: true,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Firebase Clouding Messaging!',
style: TextStyle(color: Colors.purple[200], fontSize: 22.0),
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/firebase_cloud_messaging_flutter
|
mirrored_repositories/firebase_cloud_messaging_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:fcm/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/CoinTossApp-In-Flutter
|
mirrored_repositories/CoinTossApp-In-Flutter/lib/style_text.dart
|
import 'package:flutter/material.dart';
class StyleText extends StatelessWidget {
const StyleText({super.key, required this.text});
final String text;
@override
Widget build(context) {
return Text(
text,
style: const TextStyle(
fontSize: 28,
color: Colors.white,
),
);
}
}
| 0
|
mirrored_repositories/CoinTossApp-In-Flutter
|
mirrored_repositories/CoinTossApp-In-Flutter/lib/coin_toss.dart
|
import 'package:flutter/material.dart';
import 'package:coin_toss_app/style_text.dart';
import 'dart:math';
final random = Random();
class CoinToss extends StatefulWidget {
const CoinToss({super.key});
@override
State<CoinToss> createState() {
return _CoinToss();
}
}
class _CoinToss extends State<CoinToss> {
var activeImage = 'assets/error.png';
var activeText = 'You Got Error !!';
void onPressed() {
var toss = random.nextInt(2) + 1;
if (toss == 1) {
setState(() {
activeText = 'You Got Head';
activeImage = 'assets/head.png';
});
} else if (toss == 2) {
setState(() {
activeText = 'You Got Tails';
activeImage = 'assets/tail.png';
});
}
}
@override
Widget build(context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Image.asset(
activeImage,
width: 200,
),
const SizedBox(
height: 20,
),
OutlinedButton(
onPressed: onPressed,
style: OutlinedButton.styleFrom(
foregroundColor: Colors.white,
),
child: const StyleText(
text: 'Toss !!',
),
),
const SizedBox(
height: 50,
),
StyleText(
text: activeText,
),
],
);
}
}
| 0
|
mirrored_repositories/CoinTossApp-In-Flutter
|
mirrored_repositories/CoinTossApp-In-Flutter/lib/gradient_contrast.dart
|
import 'package:flutter/material.dart';
import 'package:coin_toss_app/coin_toss.dart';
class GradientContrast extends StatelessWidget {
const GradientContrast({super.key});
@override
Widget build(context) {
return Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
Color.fromARGB(249, 31, 30, 30),
Color.fromARGB(216, 95, 91, 91)
],
begin: Alignment.topLeft,
end: Alignment.bottomLeft,
),
),
child: const Center(
child: CoinToss(),
),
);
}
}
| 0
|
mirrored_repositories/CoinTossApp-In-Flutter
|
mirrored_repositories/CoinTossApp-In-Flutter/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:coin_toss_app/gradient_contrast.dart';
void main() {
runApp(
const MaterialApp(
home: Scaffold(
body: GradientContrast(),
),
),
);
}
| 0
|
mirrored_repositories/flutter_days_app
|
mirrored_repositories/flutter_days_app/lib/main_windows.dart
|
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_days_app/windows/nav.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
Future<void> main() async {
await initHiveForFlutter();
final HttpLink httpLink =
HttpLink('https://cafe-javas-flutter-app.herokuapp.com/v1/graphql');
ValueNotifier<GraphQLClient> client = ValueNotifier(
GraphQLClient(
link: httpLink,
cache: GraphQLCache(
store: HiveStore(),
),
),
);
runApp(MyApp(
graphQLClient: client,
));
}
class MyApp extends StatelessWidget {
final ValueNotifier<GraphQLClient> graphQLClient;
const MyApp({required this.graphQLClient, Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return GraphQLProvider(
client: graphQLClient,
child: FluentApp(
title: 'Flutter CJs App',
themeMode: ThemeMode.system,
debugShowCheckedModeBanner: false,
theme: FluentThemeData(
// accentColor: AccentColor('4289180570', const {
// '50': Color(0xfff2f4f0),
// '100': Color(0xffe6e9e2),
// '200': Color(0xffccd3c5),
// '300': Color(0xffb3bda8),
// '400': Color(0xff9aa78b),
// '500': Color(0xff80926d),
// '600': Color(0xff677458),
// '700': Color(0xff4d5742),
// '800': Color(0xff333a2c),
// '900': Color(0xff1a1d16)
// }),
accentColor: const Color(0xff044064).toAccentColor(),
fontFamily: 'Segoe',
visualDensity: VisualDensity.adaptivePlatformDensity,
//typography: Typography.material2018(),
scaffoldBackgroundColor: const Color(0xfffafafa),
micaBackgroundColor: const Color(0xffa7b39a),
acrylicBackgroundColor: const Color(0xffccd3c5),
iconTheme: const IconThemeData(
color: Color(0xff044064),
)),
home: const WindowsNav(),
),
);
}
}
| 0
|
mirrored_repositories/flutter_days_app
|
mirrored_repositories/flutter_days_app/lib/main.dart
|
import 'package:flutter/material.dart' show ThemeMode, Brightness;
import 'package:flutter/widgets.dart';
import 'package:flutter_days_app/macintosh/nav.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:macos_ui/macos_ui.dart';
Future<void> main() async {
// Cache the data from the graphql endpoint.
await initHiveForFlutter();
final HttpLink httpLink = HttpLink(
'https://cafe-javas-flutter-app.herokuapp.com/v1/graphql',
);
ValueNotifier<GraphQLClient> client = ValueNotifier(
GraphQLClient(
link: httpLink,
cache: GraphQLCache(
store: HiveStore(),
),
),
);
runApp(MyApp(graphQLClient: client));
}
class MyApp extends StatelessWidget {
const MyApp({required this.graphQLClient, Key? key}) : super(key: key);
final ValueNotifier<GraphQLClient> graphQLClient;
@override
Widget build(BuildContext context) {
return GraphQLProvider(
client: graphQLClient,
child: MacosApp(
title: 'Flutter CJs App',
debugShowCheckedModeBanner: false,
theme: MacosThemeData(
primaryColor: const Color(0xffa7b39a),
brightness: Brightness.light,
canvasColor: const Color(0xfffafafa),
iconTheme: const MacosIconThemeData(
color: Color(0xff044064),
)),
darkTheme: MacosThemeData(
brightness: Brightness.dark,
primaryColor: const Color(0xff044064),
iconTheme: const MacosIconThemeData(
color: Color(0xffa7b39a),
),
typography: MacosTypography.white,
),
themeMode: ThemeMode.system,
home: const MacintoshNav(),
),
);
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib
|
mirrored_repositories/flutter_days_app/lib/windows/nav.dart
|
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_days_app/windows/pages/cart_page.dart';
import 'package:flutter_days_app/windows/pages/favourite_page.dart';
import 'package:flutter_days_app/windows/pages/locations_page.dart';
import 'package:flutter_days_app/windows/pages/menu_page.dart';
import 'package:flutter_days_app/windows/pages/settings_page.dart';
class WindowsNav extends StatefulWidget {
const WindowsNav({Key? key}) : super(key: key);
@override
State<WindowsNav> createState() => _WindowsNavState();
}
class _WindowsNavState extends State<WindowsNav> {
final List<Widget> _pages = const [
MenuPage(),
LocationsPage(),
FavouritePage(),
CartPage(),
SettingsPage(),
AbsorbPointer(),
AbsorbPointer()
];
int pageIndex = 0;
@override
Widget build(BuildContext context) {
return NavigationView(
appBar: NavigationAppBar(
leading: Image.asset(
'assets/cjs_logo.png',
width: 40,
height: 40,
color: const Color(0xff044064),
),
title: const Text('Flutter CJs App'),
automaticallyImplyLeading: false),
pane: NavigationPane(
selected: pageIndex,
onChanged: (changed) => setState(() => pageIndex = changed),
size: const NavigationPaneSize(
openMinWidth: 250,
openMaxWidth: 350,
),
displayMode: PaneDisplayMode.compact,
items: [
PaneItem(
icon: const Icon(FluentIcons.context_menu),
title: const Text('Menu'),
body: _pages[0],
),
PaneItem(
icon: const Icon(FluentIcons.map_pin),
title: const Text('Locations'),
body: _pages[1],
),
PaneItem(
icon: const Icon(FluentIcons.favorite_star),
title: const Text('Favorites'),
body: _pages[2],
),
PaneItem(
icon: const Icon(FluentIcons.shopping_cart),
title: const Text('Cart'),
infoBadge: const InfoBadge(source: Text('4')),
body: _pages[3]),
PaneItem(
icon: const Icon(FluentIcons.settings),
title: const Text('Settings'),
body: _pages[4],
),
],
footerItems: [
PaneItemSeparator(),
PaneItem(
icon: const Icon(FluentIcons.help),
title: const Text('Help'),
body: _pages[5],
),
PaneItem(
icon: const Icon(FluentIcons.user_window),
title: const Text('Javas User'),
body: _pages[6],
),
],
),
// content: NavigationBody(
// index: pageIndex,
// children: ,
// transitionBuilder: (child, animation) {
// return EntrancePageTransition(child: child, animation: animation);
// },
// ),
);
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/windows
|
mirrored_repositories/flutter_days_app/lib/windows/pages/locations_page.dart
|
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_days_app/graph_objects/graph_queries.dart';
import 'package:flutter_days_app/widgets/app_card.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
class LocationsPage extends StatelessWidget {
const LocationsPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return ScaffoldPage(
header: const PageHeader(
title: Text('Locations'),
),
content: Query(
options: QueryOptions(document: gql(getCafeLocations)),
builder: (QueryResult? result,
{VoidCallback? refetch, FetchMore? fetchMore}) {
//? If the query is loading, show a loading indicator.
if (result!.isLoading) {
return const Center(
child: ProgressRing(),
);
}
//? If the query returns no data, show an empty state
if (result.data == null) {
return Center(
child: Column(
children: [
const Icon(FluentIcons.location, size: 60),
const SizedBox(height: 20),
Text(
'No locations available',
style: FluentTheme.of(context).typography.subtitle,
),
],
),
);
}
//? If the query is not loading, but has an error, show the error
if (result.exception != null) {
return InfoBar(
title: const Text('Error'),
content: Text(result.exception.toString()),
severity: InfoBarSeverity.error,
);
}
//? Assign the resulting data to a List variable
List? locations = result.data!['Cafe_Locations'];
//? Create a GridView.builder widget to display the data
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisExtent: 300,
mainAxisSpacing: 50,
crossAxisSpacing: 20),
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
itemCount: locations == null ? 0 : locations.length,
itemBuilder: (BuildContext context, int index) {
final location = locations![index];
return AppCard(
cardImage: location['location_image'],
cardTitle: location['location_name'],
enableLocationIcon: true,
cardSubtitle: location['location_contact1'],
cardSubtitle2: location['location_contact2'],
);
},
);
},
),
);
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/windows
|
mirrored_repositories/flutter_days_app/lib/windows/pages/favourite_page.dart
|
import 'package:fluent_ui/fluent_ui.dart';
class FavouritePage extends StatelessWidget {
const FavouritePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return ScaffoldPage(
header: const PageHeader(
title: Text('Favourites'),
),
content: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Icon(FluentIcons.add_favorite, size: 60),
const SizedBox(height: 20),
Text(
'Favourite you meals and have them show up here',
style: FluentTheme.of(context).typography.subtitle,
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/windows
|
mirrored_repositories/flutter_days_app/lib/windows/pages/cart_page.dart
|
import 'package:fluent_ui/fluent_ui.dart';
class CartPage extends StatelessWidget {
const CartPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return ScaffoldPage(
header: const PageHeader(
title: Text('Cart'),
),
content: SingleChildScrollView(
child: ConstrainedBox(
constraints:
BoxConstraints(maxHeight: MediaQuery.of(context).size.height),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const CartListTile(
cartMain: 'CJ’S House Breakfast',
cartExtras: '1 x Extra Sausage, 1 x Egg, 1 x Bacon',
cartPrice: 'Ugx. 25,000',
),
const SizedBox(height: 20),
const CartListTile(
cartMain: 'Fish Fingers & Chips',
cartExtras: '',
cartPrice: 'Ugx. 34,500',
),
const SizedBox(height: 20),
const CartListTile(
cartMain: 'Passion Fruit Nojito',
cartExtras: '',
cartPrice: 'Ugx. 16,500',
quantity: '2',
),
const SizedBox(height: 20),
const CartListTile(
cartMain: 'Mint Scoop Ice Cream',
cartExtras: '',
cartPrice: 'Ugx. 7,000',
quantity: '1',
),
const SizedBox(height: 20),
const Divider(),
const SizedBox(height: 10),
Row(mainAxisAlignment: MainAxisAlignment.end, children: [
Text('Subtotal: UGX 99,500',
style: FluentTheme.of(context).typography.body),
]),
const SizedBox(height: 10),
Row(mainAxisAlignment: MainAxisAlignment.end, children: [
Text('VAT: 18%',
style: FluentTheme.of(context).typography.bodyStrong),
]),
const SizedBox(height: 10),
Row(mainAxisAlignment: MainAxisAlignment.end, children: [
Text('Total: UGX 117,400',
style: FluentTheme.of(context).typography.bodyLarge),
]),
const Spacer(),
const Divider(),
const SizedBox(height: 10),
Align(
alignment: Alignment.bottomCenter,
child: Center(
child: SizedBox(
width: 200,
child: FilledButton(
child: const Text('Checkout'),
onPressed: () {},
),
)),
)
],
),
),
),
),
);
}
}
class CartListTile extends StatelessWidget {
const CartListTile({
required this.cartMain,
required this.cartExtras,
required this.cartPrice,
this.quantity = '1',
Key? key,
}) : super(key: key);
final String cartMain;
final String cartExtras;
final String cartPrice;
final String? quantity;
@override
Widget build(BuildContext context) {
return Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: Image.asset(
'assets/cjs_logo.png',
fit: BoxFit.cover,
width: 40,
height: 40,
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(cartMain,
style: FluentTheme.of(context).typography.bodyLarge),
const Spacer(),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
icon: const Icon(FluentIcons.calculator_addition),
onPressed: () {}),
Text(quantity!),
IconButton(
icon: const Icon(FluentIcons.calculator_subtract),
onPressed: () {}),
],
),
],
),
Text(
cartExtras,
style: FluentTheme.of(context).typography.caption,
),
Text(cartPrice,
textAlign: TextAlign.justify,
style: FluentTheme.of(context).typography.bodyStrong),
],
),
),
),
],
);
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/windows
|
mirrored_repositories/flutter_days_app/lib/windows/pages/menu_page.dart
|
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_days_app/windows/pages/menu/breakfast_menu.dart';
import 'package:flutter_days_app/windows/pages/menu/dessert_menu.dart';
import 'package:flutter_days_app/windows/pages/menu/drinks_menu.dart';
import 'package:flutter_days_app/windows/pages/menu/meals_menu.dart';
class MenuPage extends StatefulWidget {
const MenuPage({Key? key}) : super(key: key);
@override
State<MenuPage> createState() => _MenuPageState();
}
class _MenuPageState extends State<MenuPage>
with AutomaticKeepAliveClientMixin<MenuPage> {
int currentTab = 0;
final List<Widget> _pages = const [
BreakfastMenu(),
MealsMenu(),
DrinksMenu(),
DessertMenu(),
];
@override
Widget build(BuildContext context) {
super.build(context);
return ScaffoldPage(
header: const PageHeader(
title: Text('Menu'),
),
content: SizedBox(
height: 100,
child: TabView(
currentIndex: currentTab,
onChanged: (index) => setState(() => currentTab = index),
tabs: [
Tab(
text: const Text('Breakfast Menu'),
icon: const Icon(FluentIcons.breakfast),
body: _pages[0],
closeIcon: null),
Tab(
text: const Text('Main Meals'),
icon: const Icon(FluentIcons.brunch),
body: _pages[1],
closeIcon: null),
Tab(
text: const Text('Drinks Menu'),
icon: const Icon(FluentIcons.beer_mug),
body: _pages[2],
closeIcon: null),
Tab(
text: const Text('Dessert Menu'),
icon: const Icon(FluentIcons.cake),
body: _pages[3],
closeIcon: null,
),
],
),
),
);
}
@override
bool get wantKeepAlive => true;
}
| 0
|
mirrored_repositories/flutter_days_app/lib/windows
|
mirrored_repositories/flutter_days_app/lib/windows/pages/settings_page.dart
|
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_days_app/windows/pages/settings/feedback.dart';
import 'package:flutter_days_app/windows/pages/settings/license.dart';
class SettingsPage extends StatelessWidget {
const SettingsPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return ScaffoldPage(
header: const PageHeader(
title: Text('Settings'),
),
content: ListView(children: [
ListTile(
leading: const Icon(FluentIcons.phone),
title: const Text('Call Us'),
subtitle: const Text('+25630000909'),
trailing: const Icon(FluentIcons.chevron_right),
onPressed: () {
showDialog(
context: context,
builder: (_) => ContentDialog(
title: const Text('Call Us'),
content: const Text(
'Unfortunately you are not able to call us at this time.'),
actions: [
FilledButton(
child: const Text('Close'),
onPressed: () =>
Navigator.of(context, rootNavigator: true).pop(),
),
],
));
},
),
const SizedBox(height: 10),
const ListTile(
leading: Icon(FluentIcons.mail),
title: Text('Email Us'),
subtitle: Text('info@cafejavas.co.ug'),
),
const SizedBox(height: 10),
const ListTile(
leading: Icon(FluentIcons.clipboard_list),
title: Text('Terms and Conditions'),
),
const SizedBox(height: 10),
const ListTile(
leading: Icon(FluentIcons.lock),
title: Text('Privacy Policy'),
),
const SizedBox(height: 10),
ListTile(
leading: const Icon(FluentIcons.feedback),
title: const Text('Share your Feedback'),
onPressed: () => Navigator.of(context).push(PageRouteBuilder(
pageBuilder: (_, __, ___) => const FeedbackPage(),
transitionDuration: const Duration(milliseconds: 300),
transitionsBuilder:
(_, Animation<double> animation, __, Widget child) {
return DrillInPageTransition(
animation: animation,
child: child,
);
},
)),
),
const SizedBox(height: 10),
ListTile(
leading: const Icon(FluentIcons.info),
title: const Text('Licenses'),
onPressed: () => Navigator.of(context).push(PageRouteBuilder(
pageBuilder: (_, __, ___) => const LicensePage(),
transitionDuration: const Duration(milliseconds: 300),
transitionsBuilder:
(_, Animation<double> animation, __, Widget child) {
return DrillInPageTransition(
animation: animation,
child: child,
);
},
)),
),
]),
);
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/windows/pages
|
mirrored_repositories/flutter_days_app/lib/windows/pages/menu/menu_details.dart
|
import 'dart:math';
import 'package:cached_network_image_builder/cached_network_image_builder.dart';
import 'package:fluent_ui/fluent_ui.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
class MenuDetails extends StatelessWidget {
MenuDetails({
required this.menuID,
required this.detailQuery,
required this.resultKey,
Key? key,
}) : super(key: key);
final int menuID;
final String detailQuery;
final String resultKey;
final _controller = ScrollController();
@override
Widget build(BuildContext context) {
return Query(
options: QueryOptions(
document: gql(detailQuery), variables: {"menuID": menuID}),
builder: (QueryResult result,
{VoidCallback? refetch, FetchMore? fetchMore}) {
if (result.isLoading) {
return const Center(
child: ProgressRing(),
);
}
if (result.exception != null) {
return InfoBar(
title: const Text('Error'),
content: Text(result.exception.toString()),
severity: InfoBarSeverity.error,
);
}
var detail = result.data![resultKey];
return ScaffoldPage(
header: PageHeader(
leading: IconButton(
icon: const Icon(FluentIcons.back),
iconButtonMode: IconButtonMode.large,
onPressed: () => Navigator.of(context).pop()),
title: Text(detail['name']),
commandBar: CommandBar(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.end,
overflowBehavior: CommandBarOverflowBehavior.noWrap,
//compactBreakpointWidth: 700,
primaryItems: [
CommandBarButton(
icon: const Icon(FluentIcons.favorite_star),
label: const Text('Favourite'),
onPressed: () {}),
CommandBarButton(
icon: const Icon(FluentIcons.share),
label: const Text('Share'),
onPressed: () {},
),
CommandBarButton(
icon: const Icon(FluentIcons.shopping_cart),
label: const Text('Add to Cart'),
onPressed: () {},
)
],
),
),
//padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 50),
content: Scrollbar(
controller: _controller,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
controller: _controller,
padding:
const EdgeInsets.symmetric(horizontal: 60, vertical: 20),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
//const SizedBox(width: 50),
SizedBox(
height: 300,
width: 450,
child: CachedNetworkImageBuilder(
url: detail['image'],
builder: (image) => DecoratedBox(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
image: DecorationImage(
image: FileImage(image), fit: BoxFit.cover),
),
),
placeHolder: Image.asset('assets/cjs_logo.png'),
errorWidget: Image.asset('assets/cjs_logo.png'),
imageExtensions: const ['jpg', 'png', 'jpeg'],
),
),
const SizedBox(width: 50),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text('Description',
style:
FluentTheme.of(context).typography.subtitle),
const SizedBox(height: 20),
Row(
children: [
RatingBar(
rating: double.parse(
Random().nextInt(5).toString())),
const SizedBox(width: 10),
Text('(${Random().nextInt(1000).toString()})'),
],
),
const SizedBox(height: 20),
SizedBox(
width: 400,
child: Text(detail['description'],
style: FluentTheme.of(context).typography.body),
),
const SizedBox(height: 20),
Text('UGX${detail['price']}',
style:
FluentTheme.of(context).typography.bodyStrong)
])
],
),
),
),
);
});
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/windows/pages
|
mirrored_repositories/flutter_days_app/lib/windows/pages/menu/drinks_menu.dart
|
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_days_app/widgets/app_card.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import '../../../graph_objects/graph_queries.dart';
class DrinksMenu extends StatelessWidget {
const DrinksMenu({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return ScaffoldPage(
content: Query(
options: QueryOptions(document: gql(getDrinks)),
builder: (QueryResult result,
{VoidCallback? refetch, FetchMore? fetchMore}) {
if (result.isLoading) {
return const Center(
child: ProgressRing(),
);
}
if (result.data == null) {
return Center(
child: Column(
children: [
const Icon(FluentIcons.beer_mug, size: 60),
const SizedBox(height: 20),
Text(
'No drinks available',
style: FluentTheme.of(context).typography.subtitle,
),
],
),
);
}
if (result.exception != null) {
return InfoBar(
title: const Text('Error'),
content: Text(result.exception.toString()),
severity: InfoBarSeverity.error,
);
}
List<dynamic> drinksMenu = result.data!['Drinks'];
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisExtent: 300,
mainAxisSpacing: 50,
crossAxisSpacing: 20),
padding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 20,
),
itemCount: drinksMenu.length,
itemBuilder: (BuildContext context, int index) {
final drink = drinksMenu[index];
return AppCard(
cardImage: drink['image'],
cardTitle: drink['name'].toString(),
cardSubtitle: drink['price'],
);
},
);
},
),
);
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/windows/pages
|
mirrored_repositories/flutter_days_app/lib/windows/pages/menu/breakfast_menu.dart
|
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_days_app/widgets/app_card.dart';
import 'package:flutter_days_app/windows/pages/menu/menu_details.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import '../../../graph_objects/graph_queries.dart';
class BreakfastMenu extends StatelessWidget {
const BreakfastMenu({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return ScaffoldPage(
content: Query(
options: QueryOptions(document: gql(getBreakfastMenu)),
builder: (QueryResult result,
{VoidCallback? refetch, FetchMore? fetchMore}) {
if (result.isLoading) {
return const Center(
child: ProgressRing(),
);
}
if (result.data == null) {
return Center(
child: Column(
children: [
const Icon(FluentIcons.breakfast, size: 60),
const SizedBox(height: 20),
Text(
'No breakfast available',
style: FluentTheme.of(context).typography.subtitle,
),
],
),
);
}
if (result.exception != null) {
return InfoBar(
title: const Text('Error'),
content: Text(result.exception.toString()),
severity: InfoBarSeverity.error,
);
}
List<dynamic> breakMenu = result.data!['Breakfast'];
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisExtent: 300,
mainAxisSpacing: 50,
crossAxisSpacing: 20),
padding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 20,
),
itemCount: breakMenu.length,
itemBuilder: (BuildContext context, int index) {
final breakfast = breakMenu[index];
return GestureDetector(
child: AppCard(
cardImage: breakfast['image'],
cardTitle: breakfast['name'].toString(),
cardSubtitle: 'UGX${breakfast['price']}',
),
onTap: () {
Navigator.of(context).push(PageRouteBuilder(
pageBuilder: (_, __, ___) => MenuDetails(
menuID: breakfast['id'],
detailQuery: getBreakFastByID,
resultKey: 'Breakfast_by_pk',
),
transitionDuration: const Duration(milliseconds: 300),
transitionsBuilder:
(_, Animation<double> animation, __, Widget child) {
return DrillInPageTransition(
animation: animation,
child: child,
);
},
));
},
);
},
);
},
),
);
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/windows/pages
|
mirrored_repositories/flutter_days_app/lib/windows/pages/menu/meals_menu.dart
|
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_days_app/widgets/app_card.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import '../../../graph_objects/graph_queries.dart';
import 'menu_details.dart';
class MealsMenu extends StatelessWidget {
const MealsMenu({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return ScaffoldPage(
content: Query(
options: QueryOptions(document: gql(getMainMeals)),
builder: (QueryResult result,
{VoidCallback? refetch, FetchMore? fetchMore}) {
if (result.isLoading) {
return const Center(
child: ProgressRing(),
);
}
if (result.data == null) {
return Center(
child: Column(
children: [
const Icon(FluentIcons.brunch, size: 60),
const SizedBox(height: 20),
Text(
'No meals available',
style: FluentTheme.of(context).typography.subtitle,
),
],
),
);
}
if (result.exception != null) {
return InfoBar(
title: const Text('Error'),
content: Text(result.exception.toString()),
severity: InfoBarSeverity.error,
);
}
List<dynamic> mealsMenu = result.data!['Meals'];
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisExtent: 300,
mainAxisSpacing: 50,
crossAxisSpacing: 20),
padding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 20,
),
itemCount: mealsMenu.length,
itemBuilder: (BuildContext context, int index) {
final meal = mealsMenu[index];
return GestureDetector(
child: AppCard(
cardImage: meal['image'],
cardTitle: meal['name'].toString(),
cardSubtitle: 'UGX${meal['price']}',
),
onTap: () {
Navigator.of(context).push(PageRouteBuilder(
pageBuilder: (_, __, ___) => MenuDetails(
menuID: meal['id'],
detailQuery: getMealsByID,
resultKey: 'Meals_by_pk',
),
transitionDuration: const Duration(milliseconds: 300),
transitionsBuilder:
(_, Animation<double> animation, __, Widget child) {
return DrillInPageTransition(
animation: animation,
child: child,
);
},
));
},
);
},
);
},
),
);
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/windows/pages
|
mirrored_repositories/flutter_days_app/lib/windows/pages/menu/dessert_menu.dart
|
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_days_app/widgets/app_card.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import '../../../graph_objects/graph_queries.dart';
class DessertMenu extends StatelessWidget {
const DessertMenu({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return ScaffoldPage(
content: Query(
options: QueryOptions(document: gql(getDessertsMenu)),
builder: (QueryResult result,
{VoidCallback? refetch, FetchMore? fetchMore}) {
if (result.isLoading) {
return const Center(
child: ProgressRing(),
);
}
if (result.data == null) {
return Center(
child: Column(
children: [
const Icon(FluentIcons.cake, size: 60),
const SizedBox(height: 20),
Text(
'No desserts available',
style: FluentTheme.of(context).typography.subtitle,
),
],
),
);
}
if (result.exception != null) {
return InfoBar(
title: const Text('Error'),
content: Text(result.exception.toString()),
severity: InfoBarSeverity.error,
);
}
List<dynamic> dessertMenu = result.data!['Desserts'];
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisExtent: 300,
mainAxisSpacing: 50,
crossAxisSpacing: 20),
padding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 20,
),
itemCount: dessertMenu.length,
itemBuilder: (BuildContext context, int index) {
final dessert = dessertMenu[index];
return AppCard(
cardImage: dessert['image'],
cardTitle: dessert['name'].toString(),
cardSubtitle: 'UGX${dessert['price']}',
);
},
);
},
),
);
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/windows/pages
|
mirrored_repositories/flutter_days_app/lib/windows/pages/settings/license.dart
|
import 'package:fluent_ui/fluent_ui.dart' hide ListTile;
import 'package:flutter/foundation.dart';
class LicensePage extends StatelessWidget {
const LicensePage({Key? key}) : super(key: key);
Future<List<License>> loadLicenses() async =>
LicenseRegistry.licenses.asyncMap<License>((license) async {
final title = license.packages.join('\n');
final text = license.paragraphs
.map<String>((paragraph) => paragraph.text)
.join('\n\n');
return License(title, text);
}).toList();
@override
Widget build(BuildContext context) {
return ScaffoldPage(
header: PageHeader(
leading: IconButton(
icon: const Icon(FluentIcons.back),
onPressed: () => Navigator.of(context).pop()),
title: const Text('Licenses'),
),
content: FutureBuilder<List<License>>(
future: loadLicenses(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
final licenses = snapshot.data;
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return const Center(child: ProgressRing(value: null));
default:
if (snapshot.hasError) {
return Center(
child: Text('Error: ${snapshot.error}'),
);
} else {
return ListView.separated(
shrinkWrap: true,
padding:
const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
itemCount: licenses?.length ?? 0,
itemBuilder: (BuildContext context, int index) {
final license = licenses[index];
return Expander(
header: Text(
license.title ?? '',
style: FluentTheme.of(context).typography.bodyStrong,
),
content: Text(
license.text ?? '',
style: FluentTheme.of(context).typography.body,
));
},
separatorBuilder: (BuildContext context, int index) =>
const SizedBox(height: 30),
);
}
}
},
),
);
}
}
class License {
late String title;
late String text;
License(this.title, this.text);
License.fromJson(Map<String, dynamic> json) {
title = json['title'];
text = json['text'];
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/windows/pages
|
mirrored_repositories/flutter_days_app/lib/windows/pages/settings/feedback.dart
|
import 'package:fluent_ui/fluent_ui.dart';
class FeedbackPage extends StatelessWidget {
const FeedbackPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return ScaffoldPage(
header: PageHeader(
leading: IconButton(
icon: const Icon(FluentIcons.back),
onPressed: () => Navigator.of(context).pop()),
title: const Text('Feedback'),
),
content: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 100, vertical: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'''We’d love to hear your feedback; good or bad. If we didn't make you feel special, we'd like to make it up to you. Please let us know what happened during your visit and we'll get in touch with you soon.
\n\nThe information you provide us will be treated in the strictest confidence and may be used for improving our service delivery purposes. A copy of the completed form will be automatically sent to the email address supplied.''',
textAlign: TextAlign.justify,
),
const SizedBox(height: 20),
const TextBox(
//header: 'First Name',
placeholder: 'Enter your first name',
autofillHints: [AutofillHints.givenName],
),
const SizedBox(height: 20),
const TextBox(
//header: 'Last Name',
placeholder: 'Enter your last name',
autofillHints: [AutofillHints.familyName],
),
const SizedBox(height: 20),
InfoLabel(
label: 'Restaurant Location',
child: AutoSuggestBox(
items: <String>[
'Kira Road',
'Lugogo Mall',
'Jinja Road',
'Bombo Road',
'Oasis Mall',
'Victoria Mall',
'Cargen House'
].map((e) => AutoSuggestBoxItem(value: e, label: e)).toList(),
placeholder: 'Restaurant Location',
),
),
const SizedBox(height: 20),
SizedBox(
width: MediaQuery.of(context).size.width / 2,
child: DatePicker(
header: 'Date of Visit',
selected: DateTime.now(),
startYear: DateTime.now().year - 1,
endYear: DateTime.now().year,
),
),
const SizedBox(height: 20),
const TextBox(
//header: 'Feedback',
placeholder: 'Enter your feedback',
keyboardType: TextInputType.multiline,
maxLines: 4,
textInputAction: TextInputAction.newline,
),
const SizedBox(height: 20),
SizedBox(
width: 250,
child: FilledButton(child: const Text('Send'), onPressed: () {}),
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib
|
mirrored_repositories/flutter_days_app/lib/graph_objects/graph_queries.dart
|
const String getBreakfastMenu = """
query getBreakfastMenu {
Breakfast {
id
name
description
price
image
}
}
""";
const String getDrinks = """
query getDrinks {
Drinks {
id
name
description
price
image
}
}
""";
const String getLocationsList = """
query getLocationsList {
Cafe_Locations(order_by: {location_name: asc}) {
location_id
location_name
location_latitude
location_longitude
location_image
location_contact1
location_contact2
}
}""";
const String getCafeLocations = """
query getCafeLocations {
Cafe_Locations(order_by: {location_name: asc}) {
location_name
location_contact1
location_contact2
location_image
}
}
""";
const String getMainMeals = """
query getMainMeals {
Meals {
id
name
description
price
image
}
}
""";
const String getDessertsMenu = """
query myDesserts {
Desserts {
id
name
description
price
image
}
}
""";
const String getBreakFastByID = """
query getBreakByID(\$menuID: Int!) {
Breakfast_by_pk(id: \$menuID) {
id
name
description
image
price
}
}
""";
const String getMealsByID = """
query getMealByID(\$menuID: Int!) {
Meals_by_pk(id: \$menuID) {
id
image
name
price
description
}
}
""";
const String getDessertByID = """
query getDessertByID(\$menuID: Int!) {
Desserts_by_pk(id: \$menuID) {
id
image
name
price
description
}
}""";
const String getDrinksById = """
query getDrinksByID (\$menuID: Int!) {
Drinks_by_pk(id: \$menuID) {
id
image
name
price
description
}
}""";
| 0
|
mirrored_repositories/flutter_days_app/lib
|
mirrored_repositories/flutter_days_app/lib/widgets/app_card.dart
|
import 'dart:math' as math;
//import 'package:cached_network_image/cached_network_image.dart';
import 'package:cached_network_image_builder/cached_network_image_builder.dart';
import 'package:fluent_ui/fluent_ui.dart' hide Card, IconButton;
import 'package:flutter/cupertino.dart' show CupertinoIcons;
import 'package:flutter/material.dart' show Card, IconButton;
class AppCard extends StatelessWidget {
final String? cardImage, cardTitle, cardSubtitle, cardSubtitle2;
final bool? enableLocationIcon;
const AppCard(
{Key? key,
this.cardImage,
this.cardTitle,
this.cardSubtitle,
this.cardSubtitle2,
this.enableLocationIcon = false})
: super(key: key);
@override
Widget build(BuildContext context) {
return SizedBox(
height: 300,
width: double.infinity,
child: Card(
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
elevation: 3.0,
child: Stack(
children: <Widget>[
SizedBox(
height: 300,
width: double.infinity,
child: ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
),
child: CachedNetworkImageBuilder(
url: cardImage!,
builder: (image) => FittedBox(
fit: BoxFit.cover,
child: Image.file(image),
),
placeHolder: Image.asset('assets/cjs_logo.png'),
errorWidget: Image.asset('assets/cjs_logo.png'),
imageExtensions: const ['jpg', 'png', 'jpeg'],
),
),
),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: ColoredBox(
color: FluentTheme.of(context)
.acrylicBackgroundColor
.withOpacity(0.95),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
cardTitle!,
style: FluentTheme.of(context).typography.subtitle,
textAlign: TextAlign.left,
),
const SizedBox(height: 7.0),
Text(
cardSubtitle!,
style: FluentTheme.of(context).typography.body,
),
const SizedBox(height: 7.0),
cardSubtitle2 == null
? const SizedBox.shrink()
: Text(
cardSubtitle2!,
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w400,
),
),
],
),
),
)),
enableLocationIcon == true
? Positioned(
top: 6.0,
right: 6.0,
child: Transform.rotate(
angle: -math.pi / 25,
child: IconButton(
icon: const Icon(CupertinoIcons.location_fill),
iconSize: 20,
onPressed: () {
const InfoBar(
title: Text('Open Maps'),
content: Text(
'Will navigate to map passing the cardTitle'),
severity: InfoBarSeverity.info,
);
debugPrint(
'Will navigate to map passing the cardTitle');
},
),
),
)
: const SizedBox.shrink(),
],
),
),
);
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib
|
mirrored_repositories/flutter_days_app/lib/widgets/mac_card.dart
|
import 'dart:ui';
import 'package:cached_network_image_builder/cached_network_image_builder.dart';
import 'package:flutter/widgets.dart';
import 'package:macos_ui/macos_ui.dart';
class FrostyBackground extends StatelessWidget {
final Color? color;
final double intensity;
final Widget child;
const FrostyBackground(
{Key? key, this.color, this.intensity = 25, required this.child})
: super(key: key);
@override
Widget build(BuildContext context) {
return ClipRect(
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: intensity, sigmaY: intensity),
child: DecoratedBox(
decoration: BoxDecoration(color: color),
child: child,
),
),
);
}
}
class PressableCard extends StatefulWidget {
final VoidCallback onPressed;
final Widget child;
final BorderRadius borderRadius;
final double upElevation;
final double downElevation;
final Color shadowColor;
final Duration duration;
const PressableCard(
{Key? key,
required this.onPressed,
this.borderRadius = const BorderRadius.all(Radius.circular(10)),
this.upElevation = 2,
this.downElevation = 0,
this.shadowColor = MacosColors.alternatingContentBackgroundColor,
this.duration = const Duration(milliseconds: 100),
required this.child})
: super(key: key);
@override
_PressableCardState createState() => _PressableCardState();
}
class _PressableCardState extends State<PressableCard> {
bool cardIsDown = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(() {
cardIsDown = false;
});
// ignore: unnecessary_null_comparison
if (widget.onPressed != null) {
widget.onPressed();
}
},
onTapDown: (details) => setState(() => cardIsDown = true),
onTapCancel: () => setState(() => cardIsDown = false),
child: AnimatedPhysicalModel(
elevation: cardIsDown ? widget.downElevation : widget.upElevation,
borderRadius: widget.borderRadius,
shape: BoxShape.rectangle,
shadowColor: widget.shadowColor,
duration: widget.duration,
color: MacosColors.systemGrayColor,
child: ClipRRect(
borderRadius: widget.borderRadius,
child: widget.child,
),
),
);
}
}
class MacCard extends StatelessWidget {
const MacCard({
required this.cardImage,
required this.cardTitle,
this.cardSubtitle,
this.cardSubtitle2,
this.enableCornerIcon = false,
this.onPressed,
Key? key,
}) : super(key: key);
final String cardImage;
final String cardTitle;
final String? cardSubtitle;
final String? cardSubtitle2;
final bool? enableCornerIcon;
final VoidCallback? onPressed;
@override
Widget build(BuildContext context) {
return PressableCard(
onPressed: onPressed!,
child: Stack(
children: [
SizedBox(
height: 300,
width: double.infinity,
child: CachedNetworkImageBuilder(
url: cardImage,
builder: (image) => FittedBox(
fit: BoxFit.cover,
child: Image.file(image),
),
placeHolder: Image.asset('assets/cjs_logo.png'),
errorWidget: Image.asset('assets/cjs_logo.png'),
imageExtensions: const ['jpg', 'png', 'jpeg'],
),
),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: FrostyBackground(
color: const Color(0x90ffffff),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
Text(
cardTitle,
style:
MacosTheme.of(context).typography.headline.copyWith(
fontWeight: FontWeight.w800,
),
),
const SizedBox(height: 7.0),
Text(
cardSubtitle!,
style: MacosTheme.of(context).typography.body.copyWith(
fontWeight: FontWeight.w400,
),
),
],
),
),
),
)
],
),
);
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib
|
mirrored_repositories/flutter_days_app/lib/macintosh/nav.dart
|
import 'package:flutter/cupertino.dart' hide OverlayVisibilityMode;
import 'package:flutter_days_app/macintosh/pages/favourites_page.dart';
import 'package:macos_ui/macos_ui.dart';
import 'pages/cart_page.dart';
import 'pages/locations_page.dart';
import 'pages/menu_page.dart';
import 'pages/settings_page.dart';
class MacintoshNav extends StatefulWidget {
const MacintoshNav({Key? key}) : super(key: key);
@override
State<MacintoshNav> createState() => _MacintoshNavState();
}
class _MacintoshNavState extends State<MacintoshNav> {
int pageIndex = 0;
final List<Widget> pages = <Widget>[
CupertinoTabView(builder: (BuildContext context) => const MenuPage()),
const LocationsPage(),
const FavouritesPage(),
const CartPage(),
CupertinoTabView(builder: (BuildContext context) => const SettingsPage()),
];
@override
Widget build(BuildContext context) {
return MacosWindow(
sidebar: Sidebar(
builder: (_, controller) {
return SidebarItems(
currentIndex: pageIndex,
scrollController: controller,
onChanged: (i) => setState(() => pageIndex = i),
items: const [
SidebarItem(
leading: MacosIcon(
CupertinoIcons.book_fill,
),
label: Text('Menu'),
),
SidebarItem(
leading: MacosIcon(CupertinoIcons.location_fill),
label: Text('Locations'),
),
SidebarItem(
leading: MacosIcon(CupertinoIcons.heart),
label: Text('Favourites'),
),
SidebarItem(
leading: MacosIcon(CupertinoIcons.cart),
label: Text('Cart'),
),
SidebarItem(
leading: MacosIcon(CupertinoIcons.settings),
label: Text('Settings'),
),
]);
},
bottom: Padding(
padding: const EdgeInsets.all(16.0),
child: MacosListTile(
leading: const MacosIcon(CupertinoIcons.profile_circled),
title: const Text('Javas User'),
subtitle: const Text('user@javas.com'),
onClick: () {
showMacosAlertDialog(
context: context,
builder: (_) => MacosAlertDialog(
appIcon: const MacosIcon(
CupertinoIcons.profile_circled,
size: 56,
),
title: const Text('Sign in to your account'),
message: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: const [
SizedBox(height: 8),
MacosTextField(
placeholder: 'Email',
autofillHints: [AutofillHints.email],
clearButtonMode: OverlayVisibilityMode.editing,
),
SizedBox(height: 10),
MacosTextField(
placeholder: 'Password',
autofillHints: [AutofillHints.password],
clearButtonMode: OverlayVisibilityMode.editing,
),
],
),
horizontalActions: false,
primaryButton: PushButton(
buttonSize: ButtonSize.large,
onPressed: () =>
Navigator.of(context, rootNavigator: true).pop(),
child: const Text('Sign In')),
secondaryButton: PushButton(
buttonSize: ButtonSize.large,
onPressed: () =>
Navigator.of(context, rootNavigator: true).pop(),
child: const Text('Cancel')),
),
);
},
),
),
minWidth: 200),
child: IndexedStack(
index: pageIndex,
children: pages,
),
);
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/macintosh
|
mirrored_repositories/flutter_days_app/lib/macintosh/pages/locations_page.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter_days_app/graph_objects/graph_queries.dart';
import 'package:flutter_days_app/widgets/mac_card.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:macos_ui/macos_ui.dart';
class LocationsPage extends StatelessWidget {
const LocationsPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MacosScaffold(
toolBar: const ToolBar(title: Text('Locations')),
children: [
ContentArea(builder: (context, scrollController) {
return Query(
options: QueryOptions(document: gql(getCafeLocations)),
builder: (QueryResult? result,
{VoidCallback? refetch, FetchMore? fetchMore}) {
if (result!.isLoading) {
return const Center(child: ProgressCircle());
}
if (result.data == null) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
Icon(CupertinoIcons.location_fill, size: 64),
SizedBox(height: 10),
Text('No Locations Found'),
],
);
}
if (result.exception != null) {
showMacosAlertDialog(
context: context,
builder: (_) {
return MacosAlertDialog(
appIcon: const Icon(
CupertinoIcons.exclamationmark_triangle,
size: 56,
color: MacosColors.systemRedColor),
title: const Text('Error'),
message: Text(
'Error returned the following exception: ${result.exception}'),
primaryButton: PushButton(
buttonSize: ButtonSize.large,
onPressed: () {
refetch!();
Navigator.of(context, rootNavigator: true)
.pop();
},
child: const Text('OK')),
);
});
}
List? locations = result.data!['Cafe_Locations'];
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisExtent: 300,
mainAxisSpacing: 50,
crossAxisSpacing: 20),
padding:
const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
itemCount: locations == null ? 0 : locations.length,
itemBuilder: (BuildContext context, int index) {
final location = locations![index];
return MacCard(
cardImage: location['location_image'],
cardTitle: location['location_name'],
cardSubtitle: location['location_contact1'],
//contact2: '',
onPressed: () {},
);
},
);
});
})
],
);
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/macintosh
|
mirrored_repositories/flutter_days_app/lib/macintosh/pages/cart_page.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart' show Icons, Divider;
import 'package:macos_ui/macos_ui.dart';
class CartPage extends StatelessWidget {
const CartPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MacosScaffold(
toolBar: const ToolBar(title: Text('Cart')),
children: [
ContentArea(builder: (_, __) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const CartListTile(
cartMain: 'CJ’S House Breakfast',
cartExtras: '1 x Extra Sausage, 1 x Egg, 1 x Bacon',
cartPrice: 'Ugx. 25,000',
),
const SizedBox(height: 20),
const CartListTile(
cartMain: 'Fish Fingers & Chips',
cartExtras: '',
cartPrice: 'Ugx. 34,500',
),
const SizedBox(height: 20),
const CartListTile(
cartMain: 'Passion Fruit Nojito',
cartExtras: '',
cartPrice: 'Ugx. 16,500',
quantity: '2',
),
const SizedBox(height: 20),
const CartListTile(
cartMain: 'Mint Scoop Ice Cream',
cartExtras: '',
cartPrice: 'Ugx. 7,000',
quantity: '1',
),
const SizedBox(height: 20),
const Divider(
height: 1,
color: MacosColors.systemGrayColor,
),
const SizedBox(height: 10),
Row(mainAxisAlignment: MainAxisAlignment.end, children: [
Text('Subtotal: UGX 99,500',
style: MacosTheme.of(context).typography.subheadline),
]),
const SizedBox(height: 10),
Row(mainAxisAlignment: MainAxisAlignment.end, children: [
Text('VAT: 18%',
style: MacosTheme.of(context).typography.subheadline),
]),
const SizedBox(height: 10),
Row(mainAxisAlignment: MainAxisAlignment.end, children: [
Text('Total: UGX 117,400',
style: MacosTheme.of(context)
.typography
.headline
.copyWith(fontSize: 18, fontWeight: FontWeight.bold)),
]),
const Spacer(),
const Divider(
height: 1,
color: MacosColors.systemGrayColor,
),
const SizedBox(height: 10),
Center(
child: SizedBox(
width: 300,
child: PushButton(
color:
MacosTheme.of(context).brightness == Brightness.dark
? MacosColors.white
: MacosColors.black,
buttonSize: ButtonSize.large,
onPressed: () {},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Pay with'),
MacosIcon(
Icons.apple,
color: MacosTheme.of(context).brightness ==
Brightness.dark
? MacosColors.black
: MacosColors.white,
),
const Text('Pay'),
])),
),
)
],
),
);
})
],
);
}
}
class CartListTile extends StatelessWidget {
const CartListTile({
required this.cartMain,
required this.cartExtras,
required this.cartPrice,
this.quantity = '1',
Key? key,
}) : super(key: key);
final String cartMain;
final String cartExtras;
final String cartPrice;
final String? quantity;
@override
Widget build(BuildContext context) {
return Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: Image.asset(
'assets/cjs_logo.png',
fit: BoxFit.cover,
width: 40,
height: 40,
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(cartMain,
style: MacosTheme.of(context).typography.headline),
const Spacer(),
Row(
children: [
MacosIconButton(
icon: const MacosIcon(CupertinoIcons.add),
onPressed: () {}),
Text(quantity!),
MacosIconButton(
icon: const MacosIcon(CupertinoIcons.minus),
onPressed: () {}),
],
),
],
),
Text(
cartExtras,
style: MacosTheme.of(context).typography.caption1,
),
Text(cartPrice,
textAlign: TextAlign.justify,
style: MacosTheme.of(context).typography.headline),
],
),
),
),
],
);
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/macintosh
|
mirrored_repositories/flutter_days_app/lib/macintosh/pages/menu_page.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter_days_app/macintosh/pages/menu/dessert_menu.dart';
import 'package:flutter_days_app/macintosh/pages/menu/drinks_menu.dart';
import 'package:flutter_days_app/macintosh/pages/menu/meals_menu.dart';
import 'package:macos_ui/macos_ui.dart';
import 'menu/breakfast_menu.dart';
class MenuPage extends StatefulWidget {
const MenuPage({Key? key}) : super(key: key);
@override
State<MenuPage> createState() => _MenuPageState();
}
class _MenuPageState extends State<MenuPage>
with AutomaticKeepAliveClientMixin<MenuPage> {
int _selectedViewIndex = 0;
@override
Widget build(BuildContext context) {
super.build(context);
return MacosScaffold(
toolBar: ToolBar(
title: const Text('Menu'),
actions: [
ToolBarIconButton(
label: 'Toggle Sidebar',
icon: const MacosIcon(
CupertinoIcons.sidebar_left,
),
onPressed: () => MacosWindowScope.of(context).toggleSidebar(),
showLabel: false,
),
],
),
children: [
ContentArea(builder: (_, __) {
return Stack(children: [
SingleChildScrollView(
padding:
const EdgeInsets.symmetric(horizontal: 20, vertical: 50),
child: _selectedViewIndex == 0
? const BreakfastMenu()
: _selectedViewIndex == 1
? const MealsMenu()
: _selectedViewIndex == 2
? const DrinksMenu()
: const DessertMenu()),
Positioned(
top: 10,
left: 50,
right: 50,
child: CupertinoSlidingSegmentedControl(
children: const {
0: Text('Breakfast Menu'),
1: Text('Meals Menu'),
2: Text('Drinks Menu'),
3: Text('Desserts Menu'),
},
groupValue: _selectedViewIndex,
thumbColor: MacosTheme.of(context).primaryColor,
onValueChanged: (value) =>
setState(() => _selectedViewIndex = value as int),
),
)
]);
})
],
);
}
@override
bool get wantKeepAlive => true;
}
| 0
|
mirrored_repositories/flutter_days_app/lib/macintosh
|
mirrored_repositories/flutter_days_app/lib/macintosh/pages/favourites_page.dart
|
import 'package:flutter/cupertino.dart';
import 'package:macos_ui/macos_ui.dart';
class FavouritesPage extends StatelessWidget {
const FavouritesPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MacosScaffold(
children: [
ContentArea(
builder: (_, __) => Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
Icon(
CupertinoIcons.heart,
size: 50,
),
SizedBox(height: 10),
Text(
'Favourite your favourite dishes to have them show up here.'),
],
),
),
)
],
);
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/macintosh
|
mirrored_repositories/flutter_days_app/lib/macintosh/pages/settings_page.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter_days_app/macintosh/pages/settings/feedback.dart';
import 'package:macos_ui/macos_ui.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'settings/licenses.dart';
class SettingsPage extends StatefulWidget {
const SettingsPage({Key? key}) : super(key: key);
@override
State<SettingsPage> createState() => _SettingsPageState();
}
class _SettingsPageState extends State<SettingsPage> {
int selectedIndex = 1;
@override
Widget build(BuildContext context) {
return MacosScaffold(
toolBar: const ToolBar(
title: Text('Settings'),
),
children: [
ResizablePane(
minSize: 180,
startSize: 220,
windowBreakpoint: 700,
resizableSide: ResizableSide.right,
builder: (_, __) => ListView(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
children: [
MacosListTile(
leading: const MacosIcon(CupertinoIcons.phone),
title: const Text('Call Us'),
subtitle: const Text('+256393000090'),
onClick: () => showMacosAlertDialog(
context: context,
builder: (_) => MacosAlertDialog(
appIcon: Image.asset(
'assets/cjs_logo.png',
width: 56,
height: 56,
),
title: const Text('Call Us'),
message: const Text(
'Unfortunately you are not able to call us at this time.'),
primaryButton: PushButton(
buttonSize: ButtonSize.large,
child: const Text('Cancel'),
onPressed: () =>
Navigator.of(context, rootNavigator: true)
.pop(),
),
)),
),
const SizedBox(height: 20),
MacosListTile(
leading: const MacosIcon(CupertinoIcons.mail),
title: const Text('Email Us'),
subtitle: const Text('info@cafejavas.co.ug'),
onClick: () async =>
await launchUrl(Uri.parse('mailto:info@cafejavas.co.ug')),
),
const SizedBox(height: 20),
MacosListTile(
leading: const MacosIcon(CupertinoIcons.news),
title: const Text('Terms of use'),
onClick: () async => await launchUrl(
Uri.parse('https://cafejavas.co.ug/user/terms'),
),
),
const SizedBox(height: 20),
MacosListTile(
leading: const MacosIcon(CupertinoIcons.lock),
title: const Text('Privacy Policy'),
onClick: () async => await launchUrlString(
'https://cafejavas.co.ug/user/privacy',
),
),
const SizedBox(height: 20),
MacosListTile(
leading: const MacosIcon(CupertinoIcons.bubble_left),
title: const Text('Share your feedback'),
onClick: () => Navigator.of(context).push(
CupertinoPageRoute(builder: (_) => const FeedbackPage())),
),
const SizedBox(height: 20),
MacosListTile(
leading: const MacosIcon(CupertinoIcons.info),
title: const Text('Licenses'),
onClick: () => Navigator.of(context).push(CupertinoPageRoute(
builder: (_) => const MacosLicensePage())),
),
],
),
),
],
);
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/macintosh/pages
|
mirrored_repositories/flutter_days_app/lib/macintosh/pages/menu/menu_details.dart
|
import 'dart:math';
import 'package:cached_network_image_builder/cached_network_image_builder.dart';
import 'package:flutter/cupertino.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:macos_ui/macos_ui.dart';
class MenuDetails extends StatelessWidget {
const MenuDetails({
required this.menuID,
required this.detailQuery,
required this.resultKey,
Key? key,
}) : super(key: key);
final int menuID;
final String detailQuery;
final String resultKey;
@override
Widget build(BuildContext context) {
return Query(
options: QueryOptions(
document: gql(detailQuery), variables: {"menuID": menuID}),
builder: (QueryResult result,
{VoidCallback? refetch, FetchMore? fetchMore}) {
if (result.isLoading) {
return const Center(
child: ProgressCircle(),
);
}
if (result.exception != null) {
showMacosAlertDialog(
context: context,
builder: (_) {
return MacosAlertDialog(
appIcon: const Icon(CupertinoIcons.exclamationmark_triangle,
size: 56, color: MacosColors.systemRedColor),
title: const Text('Error'),
message: Text(
'Error returned the following exception: ${result.exception}'),
primaryButton: PushButton(
buttonSize: ButtonSize.large,
onPressed: () {
refetch!();
Navigator.of(context, rootNavigator: true).pop();
},
child: const Text('OK')),
);
});
}
var detail = result.data![resultKey];
return MacosScaffold(
toolBar: ToolBar(
title: Text(detail['name']),
titleWidth: 400,
actions: [
ToolBarIconButton(
label: 'Favourite',
icon: Icon(
CupertinoIcons.heart,
color: MacosTheme.of(context).iconTheme.color,
),
showLabel: true),
ToolBarIconButton(
label: 'Share',
icon: Icon(
CupertinoIcons.share,
color: MacosTheme.of(context).iconTheme.color,
),
showLabel: true),
ToolBarIconButton(
label: 'Add to Cart',
icon: Icon(
CupertinoIcons.shopping_cart,
color: MacosTheme.of(context).iconTheme.color,
),
showLabel: true),
],
),
children: [
ContentArea(builder: (_, controller) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
controller: controller,
padding:
const EdgeInsets.symmetric(horizontal: 40, vertical: 20),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 300,
width: 450,
child: CachedNetworkImageBuilder(
url: detail['image'],
builder: (image) => DecoratedBox(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
image: DecorationImage(
image: FileImage(image), fit: BoxFit.cover),
),
),
placeHolder: Image.asset('assets/cjs_logo.png'),
errorWidget: Image.asset('assets/cjs_logo.png'),
imageExtensions: const ['jpg', 'png', 'jpeg'],
),
),
const SizedBox(width: 50),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text('Description',
style: MacosTheme.of(context)
.typography
.largeTitle),
const SizedBox(height: 20),
Row(
children: [
RatingIndicator(
value: double.parse(
Random().nextInt(5).toString())),
const SizedBox(width: 10),
Text('(${Random().nextInt(1000).toString()})'),
],
),
const SizedBox(height: 20),
SizedBox(
width: 400,
child: Text(
detail['description'],
style:
MacosTheme.of(context).typography.headline,
),
),
const SizedBox(height: 20),
Text('UGX${detail['price']}',
style: MacosTheme.of(context).typography.title2)
]),
],
),
);
})
],
);
});
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/macintosh/pages
|
mirrored_repositories/flutter_days_app/lib/macintosh/pages/menu/drinks_menu.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter_days_app/widgets/mac_card.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:macos_ui/macos_ui.dart';
import '../../../graph_objects/graph_queries.dart';
class DrinksMenu extends StatelessWidget {
const DrinksMenu({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Query(
options: QueryOptions(document: gql(getDrinks)),
builder: (QueryResult result,
{VoidCallback? refetch, FetchMore? fetchMore}) {
if (result.isLoading) {
return const Center(
child: ProgressCircle(),
);
}
if (result.data == null) {
return Center(
child: Column(
children: [
const Icon(CupertinoIcons.exclamationmark, size: 60),
const SizedBox(height: 20),
Text(
'No drinks available',
style: MacosTheme.of(context).typography.subheadline,
),
],
),
);
}
if (result.exception != null) {
showMacosAlertDialog(
context: context,
builder: (_) {
return MacosAlertDialog(
appIcon: const Icon(CupertinoIcons.exclamationmark_triangle,
size: 56, color: MacosColors.systemRedColor),
title: const Text('Error'),
message: Text(
'Error returned the following exception: ${result.exception}'),
primaryButton: PushButton(
buttonSize: ButtonSize.large,
onPressed: () {
refetch!();
Navigator.of(context, rootNavigator: true).pop();
},
child: const Text('OK')),
);
});
}
List<dynamic> drinksMenu = result.data!['Drinks'];
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisExtent: 300,
mainAxisSpacing: 50,
crossAxisSpacing: 20),
shrinkWrap: true,
itemCount: drinksMenu.length,
padding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 20,
),
itemBuilder: (BuildContext context, int index) {
final drink = drinksMenu[index];
return MacCard(
cardImage: drink['image'],
cardTitle: drink['name'],
cardSubtitle: 'UGX${drink['price']}',
onPressed: () {},
);
},
);
});
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/macintosh/pages
|
mirrored_repositories/flutter_days_app/lib/macintosh/pages/menu/breakfast_menu.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter_days_app/macintosh/pages/menu/menu_details.dart';
import 'package:flutter_days_app/widgets/mac_card.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:macos_ui/macos_ui.dart';
import '../../../graph_objects/graph_queries.dart';
class BreakfastMenu extends StatefulWidget {
const BreakfastMenu({Key? key}) : super(key: key);
@override
State<BreakfastMenu> createState() => _BreakfastMenuState();
}
class _BreakfastMenuState extends State<BreakfastMenu>
with AutomaticKeepAliveClientMixin<BreakfastMenu> {
@override
Widget build(BuildContext context) {
super.build(context);
return Query(
options: QueryOptions(document: gql(getBreakfastMenu)),
builder: (QueryResult result,
{VoidCallback? refetch, FetchMore? fetchMore}) {
if (result.isLoading) {
return const Center(
child: ProgressCircle(),
);
}
if (result.data == null) {
return Center(
child: Column(
children: [
const Icon(CupertinoIcons.exclamationmark, size: 60),
const SizedBox(height: 20),
Text(
'No breakfast available',
style: MacosTheme.of(context).typography.subheadline,
),
],
),
);
}
if (result.exception != null) {
showMacosAlertDialog(
context: context,
builder: (_) {
return MacosAlertDialog(
appIcon: const Icon(CupertinoIcons.exclamationmark_triangle,
size: 56, color: MacosColors.systemRedColor),
title: const Text('Error'),
message: Text(
'Error returned the following exception: ${result.exception}'),
primaryButton: PushButton(
buttonSize: ButtonSize.large,
onPressed: () {
refetch!();
Navigator.of(context, rootNavigator: true).pop();
},
child: const Text('OK')),
);
});
}
List<dynamic> breakMenu = result.data!['Breakfast'];
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisExtent: 300,
mainAxisSpacing: 50,
crossAxisSpacing: 20),
shrinkWrap: true,
itemCount: breakMenu.length,
padding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 20,
),
itemBuilder: (BuildContext context, int index) {
final breakfast = breakMenu[index];
return MacCard(
cardImage: breakfast['image'],
cardTitle: breakfast['name'],
cardSubtitle: 'UGX${breakfast['price']}',
onPressed: () {
Navigator.of(context).push(
CupertinoPageRoute(
builder: (builder) => MenuDetails(
menuID: breakfast['id'],
detailQuery: getBreakFastByID,
resultKey: 'Breakfast_by_pk',
),
),
);
},
);
},
);
});
}
@override
bool get wantKeepAlive => true;
}
| 0
|
mirrored_repositories/flutter_days_app/lib/macintosh/pages
|
mirrored_repositories/flutter_days_app/lib/macintosh/pages/menu/meals_menu.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter_days_app/widgets/mac_card.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:macos_ui/macos_ui.dart';
import '../../../graph_objects/graph_queries.dart';
import 'menu_details.dart';
class MealsMenu extends StatelessWidget {
const MealsMenu({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Query(
options: QueryOptions(document: gql(getMainMeals)),
builder: (QueryResult result,
{VoidCallback? refetch, FetchMore? fetchMore}) {
if (result.isLoading) {
return const Center(
child: ProgressCircle(),
);
}
if (result.data == null) {
return Center(
child: Column(
children: [
const Icon(CupertinoIcons.exclamationmark, size: 60),
const SizedBox(height: 20),
Text(
'No meals available',
style: MacosTheme.of(context).typography.subheadline,
),
],
),
);
}
if (result.exception != null) {
showMacosAlertDialog(
context: context,
builder: (_) {
return MacosAlertDialog(
appIcon: const Icon(CupertinoIcons.exclamationmark_triangle,
size: 56, color: MacosColors.systemRedColor),
title: const Text('Error'),
message: Text(
'Error returned the following exception: ${result.exception}'),
primaryButton: PushButton(
buttonSize: ButtonSize.large,
onPressed: () {
refetch!();
Navigator.of(context, rootNavigator: true).pop();
},
child: const Text('OK')),
);
});
}
List<dynamic> mealsMenu = result.data!['Meals'];
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisExtent: 300,
mainAxisSpacing: 50,
crossAxisSpacing: 20),
shrinkWrap: true,
itemCount: mealsMenu.length,
padding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 20,
),
itemBuilder: (BuildContext context, int index) {
final meal = mealsMenu[index];
return MacCard(
cardImage: meal['image'],
cardTitle: meal['name'],
cardSubtitle: 'UGX${meal['price']}',
onPressed: () {
Navigator.of(context).push(
CupertinoPageRoute(
builder: (builder) => MenuDetails(
menuID: meal['id'],
detailQuery: getMealsByID,
resultKey: 'Meals_by_pk',
),
),
);
},
);
},
);
});
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/macintosh/pages
|
mirrored_repositories/flutter_days_app/lib/macintosh/pages/menu/dessert_menu.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter_days_app/widgets/mac_card.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:macos_ui/macos_ui.dart';
import '../../../graph_objects/graph_queries.dart';
class DessertMenu extends StatelessWidget {
const DessertMenu({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Query(
options: QueryOptions(document: gql(getDessertsMenu)),
builder: (QueryResult result,
{VoidCallback? refetch, FetchMore? fetchMore}) {
if (result.isLoading) {
return const Center(
child: ProgressCircle(),
);
}
if (result.data == null) {
return Center(
child: Column(
children: [
const Icon(CupertinoIcons.exclamationmark, size: 60),
const SizedBox(height: 20),
Text(
'No desserts available',
style: MacosTheme.of(context).typography.subheadline,
),
],
),
);
}
if (result.exception != null) {
showMacosAlertDialog(
context: context,
builder: (_) {
return MacosAlertDialog(
appIcon: const Icon(CupertinoIcons.exclamationmark_triangle,
size: 56, color: MacosColors.systemRedColor),
title: const Text('Error'),
message: Text(
'Error returned the following exception: ${result.exception}'),
primaryButton: PushButton(
buttonSize: ButtonSize.large,
onPressed: () {
refetch!();
Navigator.of(context, rootNavigator: true).pop();
},
child: const Text('OK')),
);
});
}
List<dynamic> dessertMenu = result.data!['Desserts'];
return GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
mainAxisExtent: 300,
mainAxisSpacing: 50,
crossAxisSpacing: 20),
shrinkWrap: true,
itemCount: dessertMenu.length,
padding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 20,
),
itemBuilder: (BuildContext context, int index) {
final dessert = dessertMenu[index];
return MacCard(
cardImage: dessert['image'],
cardTitle: dessert['name'],
cardSubtitle: 'UGX${dessert['price']}',
onPressed: () {},
);
},
);
});
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/macintosh/pages
|
mirrored_repositories/flutter_days_app/lib/macintosh/pages/settings/licenses.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:macos_ui/macos_ui.dart';
class MacosLicensePage extends StatelessWidget {
const MacosLicensePage({
Key? key,
}) : super(key: key);
Future<List<License>> loadLicenses() async =>
LicenseRegistry.licenses.asyncMap<License>((license) async {
final title = license.packages.join('\n');
final text = license.paragraphs
.map<String>((paragraph) => paragraph.text)
.join('\n\n');
return License(title, text);
}).toList();
@override
Widget build(BuildContext context) {
return MacosScaffold(
toolBar: const ToolBar(
title: Text('Licenses'),
),
children: [
ContentArea(
builder: (_, __) => FutureBuilder<List<License>>(
future: loadLicenses(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
final licenses = snapshot.data;
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return const Center(child: ProgressCircle(value: null));
default:
if (snapshot.hasError) {
return Center(
child: Text('Error: ${snapshot.error}'),
);
} else {
return MacosScrollbar(
controller: __,
child: ListView.separated(
controller: __,
shrinkWrap: true,
padding: const EdgeInsets.symmetric(
horizontal: 20, vertical: 20),
itemCount: licenses?.length ?? 0,
itemBuilder: (BuildContext context, int index) {
final license = licenses[index];
return MacosListTile(
title: Text(license.title ?? '',
style:
MacosTheme.of(context).typography.title3),
// subtitle: Text(
// license.text ?? '',
// softWrap: true,
// style: const TextStyle(fontSize: 18),
// ),
//onClick: () => print('Launch license viewer'),
);
},
separatorBuilder: (BuildContext context, int index) =>
const SizedBox(height: 20),
),
);
}
}
},
),
)
]);
}
}
class License {
late String title;
late String text;
License(this.title, this.text);
License.fromJson(Map<String, dynamic> json) {
title = json['title'];
text = json['text'];
}
}
| 0
|
mirrored_repositories/flutter_days_app/lib/macintosh/pages
|
mirrored_repositories/flutter_days_app/lib/macintosh/pages/settings/feedback.dart
|
import 'package:flutter/cupertino.dart';
import 'package:macos_ui/macos_ui.dart';
class FeedbackPage extends StatelessWidget {
const FeedbackPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MacosScaffold(
toolBar: const ToolBar(title: Text('Share your feedback')),
children: [
ContentArea(
builder: (context, scrollController) => MacosScrollbar(
controller: scrollController,
child: SingleChildScrollView(
controller: scrollController,
padding:
const EdgeInsets.symmetric(horizontal: 100, vertical: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'''We’d love to hear your feedback; good or bad. If we didn't make you feel special, we'd like to make it up to you. Please let us know what happened during your visit and we'll get in touch with you soon.
\n\nThe information you provide us will be treated in the strictest confidence and may be used for improving our service delivery purposes. A copy of the completed form will be automatically sent to the email address supplied.''',
textAlign: TextAlign.justify,
),
const SizedBox(height: 20),
const Label(text: Text('First Name')),
const MacosTextField(
placeholder: 'Enter your first name',
autofillHints: [AutofillHints.givenName],
textInputAction: TextInputAction.next,
),
const SizedBox(height: 20),
const Label(text: Text('Last Name')),
const MacosTextField(
placeholder: 'Enter your last name',
autofillHints: [AutofillHints.familyName],
),
const SizedBox(height: 20),
const Label(text: Text('Restaurant Location')),
MacosPopupButton<String>(
value: 'Kira Road',
onChanged: (String? newValue) {
// setState(() {
// popupValue = newValue!;
// });
},
items: <String>[
'Kira Road',
'Lugogo Mall',
'Jinja Road',
'Bombo Road',
'Oasis Mall',
'Victoria Mall',
'Cargen House'
].map<MacosPopupMenuItem<String>>((String value) {
return MacosPopupMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
const SizedBox(height: 20),
const Label(
text: Text('Date of Visit'),
),
const SizedBox(height: 20),
MacosDatePicker(
onDateChanged: (date) => debugPrint(date.toString()),
),
const SizedBox(height: 20),
const Label(
text: Text('Feedback'),
),
const MacosTextField(
placeholder: 'Enter your feedback',
keyboardType: TextInputType.multiline,
maxLines: 4,
textInputAction: TextInputAction.newline,
),
const SizedBox(height: 20),
SizedBox(
width: 250,
child: PushButton(
buttonSize: ButtonSize.large,
onPressed: () {},
child: const Text('Send')),
),
],
),
),
),
)
],
);
}
}
| 0
|
mirrored_repositories/flutter_days_app
|
mirrored_repositories/flutter_days_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_days_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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.