repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/BitCoin-Ticker | mirrored_repositories/BitCoin-Ticker/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:bitcoin_ticker/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/flutter-Anniversary | mirrored_repositories/flutter-Anniversary/lib/env.dart | const ENV = 'DEV';
| 0 |
mirrored_repositories/flutter-Anniversary | mirrored_repositories/flutter-Anniversary/lib/main.dart | import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:daily/pages/home/home.dart';
import 'package:oktoast/oktoast.dart';
import 'package:syncfusion_flutter_core/core.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
void main() {
// Register Syncfusion license
SyncfusionLicense.registerLicense('NT8mJyc2IWhia31hfWN9ZmZoYmF8YGJ8ampqanNiYmlmamlmanMDHmhiZ2BmYGprZmFqEyIifTA8Pg==');
// 安卓透明状态栏
if (Platform.isAndroid) {
SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(statusBarColor: Colors.transparent);
SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
}
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return OKToast(
child: MaterialApp(
title: '时光',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
DefaultCupertinoLocalizations.delegate
],
supportedLocales: [
const Locale('en'),
const Locale('zh'),
],
locale: Locale('zh'),
localeResolutionCallback: (Locale locale, Iterable<Locale> supportedLocales) {
return locale;
},
home: Home(),
),
);
}
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib/pages | mirrored_repositories/flutter-Anniversary/lib/pages/edit/edit.dart | import 'dart:io';
import 'package:daily/components/bottom_button.dart';
import 'package:daily/components/custom_dialog.dart';
import 'package:daily/components/file_image.dart';
import 'package:daily/model/daily.dart';
import 'package:daily/pages/detail/detail.dart';
import 'package:daily/pages/home/home.dart';
import 'package:daily/styles/colors.dart';
import 'package:daily/styles/iconfont.dart';
import 'package:daily/styles/text_style.dart';
import 'package:daily/utils/event_bus.dart';
import 'package:daily/utils/sqlite_help.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:oktoast/oktoast.dart';
import 'package:syncfusion_flutter_datepicker/datepicker.dart';
class EditPage extends StatefulWidget {
final Daliy daliy;
EditPage({Key key, this.daliy}) : super(key: key);
@override
_EditPageState createState() => _EditPageState();
}
class _EditPageState extends State<EditPage> with TickerProviderStateMixin {
final picker = ImagePicker();
final sqlLiteHelper = SqlLiteHelper();
DateTime targetDay;
int imgCurrentIndex;
File _imageBg = File('');
PickedFile pickedFile;
DateFormat formatter = DateFormat('yyyy-MM-dd');
TextEditingController _titleController = TextEditingController();
TextEditingController _headTextController = TextEditingController();
TextEditingController _contentController = TextEditingController();
@override
void initState() {
imgCurrentIndex = 0;
targetDay = DateTime.parse(widget.daliy.targetDay);
_imageBg = File(widget.daliy.imageUrl);
_titleController.addListener(() {
setState(() {});
});
_headTextController.addListener(() {
setState(() {});
});
_titleController.text = widget.daliy.title;
_headTextController.text = widget.daliy.headText;
_contentController.text = widget.daliy.remark;
super.initState();
}
@override
void dispose() {
_titleController.removeListener(() {});
_headTextController.removeListener(() {});
super.dispose();
}
void _clearInput(TextEditingController controller) {
controller.clear();
}
Future getImage() async {
pickedFile = await picker.getImage(source: ImageSource.gallery);
//ƒIX: #3
if (pickedFile != null && pickedFile.path.length > 0) {
setState(() {
_imageBg = File(pickedFile.path);
print(pickedFile.path);
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () async {
FocusScope.of(context).requestFocus(FocusNode());
},
child: Container(
height: MediaQuery.of(context).size.height,
color: AppColors.homeBackGorundColor,
child: Stack(
children: <Widget>[
Container(
color: AppColors.addBackGorundColor,
height: MediaQuery.of(context).size.height * 0.25,
width: MediaQuery.of(context).size.width,
margin: EdgeInsets.only(bottom: 20),
child: Stack(
children: <Widget>[
GestureDetector(
onTap: () => getImage(),
behavior: HitTestBehavior.translucent,
child: Container(
height: 400,
width: MediaQuery.of(context).size.width,
child: _imageBg.existsSync()
? FileImageFormPath(imgPath: _imageBg.path)
: _buildNotChooseImage(),
),
),
Center(
child:
_imageBg.existsSync() ? Text('每个日子都值得纪念', style: AppTextStyles.headTextStyle) : SizedBox(),
)
],
),
),
Positioned(
top: MediaQuery.of(context).padding.top,
right: 15,
child: GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () => _deleteDialog(context),
child: Container(
width: 50,
height: 50,
child: Center(child: Text('删除', style: AppTextStyles.headTextStyle)),
),
),
),
Positioned(
top: MediaQuery.of(context).padding.top,
left: 15,
child: GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () => Navigator.pop(context),
child: Container(height: 50, width: 50, child: Icon(Icons.arrow_back, color: Colors.white)),
),
),
Positioned.fill(
top: MediaQuery.of(context).size.height * 0.25 + 20,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
_buildSelcetItem(
label: '日期',
value: formatter.format(targetDay),
onTap: () => _seletDate(context, targetDay),
),
_buildItemInput(
label: '标题',
placeHolder: '为纪念日写个标题吧~',
controller: _titleController,
),
_buildItemInput(
label: '描述',
placeHolder: '我还没想好要写什么...',
controller: _headTextController,
),
_buildContentTextFiled(
controller: _contentController,
),
Container(
padding: EdgeInsets.symmetric(vertical: 30),
child: BottomButton(
text: '保存',
height: 60,
handleOk: () => _saveAction(context),
),
),
],
),
)
],
),
),
),
),
);
}
/// not choose Image
Widget _buildNotChooseImage() {
return Container(
color: Colors.black45.withOpacity(0.3),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: Container(
height: 50,
width: 50,
child: Icon(Icons.add, size: 24),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(25),
),
),
),
SizedBox(height: 5),
Text('选择一张背景图片', style: AppTextStyles.chooseImageStyle),
],
),
);
}
/// _buildSelcetItem
Widget _buildSelcetItem({String label, String value, Function onTap}) {
return Container(
height: 60,
padding: EdgeInsets.symmetric(horizontal: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: onTap,
child: Container(
width: MediaQuery.of(context).size.width - 60,
child: Row(
children: <Widget>[
Text(label, style: AppTextStyles.inputLabelStyle),
SizedBox(width: 32),
Text(value, style: AppTextStyles.inputLabelStyle),
],
),
),
),
Icon(Icons.chevron_right, size: 20, color: Colors.grey)
],
),
);
}
// Input Item
Widget _buildItemInput({
String label,
String placeHolder,
String errorTipText,
TextEditingController controller,
}) {
return Container(
height: 60,
padding: EdgeInsets.symmetric(horizontal: 20),
child: Row(
children: <Widget>[
Text(label, style: AppTextStyles.inputLabelStyle),
SizedBox(width: 20),
Expanded(
child: TextField(
controller: controller,
keyboardType: TextInputType.text,
style: AppTextStyles.inputValueStyle,
decoration: InputDecoration(
hintText: placeHolder,
hintStyle: AppTextStyles.inputHintStyle,
border: OutlineInputBorder(borderSide: BorderSide.none),
suffixIcon: GestureDetector(
onTap: () => _clearInput(controller),
child: controller.text != '' ? Icon(Icons.cancel, size: 18, color: Colors.black) : SizedBox(),
),
),
cursorColor: AppColors.homeBackGorundColor,
// // 标题
// validator: (v) {
// return validateFunc(v);
// }
),
),
],
),
);
}
/// Content
Widget _buildContentTextFiled({TextEditingController controller}) {
return Container(
height: 170,
margin: EdgeInsets.only(top: 10),
padding: EdgeInsets.symmetric(horizontal: 20),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
),
child: TextField(
maxLines: 5,
maxLength: 500,
controller: controller,
cursorColor: AppColors.homeBackGorundColor,
style: AppTextStyles.inputValueStyle,
decoration: InputDecoration(
hintText: '在这里写下有关这个日子的故事吧~',
hintStyle: AppTextStyles.inputHintStyle,
border: InputBorder.none,
contentPadding: EdgeInsets.all(10)
// border: OutlineInputBorder(borderSide: BorderSide.none),
),
),
),
);
}
/// Date Select
void _seletDate(BuildContext context, DateTime targetDay) {
showModalBottomSheet(
context: context,
backgroundColor: AppColors.dateSelectBackGorundColor,
isScrollControlled: true,
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
builder: (BuildContext context) {
return Container(
height: MediaQuery.of(context).size.height * 0.55,
decoration: BoxDecoration(borderRadius: BorderRadius.circular(16)),
child: Column(
children: <Widget>[
SizedBox(height: 16),
SfDateRangePicker(
initialSelectedDate: targetDay,
initialDisplayDate: targetDay,
backgroundColor: AppColors.dateSelectBackGorundColor,
selectionColor: AppColors.dateSelectHlight,
todayHighlightColor: AppColors.dateSelectHlight,
monthCellStyle: DateRangePickerMonthCellStyle(todayTextStyle: AppTextStyles.dateSelectStyle),
yearCellStyle: DateRangePickerYearCellStyle(todayTextStyle: AppTextStyles.dateSelectStyle),
onSelectionChanged: (DateRangePickerSelectionChangedArgs args) {
_dateChange(args.value);
},
),
],
));
});
}
/// date OnChange
void _dateChange(DateTime date) {
setState(() {
targetDay = date;
});
Navigator.pop(context);
}
/// saveAction
void _saveAction(BuildContext context) async {
if (_titleController.text.length == 0) {
showToast('标题名是必须填写的哦~');
return;
}
if (pickedFile == null && widget.daliy.imageUrl == '') {
showToast('必须选择一张背景图片哦~');
return;
}
//insert to sqlite
final headTextNull = '生如夏花之灿烂';
final remarkNull = '只要面对着阳光努力向上,日子就会变得单纯而美好。';
final Daliy newDaliy = Daliy(
id: widget.daliy.id,
title: _titleController.text,
targetDay: formatter.format(targetDay),
imageUrl: pickedFile == null ? widget.daliy.imageUrl : pickedFile.path,
remark: _contentController.text == '' ? remarkNull : _contentController.text,
headText: _headTextController.text == '' ? headTextNull : _headTextController.text,
);
await sqlLiteHelper.open();
await sqlLiteHelper.update(newDaliy);
showToast('修改成功');
bus.emit('editSuccess', newDaliy);
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context) {
return HeroDetailPage(daliy: newDaliy);
}), (Route route) {
if (route.settings?.name == '/') {
return true; //停止关闭
}
return false; //继续关闭
});
}
void _deleteDialog(BuildContext context) {
showDialog(
context: context,
barrierDismissible: false,
builder: (_) {
return CustomDialog(
content: Center(
child: Column(
children: <Widget>[
Icon(Iconfont.comfirm, size: 36),
Container(
padding: EdgeInsets.only(bottom: 0.0, top: 20),
child: Text(
'确定删除该纪念日吗?',
style: AppTextStyles.deleteStyle,
),
),
],
),
),
confirmContent: '确定',
cancelContent: '取消',
isCancel: true,
confirmCallback: () {
print('object');
_deleteAction();
},
dismissCallback: () {
return;
},
);
});
}
void _deleteAction() async {
await sqlLiteHelper.open();
await sqlLiteHelper.delete(widget.daliy);
showToast('删除成功');
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context) {
return Home();
}), (Route route) {
return false;
});
}
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib/pages | mirrored_repositories/flutter-Anniversary/lib/pages/share/post_enter.dart | import 'package:daily/pages/share/post_avatar.dart';
import 'package:daily/pages/share/post_bg.dart';
import 'package:daily/pages/share/qr.dart';
import 'package:flutter/material.dart';
import 'dart:ui' as ui;
import 'package:flutter_spinkit/flutter_spinkit.dart';
enum Status { loading, complete }
class MainPainter extends CustomPainter {
final Background background;
final MainQR hero;
final PostAvatar postAvatar;
final Size size;
final String url;
MainPainter({this.background, this.hero, this.url, this.size, this.postAvatar});
@override
void paint(Canvas canvas, Size size) {
background.paint(canvas, size);
postAvatar.paint(canvas, size);
hero.paint(canvas, size);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
// TODO: implement shouldRepaint
return oldDelegate != this;
}
}
class EnterPostPage extends StatefulWidget {
String bgUrl;
String qrImageUrl;
final double screenWidth;
final double screenHeight;
EnterPostPage({this.bgUrl, this.qrImageUrl, this.screenWidth, this.screenHeight});
_EnterPostPage createState() => _EnterPostPage();
}
class _EnterPostPage extends State<EnterPostPage> with TickerProviderStateMixin {
Status gameStatus = Status.loading;
int index = 0;
Background background;
MainQR hero;
PostAvatar postAvatar;
initState() {
initPost();
}
Widget build(BuildContext context) {
if (gameStatus == Status.loading) {
return Center(child: SpinKitPumpingHeart(color: Colors.black));
}
return CustomPaint(
painter: MainPainter(
background: background,
hero: hero,
postAvatar: postAvatar,
size: Size(widget.screenWidth, widget.screenHeight)),
size: Size(widget.screenWidth, widget.screenHeight));
}
void initPost() async {
background = new Background(
url: widget.bgUrl,
screenWidth: widget.screenWidth - 60,
screenHeight: widget.screenHeight - 300,
);
hero = new MainQR(url: widget.qrImageUrl);
postAvatar = new PostAvatar();
await hero.init();
await postAvatar.init();
await background.init();
setState(() {
gameStatus = Status.complete;
});
}
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib/pages | mirrored_repositories/flutter-Anniversary/lib/pages/share/post_avatar.dart | import 'dart:ui' as ui;
import 'package:cached_network_image/cached_network_image.dart';
import 'package:daily/pages/share/utils.dart';
import 'package:flutter/material.dart';
class PostAvatar {
ui.Image image;
String nickName;
PostAvatar();
@override
void init() async {
nickName = '时光';
image = await Utils.loadImageByProvider(
CachedNetworkImageProvider('https://i.loli.net/2020/09/09/ERKPs9iMJGSvk8V.png'));
}
@override
void paint(Canvas canvas, Size size) {
canvas.save();
Paint paint = new Paint();
canvas.scale(0.35, 0.35);
print(image.width);
var textLeft = 180.0;
ui.ParagraphBuilder paragraphBuilder = ui.ParagraphBuilder(
ui.ParagraphStyle(
textAlign: TextAlign.left,
fontSize: 36.0,
textDirection: TextDirection.ltr,
maxLines: 1,
),
)
..pushStyle(
ui.TextStyle(color: Colors.white, textBaseline: ui.TextBaseline.alphabetic),
)
..addText(nickName);
ui.Paragraph paragraph = paragraphBuilder.build()..layout(ui.ParagraphConstraints(width: 500.0));
canvas.drawParagraph(paragraph, Offset(textLeft, 1230.0));
ui.ParagraphBuilder paragraphBuilder2 = ui.ParagraphBuilder(
ui.ParagraphStyle(
textAlign: TextAlign.left,
fontSize: 36.0,
textDirection: TextDirection.ltr,
maxLines: 1,
),
)
..pushStyle(
ui.TextStyle(color: Colors.white, textBaseline: ui.TextBaseline.alphabetic),
)
..addText('邀您一起加入时光旅行');
ui.Paragraph paragraph2 = paragraphBuilder2.build()..layout(ui.ParagraphConstraints(width: 500.0));
canvas.drawParagraph(paragraph2, Offset(textLeft, 1280.0));
ui.ParagraphBuilder paragraphBuilder3 = ui.ParagraphBuilder(
ui.ParagraphStyle(
textAlign: TextAlign.left,
fontSize: 32.0,
textDirection: TextDirection.ltr,
maxLines: 1,
),
)
..pushStyle(
ui.TextStyle(color: Colors.white, textBaseline: ui.TextBaseline.alphabetic),
)
..addText('阿里云技术支持');
ui.Paragraph paragraph3 = paragraphBuilder3.build()..layout(ui.ParagraphConstraints(width: 500.0));
canvas.drawParagraph(paragraph3, Offset(textLeft, 1330.0));
var radius = image.width.toDouble() / 2;
var top = 1250.0;
var left = 30.0;
canvas.clipRRect(
RRect.fromRectXY(Rect.fromLTWH(left, top, image.width.toDouble(), image.width.toDouble()), radius, radius),
doAntiAlias: false);
canvas.drawImageRect(image, Offset(0.0, 0.0) & Size(400, 400), Offset(left, top) & Size(400.0, 400.0), paint);
canvas.restore();
}
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib/pages | mirrored_repositories/flutter-Anniversary/lib/pages/share/share.dart | import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';
import 'package:daily/components/bottom_button.dart';
import 'package:daily/pages/share/post_enter.dart';
import 'package:daily/styles/colors.dart';
import 'package:daily/styles/text_style.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'dart:ui' as ui;
import 'package:oktoast/oktoast.dart';
import 'package:permission_handler/permission_handler.dart';
class ShareContentPost extends StatefulWidget {
String bgUrl;
String qrImageUrl;
ShareContentPost({this.bgUrl, this.qrImageUrl});
@override
_ShareContentPostState createState() => _ShareContentPostState();
}
class _ShareContentPostState extends State<ShareContentPost> {
GlobalKey globalKey = GlobalKey();
Future<void> _capturePng() async {
// '保存中...'
RenderRepaintBoundary boundary = globalKey.currentContext.findRenderObject();
ui.Image image = await boundary.toImage(pixelRatio: window.devicePixelRatio);
ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes = byteData.buffer.asUint8List();
print(pngBytes);
var status = await Permission.storage.request();
if (status == PermissionStatus.granted) {
var result = await ImageGallerySaver.saveImage(pngBytes);
print(result);
if (result == true || result != '') {
showToast('成功保存到相册!');
// Navigator.pop(context);
}
}
}
@override
Widget build(BuildContext context) {
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle.dark,
child: Scaffold(
appBar: AppBar(
elevation: 0,
centerTitle: true,
brightness: Brightness.dark,
backgroundColor: AppColors.homeBackGorundColor,
title: Text('分享', style: AppTextStyles.shareTitleStyle),
leading: GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () => Navigator.pop(context),
child: Container(height: 50, width: 50, child: Icon(Icons.arrow_back, color: Colors.black)),
),
),
body: Center(
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.all(30),
color: AppColors.homeBackGorundColor,
child: Column(
children: <Widget>[
Expanded(
child: RepaintBoundary(
key: globalKey,
child: EnterPostPage(
bgUrl: widget.bgUrl,
qrImageUrl: widget.qrImageUrl,
screenWidth: MediaQuery.of(context).size.width,
screenHeight: MediaQuery.of(context).size.height,
),
),
),
Container(
padding: EdgeInsets.only(top: 20),
child: BottomButton(
text: '保存',
height: 50,
handleOk: () => _capturePng(),
),
),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib/pages | mirrored_repositories/flutter-Anniversary/lib/pages/share/post_bg.dart | // 背景图
import 'package:cached_network_image/cached_network_image.dart';
import 'package:daily/pages/share/utils.dart';
import 'package:flutter/material.dart';
import 'dart:ui' as ui;
class Background {
// 屏幕的宽度
double screenWidth;
// 屏幕的高度
double screenHeight;
// 加载的背景图片
ui.Image image;
String url;
// 构造函数
Background({this.url, this.screenWidth, this.screenHeight});
// 初始化, 各种资源
Future<VoidCallback> init() async {
image = await Utils.loadImageByProvider(CachedNetworkImageProvider(url));
}
// 绘图函数
paint(Canvas canvas, Size size) async {
Rect screenWrap = Offset(0.0, 0.0) & Size(screenWidth, screenHeight);
Paint screenWrapPainter = new Paint();
screenWrapPainter.color = Colors.white;
screenWrapPainter.style = PaintingStyle.fill;
canvas.drawRect(screenWrap, screenWrapPainter);
canvas.save();
// canvas.scale(1, 1);
Paint paint = new Paint();
canvas.drawImageRect(image, Offset(0.0, 0.0) & Size(image.width.toDouble(), image.height.toDouble()),
Offset(0.0, 0.0) & Size(screenWidth, screenHeight), paint);
canvas.restore();
}
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib/pages | mirrored_repositories/flutter-Anniversary/lib/pages/share/qr.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import './utils.dart';
import 'dart:ui' as ui;
class MainQR {
ui.Image image;
String url;
MainQR({this.url});
@override
void init() async {
image = await Utils.loadImageByProvider(CachedNetworkImageProvider(url));
}
@override
void paint(Canvas canvas, Size size) {
canvas.save();
Paint paint = new Paint();
canvas.scale(0.25, 0.25);
canvas.drawImageRect(image, Offset(0.0, 0.0) & Size(400, 400), Offset(850.0, 1640.0) & Size(400.0, 400.0), paint);
ui.ParagraphBuilder paragraphBuilder = ui.ParagraphBuilder(
ui.ParagraphStyle(
textAlign: TextAlign.center,
fontSize: 36.0,
textDirection: TextDirection.ltr,
maxLines: 1,
),
)
..pushStyle(
ui.TextStyle(color: Colors.white, textBaseline: ui.TextBaseline.alphabetic),
)
..addText('长按识别');
ui.Paragraph paragraph = paragraphBuilder.build()..layout(ui.ParagraphConstraints(width: 200.0));
canvas.drawParagraph(paragraph, Offset(950.0, 2060.0));
canvas.restore();
}
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib/pages | mirrored_repositories/flutter-Anniversary/lib/pages/share/utils.dart | import 'dart:async';
import 'dart:ui' as ui;
import 'dart:typed_data';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:qr_flutter/qr_flutter.dart';
class Utils {
static Future<ui.Image> getImage(String asset) async {
ByteData data = await rootBundle.load(asset);
var codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
FrameInfo fi = await codec.getNextFrame();
return fi.image;
}
static Future<ui.Image> getImageByQR(String url, {size: 70.0}) async {
final image = await QrPainter(
data: url,
version: QrVersions.auto,
gapless: false,
).toImage(size);
final a = await image.toByteData(format: ImageByteFormat.png);
var codec = await ui.instantiateImageCodec(a.buffer.asUint8List());
FrameInfo fi = await codec.getNextFrame();
return fi.image;
}
static Future<ui.Image> loadImageByProvider(
ImageProvider provider, {
ImageConfiguration config = ImageConfiguration.empty,
}) async {
Completer<ui.Image> completer = Completer<ui.Image>(); //完成的回调
ImageStreamListener listener;
ImageStream stream = provider.resolve(config); //获取图片流
listener = ImageStreamListener((ImageInfo frame, bool sync) {
//监听
final ui.Image image = frame.image;
completer.complete(image); //完成
stream.removeListener(listener); //移除监听
});
stream.addListener(listener); //添加监听
return completer.future; //返回
}
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib/pages | mirrored_repositories/flutter-Anniversary/lib/pages/detail/detail.dart | import 'dart:async';
import 'dart:io';
import 'package:daily/components/file_image.dart';
import 'package:daily/components/placeholder_image.dart';
import 'package:daily/model/daily.dart';
import 'package:daily/pages/edit/edit.dart';
import 'package:daily/styles/colors.dart';
import 'package:daily/styles/iconfont.dart';
import 'package:daily/styles/text_style.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class HeroDetailPage extends StatefulWidget {
final Daliy daliy;
final String imgPlaceHolder;
const HeroDetailPage({Key key, this.daliy, this.imgPlaceHolder}) : super(key: key);
@override
_HeroDetailPageState createState() => _HeroDetailPageState();
}
class _HeroDetailPageState extends State<HeroDetailPage> {
Timer _timer;
bool _toogle = true;
int _countdownTime = 2;
String countYear = '';
String countMonth = '';
String countDay = '';
String countTotalDay = '';
bool _todayIsLateTarget = true;
@override
void initState() {
caclTimeDistance();
startCountdownTimer();
super.initState();
}
// 计算时间差
void caclTimeDistance() {
int year = 0;
int month = 0;
int day = 0;
int total = 0;
final today = new DateTime.now();
final targetDay = DateTime.parse(widget.daliy.targetDay);
final difference = today.difference(targetDay);
_todayIsLateTarget = difference.inDays > 0 ? true : false;
total = (difference.inDays).abs();
year = total ~/ 365;
month = (total - year * 365) ~/ 30;
day = total - year * 365 - month * 30;
countTotalDay = formatNum(total);
countYear = formatNum(year);
countMonth = formatNum(month);
countDay = formatNum(day);
setState(() {});
// print([countTotalDay, countYear, countMonth, countDay]);
}
String formatNum(int num) {
return num < 10 ? '0$num' : num.toString();
}
// 每隔2s切换Widget
void startCountdownTimer() {
const oneSec = Duration(seconds: 1);
var callback = (timer) => {
setState(() {
if (_countdownTime < 1) {
_toogle = !_toogle;
_countdownTime = 2;
} else {
_countdownTime = _countdownTime - 1;
}
})
};
_timer = Timer.periodic(oneSec, callback);
}
@override
void dispose() {
super.dispose();
if (_timer != null) {
_timer.cancel();
}
}
@override
Widget build(BuildContext context) {
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle.light,
child: Scaffold(
body: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: Container(
height: MediaQuery.of(context).size.height,
color: AppColors.detailBackGorundColor,
child: SingleChildScrollView(
child: Column(
children: <Widget>[
Hero(
tag: 'hero${widget.daliy.id}',
child: Container(
height: 400,
child: Stack(
children: <Widget>[
_buildTopBg(context, widget.daliy),
_buildTopContent(context, widget.daliy),
],
),
),
),
_buildBottomContent(widget.daliy),
],
),
),
),
),
),
);
}
/// 顶部背景图
Widget _buildTopBg(BuildContext context, Daliy daliy) {
return Container(
height: 400,
width: MediaQuery.of(context).size.width,
child: File(daliy.imageUrl).existsSync()
? FileImageFormPath(imgPath: daliy.imageUrl)
: PlaceHolderImage(imgUrl: widget.imgPlaceHolder),
);
}
/// 顶部内容
Widget _buildTopContent(BuildContext context, Daliy daliy) {
return SafeArea(
bottom: false,
child: Padding(
padding: EdgeInsets.all(18),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(daliy.headText, style: AppTextStyles.headTextStyle),
GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () {
Navigator.push(
context,
PageRouteBuilder(
transitionDuration: Duration(milliseconds: 300),
pageBuilder: (BuildContext context, Animation animation, Animation secondaryAnimation) {
return ScaleTransition(
scale: animation,
alignment: Alignment.topRight,
child: EditPage(daliy: daliy),
);
}),
).then((value) {
setState(() {
daliy = value;
});
});
// Navigator.of(context).push(
// MaterialPageRoute(builder: (context) {
// return EditPage(daliy: daliy);
// }),
// ).then((value) {
// setState(() {
// daliy = value;
// });
// });
},
child: Container(
width: 80,
child: Align(
alignment: Alignment.centerRight,
child: Text('编辑', style: AppTextStyles.headTextStyle),
),
),
),
],
),
Text(daliy.title, style: AppTextStyles.titleTextStyle),
Expanded(
child: AnimatedSwitcher(
duration: Duration(seconds: 1),
child: _toogle
? _buildMiddleYear(daliy, senceWidth: MediaQuery.of(context).size.width)
: _buildMiddleCountDay(daliy, senceWidth: MediaQuery.of(context).size.width),
),
),
Text(daliy.targetDay, style: AppTextStyles.targetDayStyle)
],
),
),
);
}
/// 年月日
Widget _buildMiddleYear(Daliy daliy, {double senceWidth}) {
return Center(
key: ValueKey('year'),
child: Container(
width: (senceWidth - 36) * 0.6,
height: 80,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
height: 80,
child: Stack(
alignment: Alignment.center,
children: <Widget>[
Text(countYear, style: AppTextStyles.countTitleStyle),
Positioned(top: 50, child: Text('年', style: AppTextStyles.countBottomTipStyle)),
],
),
),
Container(
height: 80,
child: Stack(
alignment: Alignment.center,
children: <Widget>[
Text(countMonth, style: AppTextStyles.countTitleStyle),
Positioned(top: 50, child: Text('月', style: AppTextStyles.countBottomTipStyle)),
],
),
),
Container(
height: 80,
child: Stack(
alignment: Alignment.center,
children: <Widget>[
Text(countDay, style: AppTextStyles.countTitleStyle),
Positioned(top: 50, child: Text('日', style: AppTextStyles.countBottomTipStyle)),
],
),
),
],
),
),
);
}
/// 距离目标日的总天数
Widget _buildMiddleCountDay(Daliy daliy, {double senceWidth}) {
return Center(
key: ValueKey('day'),
child: Container(
width: (senceWidth - 36) * 0.6,
height: 80,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(countTotalDay, style: AppTextStyles.countTitleStyle),
SizedBox(width: 2),
Text('天', style: AppTextStyles.countBottomTipStyle),
Icon(_todayIsLateTarget ? Iconfont.up2 : Iconfont.down1, color: Colors.white, size: 14),
],
),
),
);
}
/// 底部内容
Widget _buildBottomContent(Daliy daliy) {
return Container(
padding: EdgeInsets.all(10),
margin: EdgeInsets.all(10),
width: MediaQuery.of(context).size.width - 20,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
),
child: Text(daliy.remark, style: AppTextStyles.contentStyle),
);
}
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib/pages | mirrored_repositories/flutter-Anniversary/lib/pages/add/add.dart | import 'dart:io';
import 'package:daily/components/bottom_button.dart';
import 'package:daily/components/file_image.dart';
import 'package:daily/model/daily.dart';
import 'package:daily/styles/colors.dart';
import 'package:daily/styles/text_style.dart';
import 'package:daily/utils/sqlite_help.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:oktoast/oktoast.dart';
import 'package:syncfusion_flutter_datepicker/datepicker.dart';
class AddNew extends StatefulWidget {
AddNew({Key key}) : super(key: key);
@override
_AddNewState createState() => _AddNewState();
}
class _AddNewState extends State<AddNew> with TickerProviderStateMixin {
final picker = ImagePicker();
final sqlLiteHelper = SqlLiteHelper();
DateTime targetDay;
int imgCurrentIndex;
File _imageBg = File('');
PickedFile pickedFile;
DateFormat formatter = DateFormat('yyyy-MM-dd');
TextEditingController _titleController = TextEditingController();
TextEditingController _headTextController = TextEditingController();
TextEditingController _contentController = TextEditingController();
Future getImage() async {
pickedFile = await picker.getImage(source: ImageSource.gallery);
if (pickedFile != null && pickedFile.path.length > 0) {
setState(() {
_imageBg = File(pickedFile.path);
print(pickedFile.path);
});
}
}
@override
void initState() {
imgCurrentIndex = 0;
targetDay = DateTime.now();
_titleController.addListener(() {
setState(() {});
});
_headTextController.addListener(() {
setState(() {});
});
super.initState();
}
@override
void dispose() {
_titleController.removeListener(() {});
_headTextController.removeListener(() {});
super.dispose();
}
void _clearInput(TextEditingController controller) {
controller.clear();
}
@override
Widget build(BuildContext context) {
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle.light,
child: Scaffold(
body: SingleChildScrollView(
child: GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () async {
FocusScope.of(context).requestFocus(FocusNode());
},
child: Container(
height: MediaQuery.of(context).size.height,
color: AppColors.homeBackGorundColor,
child: Stack(
children: <Widget>[
Container(
color: AppColors.addBackGorundColor,
height: MediaQuery.of(context).size.height * 0.25,
width: MediaQuery.of(context).size.width,
margin: EdgeInsets.only(bottom: 20),
child: Stack(
children: <Widget>[
GestureDetector(
onTap: () => getImage(),
behavior: HitTestBehavior.translucent,
child: Container(
height: 400,
width: MediaQuery.of(context).size.width,
child: _imageBg.existsSync()
? FileImageFormPath(imgPath: pickedFile.path)
: _buildNotChooseImage(),
),
),
Center(
child: _imageBg.existsSync()
? Text('每个日子都值得纪念', style: AppTextStyles.headTextStyle)
: SizedBox(),
)
],
)),
Positioned(
top: MediaQuery.of(context).padding.top,
left: 15,
child: GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () => Navigator.pop(context, false),
child: Container(height: 50, width: 50, child: Icon(Icons.arrow_back, color: Colors.white)),
),
),
Positioned.fill(
top: MediaQuery.of(context).size.height * 0.25 + 20,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
_buildSelcetItem(
label: '日期',
value: formatter.format(targetDay),
onTap: () => _seletDate(context, targetDay),
),
_buildItemInput(
label: '标题',
placeHolder: '为纪念日写个标题吧~',
controller: _titleController,
),
_buildItemInput(
label: '描述',
placeHolder: '我还没想好要写什么...',
controller: _headTextController,
),
_buildContentTextFiled(
controller: _contentController,
),
Container(
padding: EdgeInsets.symmetric(vertical: 30),
child: BottomButton(
text: '保存',
height: 60,
handleOk: () => _addAction(context),
),
),
],
),
)
],
),
),
),
),
),
);
}
/// not choose Image
Widget _buildNotChooseImage() {
return Container(
color: Colors.black45.withOpacity(0.3),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: Container(
height: 50,
width: 50,
child: Icon(Icons.add, size: 24),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(25),
),
),
),
SizedBox(height: 5),
Text('选择一张背景图片', style: AppTextStyles.chooseImageStyle),
],
),
);
}
/// _buildSelcetItem
Widget _buildSelcetItem({String label, String value, Function onTap}) {
return Container(
height: 60,
padding: EdgeInsets.symmetric(horizontal: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: onTap,
child: Container(
width: MediaQuery.of(context).size.width - 60,
child: Row(
children: <Widget>[
Text(label, style: AppTextStyles.inputLabelStyle),
SizedBox(width: 32),
Text(value, style: AppTextStyles.inputLabelStyle),
],
),
),
),
Icon(Icons.chevron_right, size: 20, color: Colors.grey)
],
),
);
}
// Input Item
Widget _buildItemInput({
String label,
String placeHolder,
String errorTipText,
TextEditingController controller,
}) {
return Container(
height: 60,
padding: EdgeInsets.symmetric(horizontal: 20),
child: Row(
children: <Widget>[
Text(label, style: AppTextStyles.inputLabelStyle),
SizedBox(width: 20),
Expanded(
child: TextField(
controller: controller,
keyboardType: TextInputType.text,
style: AppTextStyles.inputValueStyle,
decoration: InputDecoration(
hintText: placeHolder,
hintStyle: AppTextStyles.inputHintStyle,
border: OutlineInputBorder(borderSide: BorderSide.none),
suffixIcon: GestureDetector(
onTap: () => _clearInput(controller),
child: controller.text != '' ? Icon(Icons.cancel, size: 18, color: Colors.black) : SizedBox(),
),
),
cursorColor: AppColors.homeBackGorundColor,
// // 标题
// validator: (v) {
// return validateFunc(v);
// }
),
),
],
),
);
}
/// Content
Widget _buildContentTextFiled({TextEditingController controller}) {
return Container(
height: 170,
margin: EdgeInsets.only(top: 10),
padding: EdgeInsets.symmetric(horizontal: 20),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
),
child: TextField(
maxLines: 5,
maxLength: 500,
controller: controller,
cursorColor: AppColors.homeBackGorundColor,
style: AppTextStyles.inputValueStyle,
decoration: InputDecoration(
hintText: '在这里写下有关这个日子的故事吧~',
hintStyle: AppTextStyles.inputHintStyle,
border: InputBorder.none,
contentPadding: EdgeInsets.all(10)
// border: OutlineInputBorder(borderSide: BorderSide.none),
),
),
),
);
}
/// Date Select
void _seletDate(BuildContext context, DateTime targetDay) {
showModalBottomSheet(
context: context,
backgroundColor: AppColors.dateSelectBackGorundColor,
isScrollControlled: true,
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
builder: (BuildContext context) {
return Container(
height: MediaQuery.of(context).size.height * 0.55,
decoration: BoxDecoration(borderRadius: BorderRadius.circular(16)),
child: Column(
children: <Widget>[
SizedBox(height: 16),
SfDateRangePicker(
initialSelectedDate: targetDay,
initialDisplayDate: targetDay,
backgroundColor: AppColors.dateSelectBackGorundColor,
selectionColor: AppColors.dateSelectHlight,
todayHighlightColor: AppColors.dateSelectHlight,
monthCellStyle: DateRangePickerMonthCellStyle(todayTextStyle: AppTextStyles.dateSelectStyle),
yearCellStyle: DateRangePickerYearCellStyle(todayTextStyle: AppTextStyles.dateSelectStyle),
onSelectionChanged: (DateRangePickerSelectionChangedArgs args) {
_dateChange(args.value);
},
),
],
));
});
}
/// date OnChange
void _dateChange(DateTime date) {
setState(() {
targetDay = date;
});
Navigator.pop(context);
}
/// addAction
void _addAction(BuildContext context) async {
if (_titleController.text.length == 0) {
showToast('标题名是必须填写的哦~');
return;
}
if (pickedFile == null) {
showToast('必须选择一张背景图片哦~');
return;
}
//insert to sqlite
final headTextNull = '生如夏花之灿烂';
final remarkNull = '只要面对着阳光努力向上,日子就会变得单纯而美好。';
final Daliy daliy = Daliy(
title: _titleController.text,
targetDay: formatter.format(targetDay),
imageUrl: pickedFile.path,
remark: _contentController.text == '' ? remarkNull : _contentController.text,
headText: _headTextController.text == '' ? headTextNull : _headTextController.text,
);
await sqlLiteHelper.open();
await sqlLiteHelper.insert(daliy);
showToast('添加成功');
Navigator.pop(context, true);
}
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib/pages | mirrored_repositories/flutter-Anniversary/lib/pages/about/about.dart | import 'dart:math';
import 'package:daily/components/webview_page.dart';
import 'package:daily/model/img.dart';
import 'package:daily/pages/share/share.dart';
import 'package:daily/styles/colors.dart';
import 'package:daily/styles/text_style.dart';
import 'package:flutter/material.dart';
class About extends StatelessWidget {
final List<ImageModel> imgList;
const About({Key key, this.imgList}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: AppColors.homeBackGorundColor,
child: Stack(
children: <Widget>[
Positioned(
top: MediaQuery.of(context).padding.top,
left: 15,
child: GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () => Navigator.pop(context, false),
child: Container(height: 50, width: 50, child: Icon(Icons.arrow_back, color: Colors.black)),
),
),
Positioned(
top: 0,
right: 0,
child: Container(
child: CustomPaint(
size: Size(300, 300), //指定画布大小
painter: MyPainterTopRight(MediaQuery.of(context).size.width, MediaQuery.of(context).size.height),
),
),
),
Positioned(
bottom: 0,
left: 0,
child: Container(
child: CustomPaint(
size: Size(200, 200), //指定画布大小
painter: MyPainterBottomLeft(MediaQuery.of(context).size.width, MediaQuery.of(context).size.height),
),
),
),
Positioned(
top: 100,
left: 48,
child: Container(
width: 60,
height: 60,
child: Image.asset('assets/images/app.png', fit: BoxFit.contain),
),
),
Positioned(
top: 160,
left: 60,
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('0.4.0', style: AppTextStyles.aboutStyle),
SizedBox(height: 10),
Text('这是一款能够留住时光的APP', style: AppTextStyles.aboutStyle),
],
),
),
),
Positioned(
left: 50,
bottom: MediaQuery.of(context).padding.bottom + 200,
child: Container(
width: 200,
height: 150,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
_buildMiddleItem(
title: '功能介绍',
imgUrl: 'assets/images/list.png',
size: 36,
action: () {
Navigator.of(context).push(MaterialPageRoute(builder: (_) {
return WebViewPage(
url: 'https://github.com/xieyezi/flutter-Anniversary/blob/master/CHANGELOG.md',
title: '功能介绍',
);
}));
}),
_buildMiddleItem(
title: '与作者联系',
imgUrl: 'assets/images/email.png',
size: 30,
action: () {
Navigator.of(context).push(MaterialPageRoute(builder: (_) {
return WebViewPage(
url: 'https://github.com/xieyezi/flutter-Anniversary/issues/new',
title: '与作者联系',
);
}));
}),
_buildMiddleItem(
title: '分享给好友',
imgUrl: 'assets/images/air.png',
size: 30,
action: () {
Navigator.push(
context,
PageRouteBuilder(
transitionDuration: Duration(milliseconds: 300),
pageBuilder: (BuildContext context, Animation animation, Animation secondaryAnimation) {
return ScaleTransition(
scale: animation,
alignment: Alignment.bottomRight,
child: ShareContentPost(bgUrl: imgList[6].imgUrl, qrImageUrl: imgList[7].imgUrl),
);
}),
);
}),
],
),
),
),
Positioned(
right: 20,
bottom: MediaQuery.of(context).padding.bottom + 20,
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
GestureDetector(
onTap: () {
Navigator.of(context).push(MaterialPageRoute(builder: (_) {
return WebViewPage(
url: 'https://juejin.im/user/4248168660738606/posts',
title: '觉非',
);
}));
},
child: Text('觉非 温情出品', style: AppTextStyles.aboutBottomStyle)),
SizedBox(height: 8),
GestureDetector(
onTap: () {
Navigator.of(context).push(MaterialPageRoute(builder: (_) {
return WebViewPage(
url: 'https://github.com/xieyezi/flutter-Anniversary/blob/master/LICENSE',
title: '时光',
);
}));
},
child: Text('隐私协议 软件使用协议 官方地址', style: AppTextStyles.aboutBottomStyle)),
],
),
),
],
),
),
);
}
Widget _buildMiddleItem({String imgUrl, String title, double size, Function action}) {
return GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () => action(),
child: Row(
children: <Widget>[
Image.asset(
imgUrl,
width: size,
height: size,
),
SizedBox(width: 10),
Text(title, style: AppTextStyles.aboutMiddleStyle),
],
),
);
}
}
class MyPainterTopRight extends CustomPainter {
final double screenWitdh;
final double screenHeight;
MyPainterTopRight(this.screenWitdh, this.screenHeight);
@override
void paint(Canvas canvas, Size size) {
Paint paint = Paint()
..isAntiAlias = true
..color = Color.fromRGBO(93, 92, 238, 0.9)
..strokeCap = StrokeCap.round
..strokeWidth = 80
..style = PaintingStyle.stroke;
/// Offset(),横纵坐标偏移
/// void drawArc(Rect rect, double startAngle, double sweepAngle, bool useCenter, Paint paint)
/// Rect来确认圆弧的位置, 开始的弧度、结束的弧度、是否使用中心点绘制(圆弧是否向中心闭合)、以及paint.
final center = new Offset(screenWitdh - 30, 0);
canvas.drawArc(new Rect.fromCircle(center: center, radius: size.width / 2), pi / 2, 2 * pi * 0.5, false, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => true;
}
class MyPainterBottomLeft extends CustomPainter {
final double screenWitdh;
final double screenHeight;
MyPainterBottomLeft(this.screenWitdh, this.screenHeight);
@override
void paint(Canvas canvas, Size size) {
Paint paint = Paint()
..isAntiAlias = true
..color = Color.fromRGBO(33, 255, 217, 1)
..strokeCap = StrokeCap.round
..strokeWidth = 100
..style = PaintingStyle.fill;
canvas.drawCircle(Offset(0, 200), 140, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => true;
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib/pages | mirrored_repositories/flutter-Anniversary/lib/pages/home/home.dart | import 'dart:io';
import 'package:daily/components/file_image.dart';
import 'package:daily/components/placeholder_image.dart';
import 'package:daily/model/img.dart';
import 'package:daily/model/daily.dart';
import 'package:daily/pages/about/about.dart';
import 'package:daily/pages/add/add.dart';
import 'package:daily/pages/detail/detail.dart';
import 'package:daily/pages/share/share.dart';
import 'package:daily/services/add_sevice.dart';
import 'package:daily/styles/colors.dart';
import 'package:daily/styles/iconfont.dart';
import 'package:daily/styles/text_style.dart';
import 'package:daily/utils/event_bus.dart';
import 'package:daily/utils/random_img.dart';
import 'package:daily/utils/sqlite_help.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:unicorndial/unicorndial.dart';
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> with TickerProviderStateMixin {
bool loading = false;
String imgPlaceHolder = '';
List<ImageModel> _imgList;
List<Daliy> _daliyList = [];
final sqlLiteHelper = SqlLiteHelper();
final DateFormat formatter = DateFormat('yyyy-MM-dd');
@override
void initState() {
loadAllformSqlite();
loadCategroyList();
bus.on('editSuccess', (arg) {
loadAllformSqlite();
});
super.initState();
}
// loadAll from sqflite
Future<void> loadAllformSqlite() async {
_daliyList = [];
await sqlLiteHelper.open();
_daliyList = await sqlLiteHelper.queryAll();
setState(() {});
}
// load category from netWork
Future<void> loadCategroyList() async {
loading = true;
List<ImageModel> res = await API.getData();
_imgList = res;
imgPlaceHolder = RandomImg.randomImg(_imgList);
loading = false;
setState(() {});
}
@override
Widget build(BuildContext context) {
// 首次加载,初始化一个daliy
if (_daliyList.length == 0 && !loading) {
final Daliy daliy = Daliy(
id: 0,
title: '欢迎来到时光',
headText: '这是你的第一个纪念日',
targetDay: formatter.format(DateTime.now()),
imageUrl: imgPlaceHolder,
remark: '''欢迎来到时光!
这是一款功能简洁的纪念日APP,你可以首页右下角的按钮,新增一个纪念日,赶紧体验起来吧~
祝福你的每个日子都开开心心!
''',
);
_daliyList.add(daliy);
setState(() {});
}
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle.dark,
child: Scaffold(
floatingActionButton: loading ? SizedBox() : _buildFoaltButton(context),
body: loading
? Center(child: SpinKitPumpingHeart(color: Colors.black))
: Container(
color: AppColors.homeBackGorundColor,
height: MediaQuery.of(context).size.height,
child: SingleChildScrollView(
child: Container(
padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top, bottom: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
buildTop(),
createListView(),
],
),
),
),
),
),
);
}
/// FloatingActionButton
Widget _buildFoaltButton(BuildContext context) {
final childButtons = List<UnicornButton>();
childButtons.add(UnicornButton(
hasLabel: false,
currentButton: FloatingActionButton(
mini: true,
heroTag: 'add',
backgroundColor: AppColors.homeBackGorundColor,
child: Icon(Icons.add_circle_outline, size: 30),
onPressed: () {
Navigator.push(
context,
PageRouteBuilder(
transitionDuration: Duration(milliseconds: 300),
pageBuilder: (BuildContext context, Animation animation, Animation secondaryAnimation) {
return ScaleTransition(
scale: animation,
alignment: Alignment.bottomRight,
child: AddNew(),
);
}),
).then((value) {
if (value) loadAllformSqlite();
});
},
)));
//TODO: 心愿
// childButtons.add(UnicornButton(
// hasLabel: false,
// currentButton: FloatingActionButton(
// mini: true,
// heroTag: 'wish',
// backgroundColor: AppColors.homeBackGorundColor,
// child: Icon(Iconfont.wish, size: 36),
// onPressed: () {
// showToast('努力更新中...');
// },
// )));
childButtons.add(UnicornButton(
hasLabel: false,
currentButton: FloatingActionButton(
mini: true,
heroTag: 'share',
backgroundColor: AppColors.homeBackGorundColor,
child: Icon(Iconfont.share, size: 24),
onPressed: () {
Navigator.push(
context,
PageRouteBuilder(
transitionDuration: Duration(milliseconds: 300),
pageBuilder: (BuildContext context, Animation animation, Animation secondaryAnimation) {
return ScaleTransition(
scale: animation,
alignment: Alignment.bottomRight,
child: ShareContentPost(bgUrl: _imgList[6].imgUrl, qrImageUrl: _imgList[7].imgUrl),
);
}),
);
},
)));
childButtons.add(UnicornButton(
hasLabel: false,
currentButton: FloatingActionButton(
mini: true,
heroTag: 'info',
backgroundColor: AppColors.homeBackGorundColor,
child: Icon(Icons.info_outline, size: 28),
onPressed: () {
Navigator.push(
context,
PageRouteBuilder(
transitionDuration: Duration(milliseconds: 300),
pageBuilder: (BuildContext context, Animation animation, Animation secondaryAnimation) {
return ScaleTransition(
scale: animation,
alignment: Alignment.bottomRight,
child: About(imgList: _imgList),
);
}),
);
},
)));
return UnicornDialer(
backgroundColor: Colors.black54.withOpacity(0.3),
parentButtonBackground: Colors.black,
orientation: UnicornOrientation.VERTICAL,
parentButton: Icon(Icons.menu),
childButtons: childButtons,
);
}
/// 顶部
Widget buildTop() {
return Padding(
padding: EdgeInsets.symmetric(vertical: 10, horizontal: 25),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Forever', style: AppTextStyles.appTitle),
Text('每一个平凡的日子,都值得纪念', style: AppTextStyles.appTip),
],
),
// SizedBox(height: 18),
// Text('每一个平凡的日子,都值得纪念', style: AppTextStyles.appTip),
],
),
);
}
/// 列表
Widget createListView() {
return MediaQuery.removePadding(
// 去除shrinkWrap产生的顶部padding
removeTop: true,
context: context,
child: ListView.builder(
itemCount: _daliyList.length,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return createItemView(index);
},
),
);
}
Widget createItemView(int index) {
var daliy = _daliyList[index];
var _animationController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 200),
);
var _animation = Tween<double>(begin: 1, end: 0.98).animate(_animationController);
return GestureDetector(
onPanDown: (details) {
_animationController.forward();
},
onPanCancel: () {
_animationController.reverse();
},
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) {
return HeroDetailPage(
daliy: daliy,
imgPlaceHolder: imgPlaceHolder,
);
},
fullscreenDialog: true,
));
},
child: Container(
height: 200,
margin: EdgeInsets.symmetric(horizontal: 30, vertical: 10),
child: ScaleTransition(
scale: _animation,
child: Hero(
tag: 'hero${daliy.id}',
child: Stack(
children: <Widget>[
Positioned.fill(
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(15)),
child: File(daliy.imageUrl).existsSync()
? FileImageFormPath(imgPath: daliy.imageUrl)
: PlaceHolderImage(imgUrl: imgPlaceHolder),
),
),
Padding(
padding: EdgeInsets.all(18),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(daliy.headText, style: AppTextStyles.headTextStyle),
Expanded(
child: Text(daliy.title, style: AppTextStyles.titleTextStyle),
),
Text(daliy.targetDay, style: AppTextStyles.targetDayStyle),
],
),
)
],
),
),
),
),
);
}
@override
bool get wantKeepAlive => true;
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib | mirrored_repositories/flutter-Anniversary/lib/components/file_image.dart | import 'dart:io';
import 'package:flutter/material.dart';
class FileImageFormPath extends StatelessWidget {
final String imgPath;
const FileImageFormPath({Key key, this.imgPath}) : super(key: key);
@override
Widget build(BuildContext context) {
return Image.file(
File(imgPath),
color: Colors.black.withOpacity(0.4),
fit: BoxFit.cover,
filterQuality: FilterQuality.low,
colorBlendMode: BlendMode.multiply,
);
}
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib | mirrored_repositories/flutter-Anniversary/lib/components/webview_page.dart | import 'package:daily/styles/colors.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
class WebViewPage extends StatefulWidget {
final String url;
final String title;
final bool autoGetTitle;
// 可以拿webviewcontroller
final ValueChanged<WebViewController> onWebViewCreated;
// 新url跳转时是否允许
final ValueChanged<NavigationRequest> navigationDelegate;
const WebViewPage(
{Key key, this.url, this.title, this.autoGetTitle = false, this.onWebViewCreated, this.navigationDelegate})
: super(key: key);
@override
_WebViewPageState createState() => _WebViewPageState();
}
class _WebViewPageState extends State<WebViewPage> with AutomaticKeepAliveClientMixin {
String title;
// 是否首次加载
bool _isFirstLoad = true;
WebViewController _controller;
@override
void initState() {
title = widget.title;
super.initState();
}
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
body: SafeArea(
child: Container(
color: Colors.white,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () => Navigator.pop(context, false),
child: Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left: 10),
child: Container(height: 30, width: 30, child: Icon(Icons.arrow_back, color: Colors.black)),
),
Container(width: MediaQuery.of(context).size.width - 70, child: Center(child: Text(title)))
],
),
),
Divider(),
Visibility(visible: _isFirstLoad, child: _progressIndicator()),
Expanded(child: _webview()),
],
),
),
),
);
}
WebView _webview() {
return WebView(
onWebViewCreated: (controller) {
_controller = controller;
widget.onWebViewCreated?.call(controller);
},
onPageFinished: _onPageFinished,
initialUrl: widget.url,
javascriptMode: JavascriptMode.unrestricted,
navigationDelegate: widget.navigationDelegate,
);
}
// 页面加载完成
_onPageFinished(String url) {
if (_isFirstLoad && widget.autoGetTitle) {
_getDocumentTiele();
}
setState(() => _isFirstLoad = false);
}
// 获取文档标题
_getDocumentTiele() {
_controller.getTitle().then((value) {
setState(() => title = value);
});
}
_progressIndicator() {
return SizedBox(
height: 2,
child: LinearProgressIndicator(
backgroundColor: Colors.black45,
valueColor: AlwaysStoppedAnimation(Colors.black45),
),
);
}
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib | mirrored_repositories/flutter-Anniversary/lib/components/custom_dialog.dart | import 'package:flutter/material.dart';
///自定义Dialog
class CustomDialog extends StatefulWidget {
//------------------不带图片的dialog------------------------
final String title; //弹窗标题
final TextStyle titleStyle; // 标题样式
final Widget content; //弹窗内容
final String confirmContent; //按钮文本
final String cancelContent; //取消按钮文本
final Color confirmTextColor; //确定按钮文本颜色
final bool isCancel; //是否有取消按钮,默认为false true:有 false:没有
final Color confirmColor; //确定按钮颜色
final Color cancelColor; //取消按钮颜色
final Color cancelTextColor; //取消按钮文本颜色
final bool outsideDismiss; //点击弹窗外部,关闭弹窗,默认为true true:可以关闭 false:不可以关闭
final Function confirmCallback; //点击确定按钮回调
final Function dismissCallback; //弹窗关闭回调
//------------------带图片的dialog------------------------
final String image; //dialog添加图片
final String imageHintText; //图片下方的文本提示
const CustomDialog({
Key key,
this.title,
this.content,
this.confirmContent,
this.confirmTextColor,
this.isCancel = true,
this.confirmColor,
this.cancelColor,
this.outsideDismiss = false,
this.confirmCallback,
this.dismissCallback,
this.image,
this.imageHintText,
this.titleStyle,
this.cancelContent,
this.cancelTextColor,
}) : super(key: key);
@override
State<StatefulWidget> createState() {
return _CustomDialogState();
}
}
class _CustomDialogState extends State<CustomDialog> {
_confirmDialog() {
/// 根据返回的索引做判断
Navigator.of(context).pop(1);
Future.delayed(Duration(milliseconds: 250), () {
if (widget.confirmCallback != null) {
widget.confirmCallback();
}
});
}
_dismissDialog() {
/// 根据返回的索引做判断
Navigator.of(context).pop(0);
Future.delayed(Duration(milliseconds: 250), () {
if (widget.dismissCallback != null) {
widget.dismissCallback();
}
});
}
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
final width = size.width;
Column _columnText = Column(
children: <Widget>[
SizedBox(height: widget.title == null ? 0 : 15.0),
// 头部title
Container(
height: 60,
child: Text(
widget.title == null ? '' : widget.title,
style: widget.titleStyle,
),
),
// 中间内容
Container(
height: 100,
child: Center(
child: widget.content,
),
),
SizedBox(height: 0.5, child: Container(color: Color(0xDBDBDBDB))),
// 底部按钮
Container(
height: 55,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Expanded(
child: widget.isCancel
? Container(
height: 55,
decoration: BoxDecoration(
color: widget.cancelColor == null ? Color(0xFFFFFFFF) : widget.cancelColor,
borderRadius: BorderRadius.only(bottomLeft: Radius.circular(16.0))),
child: FlatButton(
child: Text(widget.cancelContent == null ? '取消' : widget.cancelContent,
style: TextStyle(
fontSize: 14.0,
fontWeight: FontWeight.w100,
fontFamily: 'Dongqing',
color: widget.cancelColor == null
? (widget.cancelTextColor == null ? Colors.black87 : widget.cancelTextColor)
: Color(0xFFFFFFFF),
)),
onPressed: _dismissDialog,
splashColor: widget.cancelColor == null ? Color(0xFFFFFFFF) : widget.cancelColor,
highlightColor: widget.cancelColor == null ? Color(0xFFFFFFFF) : widget.cancelColor,
),
)
: Text(''),
flex: widget.isCancel ? 1 : 0,
),
SizedBox(width: widget.isCancel ? 1.0 : 0, child: Container(color: Color(0xDBDBDBDB))),
Expanded(
child: Container(
height: 55,
decoration: BoxDecoration(
color: widget.confirmColor == null ? Color(0xFFFFFFFF) : widget.confirmColor,
borderRadius: widget.isCancel
? BorderRadius.only(bottomRight: Radius.circular(16.0))
: BorderRadius.only(bottomLeft: Radius.circular(16.0), bottomRight: Radius.circular(16.0)),
),
child: FlatButton(
onPressed: _confirmDialog,
child: Text(widget.confirmContent == null ? '确定' : widget.confirmContent,
style: TextStyle(
fontSize: 14.0,
fontWeight: FontWeight.w100,
fontFamily: 'Dongqing',
color: widget.confirmColor == null
? (widget.confirmTextColor == null ? Colors.black87 : widget.confirmTextColor)
: Color(0xFFFFFFFF),
)),
splashColor: widget.confirmColor == null ? Color(0xFFFFFFFF) : widget.confirmColor,
highlightColor: widget.confirmColor == null ? Color(0xFFFFFFFF) : widget.confirmColor,
),
),
flex: 1),
],
),
)
],
);
Column _columnImage = Column(
children: <Widget>[
SizedBox(
height: widget.imageHintText == null ? 35.0 : 23.0,
),
Image(image: AssetImage(widget.image == null ? '' : widget.image), width: 72.0, height: 72.0),
SizedBox(height: 10.0),
Text(widget.imageHintText == null ? "" : widget.imageHintText, style: TextStyle(fontSize: 16.0)),
],
);
/// 路由拦截
return WillPopScope(
child: GestureDetector(
onTap: () => {widget.outsideDismiss ? _dismissDialog() : null},
child: Material(
type: MaterialType.transparency,
child: Center(
child: Container(
width: widget.image == null ? width - 100.0 : width - 150.0,
height: 231.0,
alignment: Alignment.center,
child: widget.image == null ? _columnText : _columnImage,
decoration: BoxDecoration(color: Color(0xFFFFFFFF), borderRadius: BorderRadius.circular(16.0)),
),
),
),
),
onWillPop: () async {
return widget.outsideDismiss;
});
}
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib | mirrored_repositories/flutter-Anniversary/lib/components/placeholder_image.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
class PlaceHolderImage extends StatelessWidget {
final String imgUrl;
const PlaceHolderImage({Key key, this.imgUrl}) : super(key: key);
@override
Widget build(BuildContext context) {
return CachedNetworkImage(
color: Colors.black.withOpacity(0.4),
imageUrl: imgUrl,
errorWidget: (context, url, error) => Icon(Icons.error),
fit: BoxFit.cover,
filterQuality: FilterQuality.low,
colorBlendMode: BlendMode.multiply,
);
}
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib | mirrored_repositories/flutter-Anniversary/lib/components/bottom_button.dart | import 'package:daily/styles/colors.dart';
import 'package:flutter/material.dart';
class BottomButton extends StatelessWidget {
final String text;
final double height;
final Function handleOk;
const BottomButton({Key key, this.handleOk, this.text, this.height}) : super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => handleOk(),
child: Container(
margin: EdgeInsets.only(
bottom: MediaQuery.of(context).padding.bottom,
left: 10,
right: 10,
),
height: height,
decoration: BoxDecoration(
color: AppColors.buttonPrimary,
// gradient: LinearGradient(
// //背景径向渐变
// colors: [AppColors.buttonLine1, AppColors.buttonLine2],
// ),
borderRadius: BorderRadius.circular(20.0),
),
child: Center(
child: Text(
text,
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib | mirrored_repositories/flutter-Anniversary/lib/config/config.dart | // 开发环境
import '../env.dart';
const SERVER_HOST_DEV = 'http://xieyezi.com:9003/mock/9/daily';
// 生产环境
const SERVER_HOST_PROD = 'http://xieyezi.com:9003/mock/9/daily';
const SERVER_API_URL = ENV == "DEV" ? SERVER_HOST_DEV : SERVER_HOST_PROD;
| 0 |
mirrored_repositories/flutter-Anniversary/lib | mirrored_repositories/flutter-Anniversary/lib/model/daily.dart | class Daliy {
int id;
String title;
String headText;
String targetDay;
String imageUrl;
String remark;
Daliy({
this.id,
this.title,
this.headText,
this.targetDay,
this.imageUrl,
this.remark,
});
// Convert a Daliy into a Map. The keys must correspond to the names of the
// columns in the database.
Map<String, dynamic> toMap() {
return {
'id': id,
'title': title,
'headText': headText,
'targetDay': targetDay,
'imageUrl': imageUrl,
'remark': remark,
};
}
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib | mirrored_repositories/flutter-Anniversary/lib/model/img.dart | // To parse this JSON data, do
//
// final ImageModel = ImageModelFromJson(jsonString);
import 'dart:convert';
List<ImageModel> imageModelFromJson(String str) =>
List<ImageModel>.from(json.decode(str).map((x) => ImageModel.fromJson(x)));
String imageModelToJson(List<ImageModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class ImageModel {
ImageModel({
this.name,
this.imgUrl,
});
String name;
String imgUrl;
factory ImageModel.fromJson(Map<String, dynamic> json) => ImageModel(
name: json["name"],
imgUrl: json["imgUrl"],
);
Map<String, dynamic> toJson() => {
"name": name,
"imgUrl": imgUrl,
};
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib | mirrored_repositories/flutter-Anniversary/lib/styles/text_style.dart | import 'dart:ui';
import 'package:flutter/material.dart';
class AppTextStyles {
/// APP Title
static const TextStyle appTitle = TextStyle(
decoration: TextDecoration.none,
fontSize: 30,
color: Colors.black87,
fontWeight: FontWeight.bold,
fontFamily: 'Conspired',
);
/// APP Welcome
static const TextStyle appTip = TextStyle(
fontSize: 14,
decoration: TextDecoration.none,
color: Colors.black54,
fontWeight: FontWeight.w100,
fontFamily: 'Dongqing',
);
/// Daily title
static const TextStyle titleTextStyle = TextStyle(
fontSize: 30,
color: Colors.white,
decoration: TextDecoration.none,
fontFamily: 'Dongqing',
);
/// Daily headText
static const TextStyle headTextStyle = TextStyle(
fontSize: 16,
color: Colors.white,
decoration: TextDecoration.none,
fontFamily: 'Dongqing',
);
/// Daily targetDay
static const TextStyle targetDayStyle = TextStyle(
fontSize: 16,
color: Colors.white,
decoration: TextDecoration.none,
fontFamily: 'Dongqing',
);
/// (Daily countYear countMonth countDay countTotalDay) Title
static const TextStyle countTitleStyle = TextStyle(
fontSize: 24,
color: Colors.white,
fontWeight: FontWeight.w500,
decoration: TextDecoration.none,
fontFamily: 'Dongqing',
);
/// (Daily countYear countMonth countDay countTotalDay) BottomTip
static const TextStyle countBottomTipStyle = TextStyle(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.w200,
decoration: TextDecoration.none,
fontFamily: 'Dongqing',
);
/// (Daily detail Content) BottomTip
static const TextStyle contentStyle = TextStyle(
height: 1.5,
fontSize: 16,
letterSpacing: 1.0,
color: Color(0xFF666666),
fontWeight: FontWeight.w200,
fontFamily: 'Dongqing',
);
/// (Daily add Input label) label
static const TextStyle inputLabelStyle = TextStyle(
fontSize: 16,
color: Color(0xFF333333),
decoration: TextDecoration.none,
fontWeight: FontWeight.w100,
fontFamily: 'Dongqing',
);
/// (Daily add Input hint) hint
static const TextStyle inputHintStyle = TextStyle(
fontSize: 15,
color: Color(0xFF666666),
decoration: TextDecoration.none,
fontFamily: 'Dongqing',
);
/// (Daily add Input value) value
static const TextStyle inputValueStyle = TextStyle(
fontSize: 16,
color: Color(0xFF333333),
decoration: TextDecoration.none,
fontFamily: 'Dongqing',
);
/// (Daily add Select cateGoryText) cateGoryText
static const TextStyle cateGoryTextStyle = TextStyle(
fontSize: 24,
color: Colors.white,
fontWeight: FontWeight.w100,
fontFamily: 'Dongqing',
);
/// (Daily add Select dateSelect) dateSelect
static const TextStyle dateSelectStyle = TextStyle(
fontWeight: FontWeight.w400,
fontSize: 12,
color: Colors.black,
);
/// Daily chooseImage
static const TextStyle chooseImageStyle = TextStyle(
fontSize: 14,
color: Colors.white,
decoration: TextDecoration.none,
fontWeight: FontWeight.w200,
fontFamily: 'Dongqing',
);
/// Daily delete
static const TextStyle deleteStyle = TextStyle(
color: Color(0xFF333333),
fontSize: 14,
decoration: TextDecoration.none,
fontWeight: FontWeight.w100,
fontFamily: 'Dongqing',
);
/// Daily about
static const TextStyle aboutStyle = TextStyle(
color: Color(0xFF333333),
fontSize: 14,
decoration: TextDecoration.none,
fontWeight: FontWeight.w100,
fontFamily: 'Dongqing',
);
/// Daily about
static const TextStyle aboutMiddleStyle = TextStyle(
color: Color(0xFF333333),
fontSize: 16,
decoration: TextDecoration.none,
fontWeight: FontWeight.w100,
fontFamily: 'Dongqing',
);
/// Daily about
static const TextStyle aboutBottomStyle = TextStyle(
color: Color(0xFF333333),
fontSize: 12,
decoration: TextDecoration.none,
fontWeight: FontWeight.w100,
fontFamily: 'Dongqing',
);
/// Daily share
static const TextStyle shareTitleStyle = TextStyle(
color: Color(0xFF333333),
fontSize: 16,
decoration: TextDecoration.none,
fontWeight: FontWeight.w400,
fontFamily: 'Dongqing',
);
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib | mirrored_repositories/flutter-Anniversary/lib/styles/iconfont.dart | import 'package:flutter/material.dart';
class Iconfont {
// iconName:share
static const share = IconData(
0xe63e,
fontFamily: 'Iconfont',
matchTextDirection: true,
);
// iconName: daily
static const daily = IconData(
0xe6bc,
fontFamily: 'Iconfont',
matchTextDirection: true,
);
// iconName: up1
static const up1 = IconData(
0xe696,
fontFamily: 'Iconfont',
matchTextDirection: true,
);
// iconName: up2
static const up2 = IconData(
0xe603,
fontFamily: 'Iconfont',
matchTextDirection: true,
);
// iconName: down1
static const down1 = IconData(
0xe687,
fontFamily: 'Iconfont',
matchTextDirection: true,
);
// iconName: down2
static const down2 = IconData(
0xe65c,
fontFamily: 'Iconfont',
matchTextDirection: true,
);
// iconName: clock
static const clock = IconData(
0xe60f,
fontFamily: 'Iconfont',
matchTextDirection: true,
);
// iconName: wish
static const wish = IconData(
0xe656,
fontFamily: 'Iconfont',
matchTextDirection: true,
);
// iconName: comfirm
static const comfirm = IconData(
0xe647,
fontFamily: 'Iconfont',
matchTextDirection: true,
);
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib | mirrored_repositories/flutter-Anniversary/lib/styles/colors.dart | import 'dart:ui';
import 'package:flutter/material.dart';
class AppColors {
/// Home backGorundColor
static const Color homeBackGorundColor = Color.fromRGBO(189, 195, 199, 0.06);
/// Detail backGorundColor
static const Color detailBackGorundColor = Color.fromRGBO(189, 195, 199, 0.06);
/// Button
static Color buttonPrimary = Colors.black;
/// Add backGorundColor
static const Color addBackGorundColor = Color.fromRGBO(189, 195, 199, 0.06);
/// DateSelect
static Color dateSelectBackGorundColor = Colors.grey[100];
/// dateSelectHlight
static Color dateSelectHlight = Colors.black;
/// cateGroySelect
static Color cateGroySelectBackGorundColor = Colors.grey[200];
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib | mirrored_repositories/flutter-Anniversary/lib/utils/request.dart | import 'dart:async';
import 'package:daily/config/config.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
/*
* 请求 操作类
* 单例模式
* 手册
* https://github.com/flutterchina/dio/blob/master/README-ZH.md
*
*/
class RequestUtil {
static RequestUtil _instance = RequestUtil._internal();
factory RequestUtil() => _instance;
Dio dio;
RequestUtil._internal() {
// BaseOptions、Options、RequestOptions 都可以配置参数,优先级别依次递增,且可以根据优先级别覆盖参数
BaseOptions options = new BaseOptions(
// 请求基地址,可以包含子路径
baseUrl: SERVER_API_URL,
//连接服务器超时时间,单位是毫秒.
connectTimeout: 10000,
// 响应流上前后两次接受到数据的间隔,单位为毫秒。
receiveTimeout: 5000,
// Http请求头.
headers: {},
/// 请求的Content-Type,默认值是"application/json; charset=utf-8".
/// 如果您想以"application/x-www-form-urlencoded"格式编码请求数据,
/// 可以设置此选项为 `Headers.formUrlEncodedContentType`, 这样[Dio]
/// 就会自动编码请求体.
contentType: 'application/json; charset=utf-8',
/// [responseType] 表示期望以那种格式(方式)接受响应数据。
/// 目前 [ResponseType] 接受三种类型 `JSON`, `STREAM`, `PLAIN`.
///
/// 默认值是 `JSON`, 当响应头中content-type为"application/json"时,dio 会自动将响应内容转化为json对象。
/// 如果想以二进制方式接受响应数据,如下载一个二进制文件,那么可以使用 `STREAM`.
///
/// 如果想以文本(字符串)格式接收响应数据,请使用 `PLAIN`.
responseType: ResponseType.json,
);
dio = new Dio(options);
// 添加拦截器
dio.interceptors.add(InterceptorsWrapper(onRequest: (RequestOptions options) {
// 在请求被发送之前做一些事情
return options; //continue
}, onResponse: (Response response) {
// 在返回响应数据之前做一些预处理
return response; // continue
}, onError: (DioError e) {
// 当请求失败时做一些预处理
return createErrorEntity(e);
}));
}
/*
* 获取token
*/
getAuthorizationHeader() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getInt('token');
}
/// get 操作
Future get(
String path, {
dynamic params,
Options options,
}) async {
try {
Options requestOptions = options ?? Options();
/// 以下三行代码为获取token然后将其合并到header的操作
Map<String, dynamic> _authorization = {"token": getAuthorizationHeader()};
if (_authorization != null) {
requestOptions = requestOptions.merge(headers: _authorization);
}
var response = await dio.get(
path,
queryParameters: params,
options: requestOptions,
);
return response.data;
} on DioError catch (e) {
throw createErrorEntity(e);
}
}
/// post 操作
Future post(String path, {dynamic params, Options options}) async {
Options requestOptions = options ?? Options();
/// 以下三行代码为获取token然后将其合并到header的操作
// Map<String, dynamic> _authorization = getAuthorizationHeader();
// if (_authorization != null) {
// requestOptions = requestOptions.merge(headers: _authorization);
// }
var response = await dio.post(path, data: params, options: requestOptions);
return response.data;
}
/// put 操作
Future put(String path, {dynamic params, Options options}) async {
Options requestOptions = options ?? Options();
/// 以下三行代码为获取token然后将其合并到header的操作
// Map<String, dynamic> _authorization = getAuthorizationHeader();
// if (_authorization != null) {
// requestOptions = requestOptions.merge(headers: _authorization);
// }
var response = await dio.put(path, data: params, options: requestOptions);
return response.data;
}
/// patch 操作
Future patch(String path, {dynamic params, Options options}) async {
Options requestOptions = options ?? Options();
/// 以下三行代码为获取token然后将其合并到header的操作
// Map<String, dynamic> _authorization = getAuthorizationHeader();
// if (_authorization != null) {
// requestOptions = requestOptions.merge(headers: _authorization);
// }
var response = await dio.patch(path, data: params, options: requestOptions);
return response.data;
}
/// delete 操作
Future delete(String path, {dynamic params, Options options}) async {
Options requestOptions = options ?? Options();
/// 以下三行代码为获取token然后将其合并到header的操作
// Map<String, dynamic> _authorization = getAuthorizationHeader();
// if (_authorization != null) {
// requestOptions = requestOptions.merge(headers: _authorization);
// }
var response = await dio.delete(path, data: params, options: requestOptions);
return response.data;
}
/// post form 表单提交操作
Future postForm(String path, {dynamic params, Options options}) async {
Options requestOptions = options ?? Options();
/// 以下三行代码为获取token然后将其合并到header的操作
// Map<String, dynamic> _authorization = getAuthorizationHeader();
// if (_authorization != null) {
// requestOptions = requestOptions.merge(headers: _authorization);
// }
var response = await dio.post(path, data: FormData.fromMap(params), options: requestOptions);
return response.data;
}
}
/*
* error统一处理
*/
// 错误信息
ErrorEntity createErrorEntity(DioError error) {
switch (error.type) {
case DioErrorType.CANCEL:
{
return ErrorEntity(code: -1, message: "请求取消");
}
break;
case DioErrorType.CONNECT_TIMEOUT:
{
return ErrorEntity(code: -1, message: "连接超时");
}
break;
case DioErrorType.SEND_TIMEOUT:
{
return ErrorEntity(code: -1, message: "请求超时");
}
break;
case DioErrorType.RECEIVE_TIMEOUT:
{
return ErrorEntity(code: -1, message: "响应超时");
}
break;
case DioErrorType.RESPONSE:
{
try {
int errCode = error.response.statusCode;
// String errMsg = error.response.statusMessage;
// return ErrorEntity(code: errCode, message: errMsg);
switch (errCode) {
case 400:
{
return ErrorEntity(code: errCode, message: "请求语法错误");
}
break;
case 401:
{
return ErrorEntity(code: errCode, message: "没有权限");
}
break;
case 403:
{
return ErrorEntity(code: errCode, message: "服务器拒绝执行");
}
break;
case 404:
{
return ErrorEntity(code: errCode, message: "无法连接服务器");
}
break;
case 405:
{
return ErrorEntity(code: errCode, message: "请求方法被禁止");
}
break;
case 500:
{
return ErrorEntity(code: errCode, message: "服务器内部错误");
}
break;
case 502:
{
return ErrorEntity(code: errCode, message: "无效的请求");
}
break;
case 503:
{
return ErrorEntity(code: errCode, message: "服务器挂了");
}
break;
case 505:
{
return ErrorEntity(code: errCode, message: "不支持HTTP协议请求");
}
break;
default:
{
// return ErrorEntity(code: errCode, message: "未知错误");
return ErrorEntity(code: errCode, message: error.response.statusMessage);
}
}
} on Exception catch (_) {
return ErrorEntity(code: -1, message: "未知错误");
}
}
break;
default:
{
return ErrorEntity(code: -1, message: error.message);
}
}
}
// 异常处理
class ErrorEntity implements Exception {
int code;
String message;
ErrorEntity({this.code, this.message});
String toString() {
if (message == null) return "Exception";
return "Exception: code $code, $message";
}
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib | mirrored_repositories/flutter-Anniversary/lib/utils/random_img.dart | import 'dart:math';
import 'package:daily/model/img.dart';
class RandomImg {
static String randomImg(List<ImageModel> imgList) {
var random = new Random();
return imgList[random.nextInt(imgList.length - 3)].imgUrl;
}
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib | mirrored_repositories/flutter-Anniversary/lib/utils/event_bus.dart | //订阅者回调签名
typedef void EventCallback(arg);
class EventBus {
//私有构造函数
EventBus._internal();
//保存单例
static EventBus _singleton = new EventBus._internal();
//工厂构造函数
factory EventBus() => _singleton;
//保存事件订阅者队列,key:事件名(id),value: 对应事件的订阅者队列
var _emap = new Map<Object, List<EventCallback>>();
//添加订阅者
void on(eventName, EventCallback f) {
if (eventName == null || f == null) return;
_emap[eventName] ??= new List<EventCallback>();
_emap[eventName].add(f);
}
//移除订阅者
void off(eventName, [EventCallback f]) {
var list = _emap[eventName];
if (eventName == null || list == null) return;
if (f == null) {
_emap[eventName] = null;
} else {
list.remove(f);
}
}
//触发事件,事件触发后该事件所有订阅者会被调用
void emit(eventName, [arg]) {
var list = _emap[eventName];
if (list == null) return;
int len = list.length - 1;
//反向遍历,防止订阅者在回调中移除自身带来的下标错位
for (var i = len; i > -1; --i) {
list[i](arg);
}
}
}
//定义一个top-level(全局)变量,页面引入该文件后可以直接使用bus
var bus = new EventBus();
| 0 |
mirrored_repositories/flutter-Anniversary/lib | mirrored_repositories/flutter-Anniversary/lib/utils/utils.dart | class Utils {}
| 0 |
mirrored_repositories/flutter-Anniversary/lib | mirrored_repositories/flutter-Anniversary/lib/utils/sqlite_help.dart | import 'package:daily/model/daily.dart';
import 'package:sqflite/sqflite.dart';
class SqlLiteHelper {
final sqlFileName = 'db.daily';
final dailyTable = 'daily_cache';
Database db;
// 开启数据库
Future<void> open() async {
String path = "${await getDatabasesPath()}/$sqlFileName";
print(path);
if (db == null) {
db = await openDatabase(path, version: 1, onCreate: (db, ver) async {
await db.execute('''
Create Table daily_cache(
id integer primary key autoincrement,
title text,
headText text,
targetDay text,
imageUrl text,
remark text
);
''');
});
}
}
// inert
Future<void> insert(Daliy daliy) async {
await db.insert(
dailyTable,
daliy.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
// queryAll
Future<List<Daliy>> queryAll() async {
final List<Map<String, dynamic>> maps = await db.query(dailyTable);
return List.generate(maps.length, (i) {
return Daliy(
id: maps[i]['id'],
title: maps[i]['title'],
headText: maps[i]['headText'],
targetDay: maps[i]['targetDay'],
imageUrl: maps[i]['imageUrl'],
remark: maps[i]['remark'],
);
});
}
// update
Future<void> update(Daliy daliy) async {
await db.update(
dailyTable,
daliy.toMap(),
where: "id = ?",
whereArgs: [daliy.id],
);
}
// delete
Future<void> delete(Daliy daliy) async {
await db.delete(
dailyTable,
where: "id = ?",
whereArgs: [daliy.id],
);
}
}
| 0 |
mirrored_repositories/flutter-Anniversary/lib | mirrored_repositories/flutter-Anniversary/lib/services/add_sevice.dart | import 'package:daily/model/img.dart';
import 'package:daily/utils/request.dart';
class API {
/// imgList
static Future<List<ImageModel>> getData() async {
var response = await RequestUtil().get('/category_list');
return imageModelFromJson(response);
}
}
| 0 |
mirrored_repositories/flutter-Anniversary | mirrored_repositories/flutter-Anniversary/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:daily/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/Skysoft_Taxi | mirrored_repositories/Skysoft_Taxi/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:just_audio_background/just_audio_background.dart';
import 'package:skysoft_taxi/screen/xanh_sm_clone_User/login_screen.dart';
import 'package:skysoft_taxi/util/notification_controller.dart';
void main() async {
await NotificationController.initializeLocalNotifications();
await JustAudioBackground.init(
androidNotificationChannelId: 'com.ryanheise.bg_demo.channel.audio',
androidNotificationChannelName: 'Audio playback',
androidNotificationOngoing: true,
);
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
static final GlobalKey<NavigatorState> navigatorKey =
GlobalKey<NavigatorState>();
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
NotificationController.startListeningNotificationEvents();
super.initState();
}
@override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations(
[
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
],
);
return MaterialApp(
navigatorKey: MyApp.navigatorKey,
debugShowCheckedModeBanner: false,
title: 'SKYSOFT Map',
home: const LoginScreen());
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/global/global.dart | import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import '../models/user.model.dart';
import '../services/WebSocketService.dart';
import '../url/contants.dart';
class GlobalData {
static final GlobalData _instance = GlobalData._internal();
factory GlobalData() {
return _instance;
}
GlobalData._internal();
UserModel driverModel = UserModel(
role: "TX",
status: Status.NORMAL,
name: "",
description: "",
type: "",
);
UserModel userModel = UserModel(
role: "ND", status: Status.NORMAL, name: "", description: "", type: "");
}
UserModel driverModel = GlobalData().driverModel;
UserModel userModel = GlobalData().userModel;
// kết nối bộ đàm bluetooth
BluetoothConnection? connection;
WebSocketService webSocketService = WebSocketService(url: URL_WS);
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/url/contants.dart | // final String URL_WS2 = "ws://172.20.10.5:8887/ws/chat?";
// final String URL_WS3 = "ws://192.168.1.4:8888/ws/chat?";
// ignore_for_file: constant_identifier_names
const String URL_WS4 = "ws://192.168.1.75:8081/product/ws/chat-voice?";
const String URL_CHAT_UPLOAD =
"http://192.168.1.75:8081/product/rest/chat/upload";
const String URL_CHAT_GETALL =
"http://192.168.1.75:8081/product/rest/chat/getAll";
const String URL_CHAT_VOICE = "http://192.168.1.75:8081/product/rest/chat/";
const String URL_WS = URL_WS4;
const String URL_CHAT = URL_CHAT_VOICE;
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/view/message_view.dart | class MessageView {
bool rightSide;
String content;
int type;
bool tag;
bool favorite;
DateTime time;
bool autoPlay;
MessageView({
required this.content,
this.rightSide = true,
this.type = 1,
this.tag = false,
this.favorite = false,
this.autoPlay = false,
DateTime? time, // Sử dụng DateTime? để đánh dấu là tham số có thể null
}) : time = time ??
DateTime.now(); // Sử dụng null-aware operator để xử lý giá trị null
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/widgets/history_widget.dart | import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class HistoryWidget extends StatefulWidget {
final IconData iconLeft;
final String text;
final VoidCallback onTap;
final bool isLast;
const HistoryWidget({
required this.iconLeft,
required this.text,
required this.onTap,
this.isLast = false,
Key? key,
}) : super(key: key);
@override
State<HistoryWidget> createState() => _HistoryWidgetState();
}
class _HistoryWidgetState extends State<HistoryWidget> {
String getCurrentTime() {
return DateFormat('HH:mm').format(DateTime.now());
}
String getCurrentDate() {
return DateFormat('dd/MM/yyyy').format(DateTime.now());
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: widget.onTap,
child: Container(
margin: const EdgeInsets.only(bottom: 10),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(15),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ListTile(
contentPadding: const EdgeInsets.all(5),
leading: Icon(
widget.iconLeft,
size: 25,
color: Colors.blueGrey,
),
title: Text(
widget.text,
style: const TextStyle(
fontSize: 15,
color: Colors.black,
fontWeight: FontWeight.normal,
),
overflow: TextOverflow.ellipsis,
maxLines: 2,
),
subtitle: Text(
'${getCurrentTime()} - ${getCurrentDate()}',
style: const TextStyle(
fontSize: 12,
color: Colors.grey,
fontWeight: FontWeight.normal,
),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
onTap: widget.onTap,
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/widgets/destination_header.dart | import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:skysoft_taxi/screen/xanh_sm_clone_User/tim_diem_den%20_nhanh.dart';
class DestinationHeader extends StatefulWidget {
final TextEditingController pickupController;
final TextEditingController destinationController;
final void Function() onBack;
const DestinationHeader({
Key? key,
required this.pickupController,
required this.destinationController,
required this.onBack,
required Null Function() navigateToQuickFindPlaces,
}) : super(key: key);
@override
State<DestinationHeader> createState() => _DestinationHeaderState();
}
class _DestinationHeaderState extends State<DestinationHeader> {
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 10),
child: Row(
children: [
IconButton(
icon: const Icon(
Icons.arrow_back_ios,
color: Colors.black,
size: 20,
),
onPressed: widget.onBack,
),
const Text(
'Chọn điểm đến ',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 16,
),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
],
),
),
const SizedBox(height: 5),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
color: Colors.grey.shade200,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 7,
offset: const Offset(0, 3),
),
],
),
child: Column(
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
color: Colors.white,
),
child: Padding(
padding: const EdgeInsets.all(5),
child: Column(
children: <Widget>[
buildTextField(
controller: widget.pickupController,
prefixIcon: const Icon(
Icons.boy,
color: Colors.blue,
),
hintText: 'Nhập điểm đón ...',
),
const Divider(
thickness: 1,
color: Colors.cyan,
indent: 20,
endIndent: 20,
),
buildTextField(
controller: widget.destinationController,
prefixIcon: const Icon(
Icons.location_on,
color: Colors.orangeAccent,
),
hintText: 'Nhập điểm đến ...',
),
],
),
),
),
SizedBox(
height: 44,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
buildIconContainer(
icon: const Icon(Icons.map),
text: 'Chọn điểm đến',
),
],
),
),
],
),
),
],
);
}
Widget buildTextField({
required TextEditingController controller,
required Icon prefixIcon,
required String hintText,
}) {
return TextField(
controller: controller,
onChanged: (text) {
setState(() {});
},
decoration: InputDecoration(
prefixIcon: prefixIcon,
hintText: hintText,
border: InputBorder.none,
suffixIcon: controller.text.isNotEmpty
? GestureDetector(
onTap: () {
controller.clear();
setState(() {});
},
child: const Icon(Icons.clear),
)
: null,
),
);
}
Widget buildIconContainer({required Icon icon, required String text}) {
return GestureDetector(
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const QuickFindPlaces();
},
),
);
},
child: Row(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Icon(
icon.icon,
color: Colors.black,
size: 20,
),
),
Text(
text,
style: const TextStyle(
color: Colors.black,
fontSize: 14,
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/widgets/menu_widget_profile.dart | import 'package:flutter/material.dart';
class MenuWidget extends StatefulWidget {
final IconData iconLeft;
final String text;
final IconData iconRight;
final VoidCallback onTap;
final bool isLast;
const MenuWidget({
required this.iconLeft,
required this.text,
required this.iconRight,
required this.onTap,
this.isLast = false,
Key? key,
}) : super(key: key);
@override
State<MenuWidget> createState() => _MenuWidgetState();
}
class _MenuWidgetState extends State<MenuWidget> {
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: widget.onTap,
child: Container(
padding: const EdgeInsetsDirectional.all(15),
decoration: BoxDecoration(
border: widget.isLast
? null
: Border(
bottom: BorderSide(
color: Colors.grey.shade200,
width: 0.5,
),
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Icon(
widget.iconLeft,
size: 20,
color: Colors.blueGrey,
),
const SizedBox(width: 10),
Text(
widget.text,
style: const TextStyle(
fontSize: 16,
color: Colors.black,
fontWeight: FontWeight.normal,
),
),
],
),
Icon(
widget.iconRight,
size: 20,
color: Colors.black,
),
],
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/widgets | mirrored_repositories/Skysoft_Taxi/lib/widgets/imageWidget/banner_image.dart | import 'package:flutter/material.dart';
class BannerImage extends StatefulWidget {
final String imageUrl;
const BannerImage({Key? key, required this.imageUrl}) : super(key: key);
@override
State<BannerImage> createState() => _BannerImageState();
}
class _BannerImageState extends State<BannerImage> {
@override
Widget build(BuildContext context) {
return Positioned.fill(
child: Image.network(
widget.imageUrl,
fit: BoxFit.cover,
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/widgets | mirrored_repositories/Skysoft_Taxi/lib/widgets/imageWidget/slide_image_horizontal.dart | import 'dart:async';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
class HorizontalImageSlider extends StatefulWidget {
final List<String> imageUrls;
const HorizontalImageSlider({super.key, required this.imageUrls});
@override
// ignore: library_private_types_in_public_api
_HorizontalImageSliderState createState() => _HorizontalImageSliderState();
}
class _HorizontalImageSliderState extends State<HorizontalImageSlider> {
late PageController _pageController;
int _currentPage = 0;
@override
void initState() {
super.initState();
_pageController = PageController();
_startAutoSlide();
}
@override
void dispose() {
_pageController.dispose();
super.dispose();
}
void _startAutoSlide() {
Timer.periodic(
const Duration(seconds: 2),
(timer) {
if (_currentPage < widget.imageUrls.length - 1) {
_currentPage++;
} else {
_currentPage = 0;
}
if (_pageController.hasClients) {
_pageController.animateToPage(
_currentPage,
duration: const Duration(milliseconds: 500),
curve: Curves.easeInOut,
);
}
},
);
}
@override
Widget build(BuildContext context) {
return SizedBox(
height: 250.0,
child: PageView.builder(
physics: const BouncingScrollPhysics(),
controller: _pageController,
itemCount: widget.imageUrls.length,
onPageChanged: (index) {
setState(() {
_currentPage = index;
});
},
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 25),
child: ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: CachedNetworkImage(
imageUrl: widget.imageUrls[index],
placeholder: (context, url) =>
const CircularProgressIndicator(),
errorWidget: (context, url, error) => const Icon(Icons.error),
fit: BoxFit.cover,
),
),
);
},
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/widgets | mirrored_repositories/Skysoft_Taxi/lib/widgets/imageWidget/logo_login_page.dart | import 'package:flutter/material.dart';
class LogoImage extends StatefulWidget {
final String imageUrl;
const LogoImage({super.key, required this.imageUrl});
@override
// ignore: library_private_types_in_public_api
_LogoImageState createState() => _LogoImageState();
}
class _LogoImageState extends State<LogoImage> {
@override
Widget build(BuildContext context) {
return FittedBox(
fit: BoxFit.contain,
child: Image.network(
widget.imageUrl,
width: 120,
height: 120,
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/widgets | mirrored_repositories/Skysoft_Taxi/lib/widgets/imageWidget/circular_image_widget.dart | import 'package:flutter/material.dart';
class CircularImageWidget extends StatefulWidget {
final String imageUrl;
const CircularImageWidget({Key? key, required this.imageUrl})
: super(key: key);
@override
// ignore: library_private_types_in_public_api
_CircularImageWidgetState createState() => _CircularImageWidgetState();
}
class _CircularImageWidgetState extends State<CircularImageWidget> {
@override
Widget build(BuildContext context) {
double screenHeight = MediaQuery.of(context).size.height;
return SizedBox(
height: screenHeight / 12,
child: ClipOval(
child: Image.network(
widget.imageUrl,
fit: BoxFit.cover,
),
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/widgets | mirrored_repositories/Skysoft_Taxi/lib/widgets/user/paymentMethod.dart | // ignore_for_file: library_private_types_in_public_api
import 'package:flutter/material.dart';
class PaymentScreen extends StatefulWidget {
final Function(IconData icon, String name) onDone;
const PaymentScreen({Key? key, required this.onDone}) : super(key: key);
@override
State<PaymentScreen> createState() => _PaymentScreenState();
}
class _PaymentScreenState extends State<PaymentScreen> {
int selectedTip = 0;
String selectedPaymentMethod = '';
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ListView(
padding: const EdgeInsets.only(top: 45, left: 16, right: 14),
children: [
Row(
mainAxisAlignment: MainAxisAlignment
.start, // Đặt để nút và chữ "Payment Center" cùng về phía bên trái
children: <Widget>[
IconButton(
icon: const Icon(Icons.arrow_back),
iconSize: 30,
onPressed: () {
// Điều hướng hoặc thực hiện hành động khi ấn nút mũi tên ngược
Navigator.of(context).pop();
},
),
const SizedBox(
width:
8), // Khoảng cách giữa biểu tượng và chữ "Payment Center"
const Text(
"Payment Methods",
style: TextStyle(fontSize: 32, fontWeight: FontWeight.bold),
),
],
),
const SizedBox(height: 15),
const Divider(
height: 2,
color: Color(0xFFCCCCCC),
),
const SizedBox(height: 20),
const Text("Linked Method: ", style: TextStyle(fontSize: 18)),
const SizedBox(height: 16),
PaymentMethodCheckBox("Cash", this, Icons.account_balance_wallet),
const SizedBox(height: 16),
PaymentMethodCheckBox("ATM", this, Icons.credit_card),
const SizedBox(height: 20),
const Divider(
height: 2,
color: Color(0xFFCCCCCC),
),
const SizedBox(height: 20),
const Text("Select payment method:",
style: TextStyle(fontSize: 18)),
ListTile(
title: const Text("Wallet"),
leading: const Icon(Icons.account_balance_wallet),
trailing: const Icon(Icons.arrow_forward),
onTap: () {
// Điều hướng đến trang khác khi bạn chọn Wallet
},
),
ListTile(
title: const Text("Cards"),
leading: const Icon(Icons.credit_card),
trailing: const Icon(Icons.arrow_forward),
onTap: () {
// Điều hướng đến trang khác khi bạn chọn Cards
},
),
ListTile(
title: const Text("Zalo Pay"),
leading: const Icon(Icons.account_balance_sharp),
trailing: const Icon(Icons.arrow_forward),
onTap: () {
// Điều hướng đến trang khác khi bạn chọn Zalo Pay
},
),
ListTile(
title: const Text("Momo"),
leading: const Icon(Icons.monetization_on),
trailing: const Icon(Icons.arrow_forward),
onTap: () {
// Điều hướng đến trang khác khi bạn chọn Momo
},
),
const SizedBox(height: 25),
ElevatedButton(
onPressed: () {
if (selectedPaymentMethod == "Cash")
widget.onDone(Icons.account_balance_wallet, "Cash");
if (selectedPaymentMethod == "ATM")
widget.onDone(Icons.credit_card, "ATM");
// Perform payment confirmation
Navigator.pop(context, selectedPaymentMethod);
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
Colors.blue), // Đặt màu nền thành màu xanh biển
minimumSize: MaterialStateProperty.all(
const Size(200, 45)), // Điều chỉnh kích thước của nút
shape: MaterialStateProperty.all(RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
0))), // Đặt độ cong của góc thành 0 để loại bỏ bo góc
),
child: const Text("Confirm ",
style: TextStyle(color: Colors.white, fontSize: 20)),
),
],
),
),
);
}
}
class PaymentMethodCheckBox extends StatelessWidget {
final String method;
final _PaymentScreenState parent;
final IconData iconData;
const PaymentMethodCheckBox(this.method, this.parent, this.iconData,
{Key? key})
: super(key: key);
@override
Widget build(BuildContext context) {
return Row(
children: [
Checkbox(
value: method == parent.selectedPaymentMethod,
onChanged: (bool? value) {
parent.setState(() {
parent.selectedPaymentMethod = method;
});
},
),
Icon(iconData), // Sử dụng biểu tượng được chuyển vào
Text(method),
],
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/widgets | mirrored_repositories/Skysoft_Taxi/lib/widgets/user/car_info.dart | import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:skysoft_taxi/global/global.dart';
import 'package:skysoft_taxi/screen/xanh_sm_clone_User/user_chat_all.dart';
class DriverInfo extends StatefulWidget {
final VoidCallback cancelTrip;
const DriverInfo({Key? key, required this.cancelTrip}) : super(key: key);
@override
State<DriverInfo> createState() => _DriverInfoState();
}
class _DriverInfoState extends State<DriverInfo> with TickerProviderStateMixin {
@override
Widget build(BuildContext context) {
return Stack(
children: [
Positioned(
child: Column(
children: [
const Row(
children: [
Expanded(
child: Icon(
Icons.horizontal_rule,
color: Colors.grey,
size: 30,
),
),
],
),
GestureDetector(
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey[300]!,
width: 1.0,
),
),
),
child: const ListTile(
title: Center(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 20.0),
child: Text(
'Arriving in 2 minutes from now',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black,
fontSize: 20,
),
),
),
),
),
),
),
Expanded(
child: ListView(
children: [
GestureDetector(
onTap: () {
// not used anything
log("Tapped Toyota Corolla");
},
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey[300]!,
width: 1.0,
),
),
),
// height: 150,
child: ListTile(
title: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Expanded(
flex: 10,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Toyota Corolla",
style: TextStyle(
fontFamily: 'Outfit',
fontSize: 22,
fontWeight: FontWeight.w600,
),
),
Row(
children: [
Text(
"Economy:",
style: TextStyle(
fontFamily: 'Outfit',
fontSize: 16,
color: Colors.grey,
),
),
SizedBox(
width: 8,
),
Text(
'\$25.12',
style: TextStyle(
fontFamily: 'Readex Pro',
fontSize: 16,
fontWeight: FontWeight.w600,
color: Colors.redAccent,
),
),
],
),
SizedBox(
height: 25,
),
Text(
"66C-038.27",
style: TextStyle(
fontFamily: 'Outfit',
fontSize: 25,
fontWeight: FontWeight.bold,
color: Colors.blueGrey,
),
),
],
),
),
const SizedBox(
width: 85,
),
Expanded(
flex: 6,
child: Image.asset(
'assets/images/economy.png',
fit: BoxFit
.contain, // Use BoxFit to control the image's fit
),
),
],
),
),
),
),
Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey[300]!,
width: 1.0,
),
),
),
child: SizedBox(
height: 130,
child: GestureDetector(
child: ListTile(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
flex: 6,
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
const Icon(
Icons.account_circle,
size: 120,
color: Colors.blueGrey,
),
Flexible(
child: Column(
crossAxisAlignment:
CrossAxisAlignment.center,
children: [
Padding(
padding:
const EdgeInsets.only(
top: 30),
child: Text(
driverModel.name,
style: const TextStyle(
fontFamily: 'Outfit',
fontSize: 18,
fontWeight:
FontWeight.w600,
),
),
),
const Row(
children: [
Icon(
Icons.star,
color: Colors.yellow,
size: 20,
),
SizedBox(width: 2),
Text(
"5",
style: TextStyle(
fontFamily: 'Outfit',
fontSize: 16,
fontWeight:
FontWeight.w600,
),
),
],
),
],
),
),
],
),
],
),
),
Expanded(
flex: 3,
child: Row(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
GestureDetector(
onTap: () {
log("Tapped Mail Icon");
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) =>
const UserChatAll(),
),
); // Add your mail icon's onTap functionality here
},
child: Align(
alignment: Alignment.center,
child: Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(30),
color: Colors.blueGrey.shade100,
),
child: const Padding(
padding: EdgeInsets.all(8),
child: Icon(
Icons.mail,
size: 30,
color: Colors.blueGrey,
),
),
),
),
),
const SizedBox(
width: 16,
),
GestureDetector(
onTap: () {
log("Tapped Phone Icon");
// Add your phone icon's onTap functionality here
},
child: Align(
alignment: Alignment.center,
child: Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(30),
color: Colors.blueGrey.shade100,
),
child: const Padding(
padding: EdgeInsets.all(8),
child: Icon(
Icons.phone,
size: 30,
color: Colors.blueGrey,
),
),
),
),
),
],
),
),
],
),
),
),
),
)
],
),
),
GestureDetector(
onTap: () {
// not used anything
},
child: Align(
alignment: const AlignmentDirectional(0.00, 0.00),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
GestureDetector(
child: const Row(
children: [
Icon(
Icons.list,
color: Colors.blueAccent,
size: 16,
),
Padding(
padding:
EdgeInsetsDirectional.fromSTEB(5, 5, 15, 1),
child: Text(
'Ride Options',
style: TextStyle(
color: Colors.blueGrey,
fontSize: 15,
fontWeight: FontWeight.w400,
),
),
),
],
),
),
GestureDetector(
onTap: () {
log("Tapped Ride Safety");
// Handle the "Ride Safety" onTap event
},
child: const Row(
children: [
Icon(
Icons.shield,
color: Colors.blueAccent,
size: 16,
),
Padding(
padding:
EdgeInsetsDirectional.fromSTEB(5, 5, 15, 1),
child: Text(
'Ride Safety',
style: TextStyle(
color: Colors.blueGrey,
fontSize: 15,
fontWeight: FontWeight.w400,
),
),
),
],
),
),
],
),
),
),
GestureDetector(
onTap: () {
// not used anything
},
child: Align(
alignment: const AlignmentDirectional(0.00, 0.00),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(
10,
20,
20,
10,
),
child: ElevatedButton(
onPressed: () {
showCancelReasonDialog();
},
style: ElevatedButton.styleFrom(
backgroundColor:
const Color.fromARGB(255, 13, 93, 240),
padding: const EdgeInsets.symmetric(
horizontal: 85, vertical: 15),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
),
child: const Text(
'Cancel trip',
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontStyle: FontStyle.normal,
),
),
),
),
],
),
),
),
],
),
),
],
);
}
List<String> cancelReasons = [
'Tôi không muốn đi nữa',
'Tôi muốn thay đổi địa điểm',
'Đợi tài xế quá lâu',
'Khác',
];
void showCancelReasonDialog() {
int selectedReasonIndex = -1;
showDialog(
context: context,
builder: (context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return AlertDialog(
title: const Text('Chọn lý do hủy chuyến đi'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: cancelReasons.asMap().entries.map((entry) {
final index = entry.key;
final reason = entry.value;
return Row(
children: <Widget>[
Radio<int>(
activeColor: Colors.black,
value: index,
groupValue: selectedReasonIndex,
onChanged: (int? value) {
selectedReasonIndex = value ?? -1;
setState(() {});
},
),
Text(reason),
],
);
}).toList(),
),
actions: <Widget>[
ElevatedButton(
onPressed: () {
Navigator.of(context).pop();
if (selectedReasonIndex >= 0) {
final selectedReason = cancelReasons[selectedReasonIndex];
print('Lý do hủy: $selectedReason');
widget.cancelTrip();
}
},
child: const Text('OK'),
),
],
);
},
);
},
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/widgets | mirrored_repositories/Skysoft_Taxi/lib/widgets/user/ride_requested.dart | import 'package:flutter/material.dart';
class RideRequested extends StatefulWidget {
final VoidCallback onCancelRequest;
RideRequested({Key? key, required this.onCancelRequest}) : super(key: key);
@override
_RideRequestedState createState() => _RideRequestedState();
}
class _RideRequestedState extends State<RideRequested> {
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
child: Padding(
padding: const EdgeInsets.all(0.0),
child: Container(
padding: EdgeInsets.all(16.0),
child: ListView(
children: [
Text(
'Ride Requested',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
SizedBox(height: 18.0),
LinearProgressIndicator(),
SizedBox(height: 18.0),
Text(
'We are looking for the nearest driver for you',
style: TextStyle(
fontSize: 18,
),
),
SizedBox(height: 18.0),
ElevatedButton(
onPressed: () {
print('cancel requested');
widget.onCancelRequest();
},
style: ButtonStyle(
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
backgroundColor:
MaterialStateProperty.all(Colors.grey[200]),
),
child: Text('Cancel Request',
style: TextStyle(color: Colors.black)),
),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/widgets | mirrored_repositories/Skysoft_Taxi/lib/widgets/user/price_car.dart | import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:skysoft_taxi/widgets/user/paymentMethod.dart';
class PriceCar extends StatefulWidget {
final VoidCallback onBookNow;
const PriceCar({Key? key, required this.onBookNow}) : super(key: key);
@override
State<PriceCar> createState() => _PriceCarState();
}
class _PriceCarState extends State<PriceCar> {
double opacity = 0.0;
int selectedIdx = -1;
String selectedText = "Regular"; // Initialize with "Regular"
IconData paymentMethod = Icons.account_balance; // mặc định
String paymentName = "Payment";
@override
void initState() {
super.initState();
Future.delayed(Duration(milliseconds: 300), () {
opacity = 1.0;
setState(() {});
});
}
// Define the data for the list items
final List<String> assetNames = [
'economy',
'electric',
'plus',
'premium',
'luxury',
'sport',
];
final List<String> itemNames = [
'Economy',
'Electric',
'Plus',
'Premium',
'Luxury',
'Sport',
];
final List<String> subtitles = [
'3 seats',
'3 seats',
'3 seats + luggage',
'5 seats + luggage',
'4 seats + small luggage',
'1 seat',
];
final List<String> prices = [
'\$25.12',
'\$26.10',
'\$30.50',
'\$40.00',
'\$55.00',
'\$60.00',
];
// 1: cash, 2: NH
void choosePayment(IconData icon, String name) {
paymentMethod = icon;
paymentName = name;
setState(() {});
}
@override
Widget build(BuildContext context) {
return AnimatedOpacity(
opacity: opacity,
duration: Duration(milliseconds: 500),
child: Column(
children: [
const SizedBox(
height: 30,
child: Icon(
Icons.horizontal_rule,
color: Colors.grey,
),
),
Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey[300]!,
width: 1.0,
),
),
),
child: SizedBox(
height: 70,
child: Center(
child: IntrinsicWidth(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
buildTextItem("Regular"),
buildTextItem("Delivery"),
buildTextItem("Trucks"),
buildTextItem("Taxi"),
buildTextItem("Bikes"),
],
),
),
),
),
),
Expanded(
child: ListView.builder(
itemCount: assetNames.length,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () {
log("Selected item: ${itemNames[index]}");
selectedIdx = index;
setState(() {});
},
child: Container(
color: selectedIdx == index
? const Color(0xFFE2E4E9)
: Colors.white,
child: ListTile(
leading: Image.asset(
'assets/images/${assetNames[index]}.png',
width: 90,
height: 90,
),
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
itemNames[index],
style: const TextStyle(
fontFamily: 'Outfit',
fontSize: 22,
fontWeight: FontWeight.w600,
),
),
Text(
subtitles[index],
style: const TextStyle(
fontFamily: 'Outfit',
fontSize: 16,
color: Colors.grey,
),
),
],
),
subtitle: Text(
prices[index],
textAlign: TextAlign.end,
style: const TextStyle(
fontFamily: 'Readex Pro',
fontSize: 22,
fontWeight: FontWeight.w600,
),
),
),
),
);
},
),
),
SizedBox(
height: 40,
child: GestureDetector(
onTap: () {
log("Payment");
selectedText = "Payment";
setState(() {});
},
child: Container(
decoration: BoxDecoration(
border: Border(
top: BorderSide(
color: Colors.grey[300]!,
width: 1.0,
),
),
),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
GestureDetector(
onTap: () {
log("Payment");
// setState(() {
// selectedText = "Payment";
// });
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => PaymentScreen(
onDone: (method, name) =>
choosePayment(method, name)),
),
);
},
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(width: 20),
Icon(
paymentMethod,
color: selectedText == "Payment"
? Colors.blue
: Colors.blueGrey,
size: 16,
),
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(
5,
5,
10,
1,
),
child: Text(
paymentName,
style: TextStyle(
color: selectedText == "Payment"
? Colors.blue
: Colors.grey,
fontSize: 15,
fontWeight: FontWeight.normal,
),
),
),
],
),
),
GestureDetector(
onTap: () {
log("Coupon Code");
selectedText = "Coupon Code";
setState(() {});
},
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.local_offer,
color: selectedText == "Coupon Code"
? Colors.blue
: Colors.blueGrey,
size: 16,
),
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(
5,
5,
30,
1,
),
child: Text(
'Coupon Code',
style: TextStyle(
color: selectedText == "Coupon Code"
? Colors.blue
: Colors.grey,
fontSize: 15,
fontWeight: FontWeight.normal,
),
),
),
],
),
),
],
),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10.0,
),
child: SizedBox(
height: 55.0,
child: Center(
child: ListView(
scrollDirection: Axis.horizontal,
children: [
Padding(
padding: const EdgeInsetsDirectional.only(
start: 20,
),
child: ElevatedButton(
onPressed: () {
log('Book Now');
if (selectedIdx != -1) {
widget.onBookNow();
} else {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Thông báo'),
content: Text('Vui lòng chọn xe'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('OK'),
),
],
);
},
);
}
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFFE2E4E9),
padding: const EdgeInsetsDirectional.fromSTEB(
85, 10, 85, 10),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
),
child: const Text(
'Book Now',
style: TextStyle(
color: Colors.black,
fontSize: 26,
fontWeight: FontWeight.normal,
),
),
),
),
const SizedBox(
width: 15,
),
ElevatedButton(
onPressed: () {
log("Calendar");
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xffe2e4e9),
padding: const EdgeInsetsDirectional.fromSTEB(
20, 11, 20, 11),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
),
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.calendar_month,
size: 30,
color: Colors.black,
),
],
),
),
],
),
),
),
),
SizedBox(height: 16),
],
),
);
}
Widget buildTextItem(String text) {
return GestureDetector(
onTap: () {
log(text);
selectedText = text;
setState(() {});
},
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color: selectedText == text ? Colors.grey : Colors.transparent,
),
padding: const EdgeInsets.all(10),
child: Text(
text,
style: TextStyle(
color: selectedText == text ? Colors.white : Colors.black,
),
),
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/widgets | mirrored_repositories/Skysoft_Taxi/lib/widgets/user/destination_information.dart | import 'package:flutter/material.dart';
import 'package:sliding_up_panel/sliding_up_panel.dart';
class DestinationInformation extends StatefulWidget {
final PanelController panelController;
final VoidCallback bookCar;
const DestinationInformation(
{Key? key, required this.panelController, required this.bookCar})
: super(key: key);
@override
_DestinationInformationState createState() => _DestinationInformationState();
}
class _DestinationInformationState extends State<DestinationInformation> {
ScrollController controller = ScrollController();
@override
void initState() {
super.initState();
controller.addListener(() {
if (controller.position.pixels > 0) {
widget.panelController.open();
} else {
widget.panelController.close();
}
});
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(10),
child: Column(
children: [
const SizedBox(
height: 20,
child: Icon(
Icons.horizontal_rule,
color: Colors.grey,
size: 30,
),
),
Expanded(
child: ListView(
shrinkWrap: true,
controller: controller,
children: <Widget>[
Container(
padding: EdgeInsets.symmetric(vertical: 10),
margin: EdgeInsets.only(bottom: 5, left: 5),
child: Text(
'Hà Nội',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey[300]!,
width: 1.0,
),
),
),
),
Container(
padding: EdgeInsets.only(left: 16.0, top: 16),
child: Text('Thời gian: 150 phút',
style: TextStyle(fontSize: 18)),
),
Container(
padding: EdgeInsets.only(left: 16.0, top: 10, bottom: 16),
child: Text('Quãng đường: 117 km',
style: TextStyle(fontSize: 18)),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey[300]!,
width: 1.0,
),
),
),
),
SizedBox(height: 16.0),
Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 16.0),
child: ElevatedButton(
onPressed: () {
print('instruction');
},
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.blue),
shape:
MaterialStateProperty.all(RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
)),
),
child: Row(
children: [
Icon(Icons.directions, size: 24),
Text(' Đường đi'),
],
),
),
),
Padding(
padding: const EdgeInsets.only(left: 16.0),
child: ElevatedButton(
onPressed: () {
print('start');
widget.bookCar();
},
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.grey),
shape:
MaterialStateProperty.all(RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
)),
),
child: Row(
children: [
Icon(Icons.assistant_navigation, size: 24),
Text(' Đặt xe'),
],
),
),
),
],
),
],
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/widgets | mirrored_repositories/Skysoft_Taxi/lib/widgets/user/searchOnPanalBar.dart | import 'package:flutter/material.dart';
import 'package:sliding_up_panel/sliding_up_panel.dart';
class SearchOnPanalBar extends StatelessWidget {
const SearchOnPanalBar({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final screenHeight = MediaQuery.of(context).size.height;
return SlidingUpPanel(
minHeight: screenHeight,
maxHeight: screenHeight,
panel: Container(
padding: const EdgeInsets.all(10),
color: Colors.white,
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 16.0),
child: Material(
color: Colors.transparent, // Đặt màu nền là trong suốt
child: InkWell(
onTap: () {
Navigator.of(context).pop();
},
child: IconButton(
icon: Icon(Icons.close),
onPressed: null,
),
),
),
),
const SizedBox(height: 16.0),
Column(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(20.0),
),
child: const TextField(
decoration: InputDecoration(
prefixIcon: Icon(Icons.near_me),
hintText: 'Current Location',
border: InputBorder.none,
),
),
),
const SizedBox(height: 16.0),
Container(
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(20.0),
),
child: const TextField(
decoration: InputDecoration(
prefixIcon: Icon(Icons.location_on),
hintText: 'Enter your destination',
border: InputBorder.none,
),
),
),
],
),
const SizedBox(height: 16.0),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: <Widget>[
const SizedBox(width: 10.0),
Container(
width: 200,
child: StartButton(),
),
const SizedBox(width: 16.0),
Container(
width: 200,
child: ChooseOnMapButton(),
),
const SizedBox(width: 16.0),
Container(
width: 200,
child: StartButton(),
),
const SizedBox(width: 16.0),
Container(
width: 200,
child: ChooseOnMapButton(),
),
],
),
),
const SizedBox(height: 16.0),
Expanded(
child: ListView.builder(
shrinkWrap: true,
physics: const ClampingScrollPhysics(),
itemCount: 5,
itemBuilder: (context, index) {
return Card(
elevation: 4,
margin: EdgeInsets.all(8.0),
color: Colors.grey[200],
child: ListTile(
contentPadding: const EdgeInsets.symmetric(
vertical: 16.0, horizontal: 16.0),
leading: const Icon(Icons.history),
title: Text('Lịch sử chuyến đi $index'),
subtitle: Text('Di chuyển tới điểm $index'),
trailing: const Icon(Icons.arrow_forward),
onTap: () {
print('lịch sử $index');
},
),
);
},
),
)
],
),
),
);
}
}
class ChooseOnMapButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ElevatedButton.icon(
onPressed: () {
print('choose on map');
},
icon: const Icon(Icons.location_searching),
label: Text('Choose on Map'),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.grey),
),
);
}
}
class StartButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ElevatedButton.icon(
onPressed: () {
print('start');
Navigator.pop(context, 'startButtonPressed');
},
icon: const Icon(Icons.near_me),
label: const Text('Test di chuyển'),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.grey),
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/widgets | mirrored_repositories/Skysoft_Taxi/lib/widgets/user/panel_bar.dart | import 'package:flutter/material.dart';
import 'package:sliding_up_panel/sliding_up_panel.dart';
class PanelBar extends StatefulWidget {
final PanelController panelController;
final VoidCallback? onTextFieldPressed;
const PanelBar(
{Key? key, required this.panelController, this.onTextFieldPressed})
: super(key: key);
@override
State<PanelBar> createState() => _PanelBarState();
}
class _PanelBarState extends State<PanelBar> with TickerProviderStateMixin {
@override
Widget build(BuildContext context) {
return Stack(
children: [
Positioned(
child: Column(
children: [
const Row(
children: [
Expanded(
child: Icon(
Icons.horizontal_rule,
color: Colors.grey,
size: 30,
),
),
],
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10.0, vertical: 13.0),
child: GestureDetector(
onTap: () async {},
child: TextField(
readOnly: true,
decoration: InputDecoration(
filled: true,
fillColor: Colors.grey[200],
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
borderSide: BorderSide.none,
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 10.0,
vertical: 15.0,
),
hintText: 'Where to ?',
hintStyle: const TextStyle(
fontSize: 16,
color: Colors.black,
),
prefixIcon: const Icon(Icons.search, color: Colors.grey),
suffixIcon: const Icon(Icons.mic, color: Colors.grey),
),
onTap: () {
widget.panelController.open();
if (widget.onTextFieldPressed != null) {
widget.onTextFieldPressed!();
}
},
),
),
),
SizedBox(height: 16.0),
Expanded(
child: ListView(
children: [
GestureDetector(
onTap: () {
// log("Connect calendar");
},
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey[300]!,
width: 1.0,
),
),
),
child: const ListTile(
leading: Icon(
Icons.warehouse,
color: Colors.grey,
),
title: Text(
'Home',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
subtitle: Text(
'Set Once and go ',
style: TextStyle(
fontStyle: FontStyle.italic,
color: Colors.blue,
),
),
),
),
),
GestureDetector(
onTap: () {
// log("Connect calendar");
},
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey[300]!,
width: 1.0,
),
),
),
child: const ListTile(
leading: Icon(
Icons.work,
color: Colors.grey,
),
title: Text(
'Work',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
subtitle: Text(
'Set Once and go ',
style: TextStyle(
fontStyle: FontStyle.italic,
color: Colors.blue,
),
),
),
),
),
GestureDetector(
onTap: () {
// log("Drive to friend & family");
},
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey[300]!,
width: 1.0,
),
),
),
child: const ListTile(
leading: Icon(
Icons.directions_car,
color: Colors.grey,
),
title: Text(
'Drive to friend & family',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
subtitle: Text(
'Search contacts',
style: TextStyle(
fontStyle: FontStyle.italic,
color: Colors.blue,
),
),
),
),
),
GestureDetector(
onTap: () {
// log("Connect calendar");
},
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey[300]!,
width: 1.0,
),
),
),
child: const ListTile(
leading: Icon(
Icons.calendar_month,
color: Colors.grey,
),
title: Text(
'Connect calendar',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
subtitle: Text(
'Sync your calendar for route planning',
style: TextStyle(
fontStyle: FontStyle.italic,
color: Colors.blue,
),
),
),
),
),
],
),
),
],
),
),
],
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/widgets | mirrored_repositories/Skysoft_Taxi/lib/widgets/user/sidebar_toggle_button .dart | // ignore_for_file: library_private_types_in_public_api
import 'package:flutter/material.dart';
class SidebarToggleButton extends StatefulWidget {
final GlobalKey<ScaffoldState> scaffoldKey;
final Function? onPressed;
const SidebarToggleButton({
required this.scaffoldKey,
this.onPressed,
Key? key,
}) : super(key: key);
@override
_SidebarToggleButtonState createState() => _SidebarToggleButtonState();
}
class _SidebarToggleButtonState extends State<SidebarToggleButton> {
@override
Widget build(BuildContext context) {
return Positioned(
top: 40.0,
left: 15.0,
child: GestureDetector(
onTap: () {
if (widget.onPressed != null) {
widget.onPressed!();
} else {
widget.scaffoldKey.currentState!.openDrawer();
}
},
child: Container(
width: 50,
height: 50,
decoration: const BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
child: const Icon(
Icons.menu,
color: Colors.black,
),
),
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/widgets | mirrored_repositories/Skysoft_Taxi/lib/widgets/user/reviews.dart | import 'package:flutter/material.dart';
import 'package:skysoft_taxi/widgets/user/stars.dart';
import 'package:sliding_up_panel/sliding_up_panel.dart';
class Reviews extends StatefulWidget {
final Function onClose;
final PanelController panelController;
const Reviews(
{super.key, required this.onClose, required this.panelController});
@override
State<Reviews> createState() => _ReviewsState();
}
class _ReviewsState extends State<Reviews> {
int numberOfStars = 0;
ScrollController controller = ScrollController();
double opacity = 0.0;
PointButton goodDriving = PointButton("Good Driving", Colors.grey[200]!,
Colors.green[200]!, Colors.grey[500]!, Colors.green[500]!);
PointButton goodRouting = PointButton("Good Routing", Colors.grey[200]!,
Colors.green[200]!, Colors.grey[500]!, Colors.green[500]!);
PointButton cleanCar = PointButton("Clean Car", Colors.grey[200]!,
Colors.green[200]!, Colors.grey[500]!, Colors.green[500]!);
PointButton polite = PointButton("Polite", Colors.grey[200]!,
Colors.green[200]!, Colors.grey[500]!, Colors.green[500]!);
PointButton badDriving = PointButton("Bad Driving", Colors.grey[200]!,
Colors.red[200]!, Colors.grey[500]!, Colors.red[500]!);
PointButton badRouting = PointButton("Bad Routing", Colors.grey[200]!,
Colors.red[200]!, Colors.grey[500]!, Colors.red[500]!);
PointButton dirtyCar = PointButton("Dirty Car", Colors.grey[200]!,
Colors.red[200]!, Colors.grey[500]!, Colors.red[500]!);
PointButton impolite = PointButton("Impolite", Colors.grey[200]!,
Colors.red[200]!, Colors.grey[500]!, Colors.red[500]!);
void handleSelectStar(int index) {
numberOfStars = index;
setState(() {});
}
void unSelect(PointButton button) {
if (button.isSelect) {
button.isSelect = !button.isSelect;
}
}
void showNotification(String mes, BuildContext context) {
SnackBar snackBar = SnackBar(
content: Text(mes),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
@override
void initState() {
super.initState();
Future.delayed(Duration(milliseconds: 300), () {
setState(() {
opacity = 1.0;
});
});
controller.addListener(() {
if (controller.position.pixels > 0) {
widget.panelController.open();
} else {
widget.panelController.close();
}
});
}
@override
Widget build(BuildContext context) {
return AnimatedOpacity(
opacity: opacity,
duration: Duration(milliseconds: 500),
child: Padding(
padding: const EdgeInsets.all(10),
child: Column(
children: [
SizedBox(
height: 20,
child: GestureDetector(
onTap: () {
if (widget.panelController.isPanelOpen) {
widget.panelController.close();
} else {
widget.panelController.open();
}
},
child: Row(
children: [
Expanded(
child: Icon(
Icons.horizontal_rule,
color: Colors.grey,
size: 30,
),
),
],
),
),
),
Expanded(
child: ListView(
controller: controller,
shrinkWrap: true,
padding: const EdgeInsets.all(0),
children: [
Container(
alignment: Alignment.center,
margin: EdgeInsets.only(top: 5, bottom: 5),
padding: EdgeInsets.symmetric(vertical: 10),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey[300]!,
width: 1.0,
),
),
),
child: Text(
'How was your ride?',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
),
Container(
margin: EdgeInsets.only(top: 5, bottom: 5),
padding: EdgeInsets.symmetric(vertical: 10),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey[300]!,
width: 1.0,
),
),
),
child: Column(
children: [
Text(
'Help us improve your experience by rating your driver',
style: TextStyle(fontSize: 18)),
StarsWidget(
numberOfStars: numberOfStars,
size: 50,
onClick: ((index) => handleSelectStar(index)),
)
],
),
),
Container(
padding: const EdgeInsets.only(bottom: 10),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.grey[300]!,
width: 1.0,
),
),
),
child: Column(
children: [
Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Icon(Icons.heart_broken_rounded),
Text("Nice Poins"),
buidButton(goodDriving, () {
goodDriving.isSelect =
!goodDriving.isSelect;
unSelect(badDriving);
setState(() {});
print(goodDriving.title);
}),
buidButton(goodRouting, () {
goodRouting.isSelect =
!goodRouting.isSelect;
unSelect(badRouting);
setState(() {});
print(goodRouting.title);
}),
buidButton(cleanCar, () {
cleanCar.isSelect = !cleanCar.isSelect;
unSelect(dirtyCar);
setState(() {});
print(cleanCar.title);
}),
buidButton(polite, () {
polite.isSelect = !polite.isSelect;
unSelect(impolite);
setState(() {});
print(polite.title);
}),
],
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Icon(Icons.heart_broken_rounded),
Text("Negative Poins"),
buidButton(badDriving, () {
badDriving.isSelect =
!badDriving.isSelect;
unSelect(goodDriving);
setState(() {});
print(badDriving.title);
}),
buidButton(badRouting, () {
badRouting.isSelect =
!badRouting.isSelect;
unSelect(goodRouting);
setState(() {});
print(badRouting.title);
}),
buidButton(dirtyCar, () {
dirtyCar.isSelect = !dirtyCar.isSelect;
unSelect(cleanCar);
setState(() {});
print(dirtyCar.title);
}),
buidButton(impolite, () {
impolite.isSelect = !impolite.isSelect;
unSelect(polite);
setState(() {});
print(impolite.title);
}),
],
),
),
)
],
)
],
),
),
const SizedBox(height: 16.0),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
margin: EdgeInsets.only(bottom: 10),
child: Text("Add Comment"),
),
TextFormField(
minLines: 5,
maxLines: null,
keyboardType: TextInputType.multiline,
decoration: InputDecoration(
hintText: 'Write comment',
hintStyle: TextStyle(color: Colors.grey),
border: OutlineInputBorder(
borderRadius:
BorderRadius.all(Radius.circular(10.0)),
),
),
),
Row(
children: [
Expanded(
child: ElevatedButton(
onPressed: () {
showNotification(
"Đã gửi FeedBack thành công.!", context);
print('Send FeedBack');
widget.onClose();
},
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Colors.blue),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
)),
),
child: Text('Send FeedBack'),
),
),
],
),
],
)
],
),
),
],
),
),
);
}
Row buidButton(PointButton button, onClick) {
Color colorButton = button.normalButton;
Color colorText = button.normalText;
if (button.isSelect) {
colorButton = button.activeButton;
colorText = button.activeText;
}
return Row(
children: [
Expanded(
child: ElevatedButton(
onPressed: () {
onClick();
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(colorButton),
shape: MaterialStateProperty.all(RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
)),
),
child: Text(
button.title,
style: TextStyle(color: colorText),
),
),
),
],
);
}
}
class SelectColors {
Color colorButton = Colors.grey[200]!;
Color colorText = Colors.grey[500]!;
Color colorButtonAction = Colors.green[200]!;
Color colorTextAction = Colors.green[500]!;
}
class PointButton {
String title;
Color normalButton;
Color activeButton;
Color normalText;
Color activeText;
bool isSelect = false;
PointButton(this.title, this.normalButton, this.activeButton, this.normalText,
this.activeText);
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/widgets | mirrored_repositories/Skysoft_Taxi/lib/widgets/user/side_bar.dart | // ignore_for_file: library_private_types_in_public_api
import 'package:flutter/material.dart';
import 'package:skysoft_taxi/screen/xanh_sm_clone_User/login_screen.dart';
class SideBar extends StatefulWidget {
const SideBar({super.key});
@override
_SideBarState createState() => _SideBarState();
}
class _SideBarState extends State<SideBar> {
int selectedIndex = 0; // Add your initial state logic here
void onItemTapped(int index) {
selectedIndex = index;
setState(() {});
}
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: const BorderRadius.only(
topRight: Radius.circular(25),
bottomRight: Radius.circular(25),
),
child: Drawer(
backgroundColor: Colors.white,
child: ListView(
padding: EdgeInsets.zero,
children: [
_buildHeader(),
_buildListTile(Icons.home, 'Home', Colors.blueGrey, 0),
_buildListTile(Icons.account_circle, 'Profile', Colors.blueGrey, 3),
_buildListTile(
Icons.notifications, 'Announcement', Colors.blueGrey, 4),
_buildListTile(Icons.wallet, 'Wallet', Colors.blueGrey, 5),
_buildListTile(
Icons.location_on, 'Save Locations', Colors.blueGrey, 6),
_buildListTile(
Icons.directions_car, 'Reserved Rides', Colors.blueGrey, 7),
_buildListTile(Icons.history, 'Trip History', Colors.blueGrey, 8),
_buildListTile(Icons.language, 'Website', Colors.blueGrey, 9),
_buildListTile(Icons.settings, 'Settings', Colors.blueGrey, 10),
_buildListTile(Icons.info, 'About', Colors.blueGrey, 11),
_buildListTile(Icons.exit_to_app, 'Logout', Colors.blueGrey, 12),
],
),
),
);
}
ListTile _buildListTile(
IconData icon, String title, Color textColor, int index) {
return ListTile(
contentPadding: EdgeInsets.zero,
leading: Padding(
padding: const EdgeInsets.only(left: 35),
child: Icon(icon, color: Colors.blueGrey),
),
title: Padding(
padding: const EdgeInsets.only(left: 5),
child: Text(
title,
style: TextStyle(
color: textColor,
),
),
),
tileColor: selectedIndex == index ? const Color(0xFFE2E4E9) : null,
onTap: () {
onItemTapped(index);
_navigateToPage(index);
},
);
}
// THAY ĐỔI HOME THÀNH WIDGET MUỐN ĐIỀU HƯỚNG Home()
void _navigateToPage(int index) {
switch (index) {
case 0:
// Navigator.of(context)
// .push(MaterialPageRoute(builder: (context) => const Home()));
break;
case 3:
// Navigator.of(context)
// .push(MaterialPageRoute(builder: (context) => const HomeDriver()));
break;
case 4:
// Navigator.of(context)
// .push(MaterialPageRoute(builder: (context) => const Home()));
break;
case 5:
// Navigator.of(context)
// .push(MaterialPageRoute(builder: (context) => const Home()));
break;
case 6:
// Navigator.of(context)
// .push(MaterialPageRoute(builder: (context) => const Home()));
break;
case 7:
// Navigator.of(context)
// .push(MaterialPageRoute(builder: (context) => const Home()));
break;
case 8:
// Navigator.of(context)
// .push(MaterialPageRoute(builder: (context) => const Home()));
break;
case 9:
// Navigator.of(context)
// .push(MaterialPageRoute(builder: (context) => const Home()));
break;
case 10:
// Navigator.of(context)
// .push(MaterialPageRoute(builder: (context) => const Home()));
break;
case 11:
// Navigator.of(context)
// .push(MaterialPageRoute(builder: (context) => const Home()));
break;
case 12:
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => const LoginScreen()));
break;
}
}
Widget _buildHeader() {
return Container(
padding: const EdgeInsets.all(50),
child: const Row(
children: [
CircleAvatar(
radius: 40,
backgroundImage: NetworkImage(
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQm3RFDZM21teuCMFYx_AROjt-AzUwDBROFww&usqp=CAU'),
),
SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'User Name',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
],
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/widgets | mirrored_repositories/Skysoft_Taxi/lib/widgets/user/stars.dart | import 'package:flutter/material.dart';
class StarsWidget extends StatelessWidget {
const StarsWidget(
{super.key,
required this.numberOfStars,
required this.size,
required this.onClick});
final int numberOfStars;
final double size;
final Function(int index) onClick;
@override
Widget build(BuildContext context) {
return buildNumberStar(numberOfStars, size, onClick);
}
Row buildNumberStar(numberOfStars, size, onClick) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List.generate(5, (index) {
Color color = Colors.grey.withOpacity(0.4);
if (index < numberOfStars) {
color = Colors.amber;
}
return IconButton(
onPressed: (() => onClick(index + 1)),
icon: Icon(
Icons.star,
color: color,
size: size,
));
}));
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/widgets | mirrored_repositories/Skysoft_Taxi/lib/widgets/button/button_counter.dart | // ignore_for_file: library_private_types_in_public_api
import 'package:flutter/material.dart';
class ButtonCounter extends StatefulWidget {
const ButtonCounter({Key? key}) : super(key: key);
@override
_ButtonCounterState createState() => _ButtonCounterState();
}
class _ButtonCounterState extends State<ButtonCounter> {
int counter = 1; // Set initial value to 1
void _incrementCounter() {
if (counter < 5) {
counter++;
}
setState(() {});
}
void _decrementCounter() {
if (counter > 1) {
counter--;
}
setState(() {});
}
@override
Widget build(BuildContext context) {
double screenHeight = MediaQuery.of(context).size.height;
double topPosition = screenHeight * 0.7; // Adjust the multiplier as needed
return Positioned(
top: topPosition,
left: 0,
right: 0,
child: GestureDetector(
onTap: () => {},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(20),
bottomLeft: Radius.circular(20),
),
child: ElevatedButton(
onPressed: _decrementCounter,
style: ElevatedButton.styleFrom(
padding:
const EdgeInsets.symmetric(horizontal: 15, vertical: 14),
backgroundColor: Colors.orangeAccent,
),
child: const Icon(Icons.remove, size: 18),
),
),
Container(
padding: const EdgeInsets.all(13),
decoration: const BoxDecoration(
color: Colors.white, // White background for the text
),
child: Text(
'$counter K/M',
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.normal,
color: Colors.black,
),
),
),
ClipRRect(
borderRadius: const BorderRadius.only(
topRight: Radius.circular(20),
bottomRight: Radius.circular(20),
),
child: ElevatedButton(
onPressed: _incrementCounter,
style: ElevatedButton.styleFrom(
padding:
const EdgeInsets.symmetric(horizontal: 5, vertical: 14),
backgroundColor: Colors.orangeAccent, // Remove the shadow
),
child: const Icon(Icons.add, size: 18),
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/widgets | mirrored_repositories/Skysoft_Taxi/lib/widgets/button/button_current_location.dart | import 'package:flutter/material.dart';
class CurrentLocationButton extends StatefulWidget {
const CurrentLocationButton({super.key});
@override
_CurrentLocationButtonState createState() => _CurrentLocationButtonState();
}
class _CurrentLocationButtonState extends State<CurrentLocationButton> {
@override
Widget build(BuildContext context) {
return Positioned(
top: 630,
left: 340,
child: GestureDetector(
onTap: () {},
child: Container(
width: 40,
height: 40,
decoration: const BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
child: const Icon(
Icons.location_searching,
color: Colors.black,
),
),
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/widgets | mirrored_repositories/Skysoft_Taxi/lib/widgets/button/button_save_maker.dart | import 'package:flutter/material.dart';
class ButtonSaveMaker extends StatefulWidget {
final IconData icon;
final String text;
final VoidCallback? onTap;
const ButtonSaveMaker({
super.key,
required this.icon,
required this.text,
this.onTap,
});
@override
State<ButtonSaveMaker> createState() => _ButtonSaveMakerState();
}
class _ButtonSaveMakerState extends State<ButtonSaveMaker> {
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: widget.onTap,
child: Container(
margin: const EdgeInsets.all(8.0),
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8.0),
),
child: Row(
children: [
Icon(
widget.icon,
size: 12,
color: Colors.blue,
),
const SizedBox(width: 5.0),
Text(
widget.text,
style: const TextStyle(
fontSize: 12,
color: Colors.black,
fontWeight: FontWeight.bold,
),
overflow: TextOverflow.ellipsis,
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/widgets | mirrored_repositories/Skysoft_Taxi/lib/widgets/button/button_icon_booking_type.dart | import 'package:flutter/material.dart';
class ButtonIconBookingType extends StatefulWidget {
final String imagePath;
final String text;
final VoidCallback? onTap;
const ButtonIconBookingType(
{Key? key, required this.imagePath, required this.text, this.onTap})
: super(key: key);
@override
State<ButtonIconBookingType> createState() => _ButtonIconBookingTypeState();
}
class _ButtonIconBookingTypeState extends State<ButtonIconBookingType> {
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: widget.onTap,
child: Column(
children: [
Container(
width: 60,
height: 60,
margin: const EdgeInsets.fromLTRB(15, 0, 15, 0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(15.0),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.network(
widget.imagePath,
width: 20,
height: 20,
fit: BoxFit.fill,
color: Colors.blue,
),
],
),
),
const SizedBox(height: 5.0),
Text(
widget.text,
style: const TextStyle(
fontSize: 11,
color: Colors.black,
fontWeight: FontWeight.bold,
),
overflow: TextOverflow.ellipsis,
),
],
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/audio/audio_player.dart | import 'package:just_audio/just_audio.dart';
class MyAudioPlayer {
final AudioPlayer player = AudioPlayer();
MyAudioPlayer();
Stream<PlayerState> statePlayer() {
return player.playerStateStream;
}
void playUrl(String url) async {
stop();
// Play without waiting for completion, if need waiting then add await
try {
await player.setUrl(url); // Schemes: (https: | file: | asset: )
} catch (e) {
print(e);
return;
}
player.play();
}
void pause() async {
await player.pause(); // Pause but remain ready to play
}
void stop() async {
await player.stop();
}
void seekTo(int time) async {
await player.seek(Duration(seconds: time));
}
void setSpeed(double speed) async {
await player.setSpeed(speed);
}
void setVolume(double value) async {
await player.setVolume(value);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/audio/AudioPlayerScreen.dart | import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import 'PlayerItem.dart';
import 'audio_player.dart';
class AudioPlayerScreen extends StatefulWidget {
const AudioPlayerScreen({super.key, required this.title});
final String title;
@override
State<AudioPlayerScreen> createState() => _AudioPlayerScreenState();
}
class _AudioPlayerScreenState extends State<AudioPlayerScreen> {
MyAudioPlayer player = MyAudioPlayer();
ValueNotifier<String> currentUrl = ValueNotifier<String>("");
List<String> listUrl = [
"http://192.168.1.75:8081/product/rest/chat/310.mp3",
"http://192.168.1.75:8081/product/rest/chat/312.mp3",
"http://192.168.1.75:8081/product/rest/chat/313.mp3",
"http://192.168.1.75:8081/product/rest/chat/316.mp3",
"http://192.168.1.75:8081/product/rest/chat/317.mp3",
"http://192.168.1.75:8081/product/rest/chat/318.mp3",
"http://192.168.1.75:8081/product/rest/chat/319.mp3",
];
List<Widget> buildList() {
log("buildList: ${currentUrl.value}");
List<Widget> list = [];
listUrl.forEach((element) {
list.add(PlayerItem(
audioURL: element,
time: DateTime.now(),
play: (url) {
currentUrl.value = url;
player.playUrl(url);
},
stop: () => player.stop(),
autoPlay: element == currentUrl.value,
));
});
return list;
}
@override
void initState() {
super.initState();
player.statePlayer().listen((event) {
log("State: ${event.processingState}");
if (event.processingState == ProcessingState.completed) {
// Khi âm thanh kết thúc, dừng và đặt lại vị trí 0
player.stop();
player.seekTo(0);
currentUrl.value = "";
}
});
}
@override
Widget build(BuildContext context) {
log("REBUILD");
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: ValueListenableBuilder(
valueListenable: currentUrl,
builder: (BuildContext context, String url, Widget? child) {
return ListView.builder(
itemCount: listUrl.length,
itemBuilder: (BuildContext context, int index) {
String url = listUrl.elementAt(index);
bool play = url == currentUrl.value;
log("ListView: $url - $play");
return PlayerItem(
audioURL: url,
time: DateTime.now(),
play: (url) {
currentUrl.value = url;
player.playUrl(url);
},
stop: () => player.stop(),
autoPlay: play,
);
},
);
}),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/audio/PlayerItem.dart | import 'dart:async';
import 'dart:developer';
import 'dart:math' as math;
import 'package:flutter/material.dart';
class PlayerItem extends StatefulWidget {
String audioURL;
bool isStarred;
bool isTag;
bool isRight;
DateTime time;
bool autoPlay;
Function(String) play;
Function() stop;
PlayerItem(
{super.key,
required this.audioURL,
this.isStarred = false,
this.isTag = false,
this.isRight = true,
this.autoPlay = false,
required this.time,
required this.play,
required this.stop});
@override
State<PlayerItem> createState() => _PlayerItemState();
}
class _PlayerItemState extends State<PlayerItem> {
Color? colorBg(bool isRight, bool isTag, bool isStarred) {
if (isTag) {
return Colors.red[300];
}
if (isStarred) {
return Colors.green[300];
}
if (!isRight) {
return Colors.grey[300];
}
return Colors.blue[300];
}
Color colorBorder(bool isRight, bool isTag, bool isStarred) {
if (isTag) {
return Colors.red;
}
if (isStarred) {
return Colors.green;
}
if (!isRight) {
return Colors.grey;
}
return Colors.blue;
}
@override
void initState() {
super.initState();
// log("PlayerItem: ${widget.audioURL} - ${widget.autoPlay}");
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
Padding(
padding: EdgeInsets.all(30.0),
child: Align(
alignment:
widget.isRight ? Alignment.centerRight : Alignment.centerLeft,
child: ConstrainedBox(
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * 0.7,
),
child: Container(
decoration: BoxDecoration(
color:
colorBg(widget.isRight, widget.isTag, widget.isStarred),
borderRadius: BorderRadius.circular(5),
border: Border.all(
color: colorBorder(
widget.isRight, widget.isTag, widget.isStarred),
width: 2,
),
),
child: Container(
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.circular(4.0),
),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
CircularIconButton(
icon: widget.isStarred
? Icons.star
: Icons.star_border,
iconColor:
widget.isStarred ? Colors.yellow : Colors.black,
onPressed: () {
widget.isStarred = !widget.isStarred;
setState(() {});
},
),
CircularIconButton(
icon: Icons.share,
iconColor: Colors.black,
onPressed: () {
// Chia sẻ link
log("Share link");
},
),
SizedBox(width: 8.0),
Expanded(
child: AudioWaveWidget(isPlaying: widget.autoPlay),
),
SizedBox(width: 8.0),
CircularIconButton(
icon: widget.autoPlay
? Icons.pause
: Icons.play_arrow,
iconColor: Colors.black,
onPressed: () {
widget.autoPlay = !widget.autoPlay;
widget.autoPlay
? widget.play(widget.audioURL)
: widget.stop();
setState(() {});
},
),
],
),
Text(
'${widget.time.hour}:${widget.time.minute}',
style: TextStyle(
fontSize: 12.0,
color: Colors.black,
),
),
],
),
),
),
),
),
),
// Ảnh avatar
Positioned(
bottom: 0.0, // Đặt bottom thành 0 để nằm ở góc dưới
right: widget.isRight
? 0.0
: null, // Đặt right thành 0 khi widget.isRight là true
left: widget.isRight
? null
: 0.0, // Đặt left thành 0 khi widget.isRight là false
child: CircleAvatar(
radius: 15.0,
child: Container(
color: Colors.green,
),
))
],
);
}
}
class CircularIconButton extends StatelessWidget {
final IconData icon;
final Color iconColor;
final VoidCallback? onPressed;
CircularIconButton({
required this.icon,
required this.iconColor,
this.onPressed,
});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onPressed,
child: IconButton(
icon: Icon(icon, color: iconColor),
onPressed: onPressed,
),
);
}
}
class AudioWaveWidget extends StatefulWidget {
final bool isPlaying;
// int time
AudioWaveWidget({required this.isPlaying});
@override
_AudioWaveWidgetState createState() => _AudioWaveWidgetState();
}
class _AudioWaveWidgetState extends State<AudioWaveWidget> {
late Timer _timer;
late List<double> _waveHeights;
@override
void initState() {
super.initState();
_waveHeights = List.generate(10, (index) => _generateRandomHeight());
_startWaveAnimation();
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
void _startWaveAnimation() {
const Duration interval =
Duration(milliseconds: 300); // Đặt khoảng thời gian cập nhật
_timer = Timer.periodic(interval, (Timer timer) {
_waveHeights = List.generate(10, (index) => _generateRandomHeight());
setState(() {});
});
}
@override
Widget build(BuildContext context) {
return Container(
height: 20.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List.generate(
10,
(index) => _buildWaveBar(index),
),
),
);
}
Widget _buildWaveBar(int index) {
final double waveHeight = widget.isPlaying ? _waveHeights[index] : 15.0;
final double waveSpacing = 2.0;
return Container(
width: 4.0,
margin: EdgeInsets.symmetric(horizontal: waveSpacing),
child: Align(
alignment: Alignment.bottomCenter,
child: Container(
height: waveHeight * (index + 1) / 10,
decoration: BoxDecoration(
color: widget.isPlaying ? Colors.red : Colors.black,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(2.0),
topRight: Radius.circular(2.0),
),
),
),
),
);
}
double _generateRandomHeight() {
final random = math.Random();
return (random.nextDouble() * 20.0) +
5.0; // Tạo ra giá trị ngẫu nhiên từ 5.0 đến 25.0
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/models/save_marker_model.dart | import 'package:flutter/material.dart';
class SaveMakerModel {
IconData icon;
String text;
VoidCallback? onTap;
SaveMakerModel({required this.icon, required this.text, this.onTap});
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/models/message.model.dart | enum Type { public, private }
class MessageModel {
bool isServer;
String content;
String sender;
String receiver;
Type type;
MessageModel({
required this.content,
required this.sender,
required this.receiver,
this.type = Type.public,
this.isServer = false,
});
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/models/booking_type_model.dart | class BookingTypeModel {
String imagePath;
String text;
BookingTypeModel({this.imagePath = "", this.text = ""});
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/models/banner_image_model.dart | class BannerImageModel {
String imageUrl;
BannerImageModel({this.imageUrl = ""});
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/models/logo_image_model.dart | class LogoImageModel {
String imageUrl;
LogoImageModel({this.imageUrl = ""});
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/models/user.model.dart | enum Status { BUSY, NORMAL }
class UserModel {
String role;
Status status = Status.NORMAL;
String name;
String type;
String description;
UserModel({
required this.role,
required this.type,
required this.status,
required this.name,
required this.description,
});
void changeStatusWithMessage(String mes) {
if (mes == "ACPECT") {
status = Status.BUSY;
} else if (mes == "ENDTRIP") {
status = Status.NORMAL;
}
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/models/circular_image_widget_model.dart | class CircularImageModel {
String imageUrl;
CircularImageModel({this.imageUrl = ""});
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/util/notification_controller.dart | import 'dart:developer';
import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:flutter/material.dart';
void sendNotificationOrder() {
String title = "Đang gửi thông báo";
String body = "Đã có thông báo!";
NotificationController.createOrderStaffNotification(title, body);
}
class NotificationController {
static Future<void> initializeLocalNotifications() async {
await AwesomeNotifications().initialize(
null, //'resource://drawable/res_app_icon',//
[
NotificationChannel(
channelKey: 'order_channel',
channelName: 'order_channel',
channelDescription: 'Notification for order staff',
playSound: true,
onlyAlertOnce: true,
groupAlertBehavior: GroupAlertBehavior.Children,
importance: NotificationImportance.High,
defaultPrivacy: NotificationPrivacy.Private,
defaultColor: const Color(0xFF036292),
ledColor: Colors.white),
NotificationChannel(
channelKey: 'kitchen_channel',
channelName: 'kitchen_channel',
channelDescription: 'Notification for kitchen staff',
playSound: true,
onlyAlertOnce: true,
groupAlertBehavior: GroupAlertBehavior.Children,
importance: NotificationImportance.High,
defaultPrivacy: NotificationPrivacy.Private,
defaultColor: const Color(0xFF036292),
ledColor: Colors.white)
],
debug: false);
}
/// *********************************************
/// NOTIFICATION EVENTS LISTENER
/// *********************************************
/// Notifications events are only delivered after call this method
static Future<void> startListeningNotificationEvents() async {
AwesomeNotifications()
.setListeners(onActionReceivedMethod: onActionReceivedMethod);
}
/// *********************************************
/// NOTIFICATION EVENTS
/// *********************************************
///
@pragma('vm:entry-point')
static Future<void> onActionReceivedMethod(
ReceivedAction receivedAction) async {
if (receivedAction.channelKey == "order_channel") {
log("order_channel");
// MyApp.navigatorKey.currentState?.push(
// MaterialPageRoute(builder: (context) => ConfirmServingScreen()));
} else if (receivedAction.channelKey == "kitchen_channel") {
log("kitchen_channel");
// MyApp.navigatorKey.currentState?.push(MaterialPageRoute(
// builder: (context) =>
// KitchenScreen(restaurantID: Global.restaurantID)));
}
}
/// *********************************************
/// REQUESTING NOTIFICATION PERMISSIONS
/// *********************************************
///
static Future<bool> displayNotificationRationale() async {
return await AwesomeNotifications().requestPermissionToSendNotifications();
}
/// *********************************************
/// NOTIFICATION CREATION METHODS
/// *********************************************
///
static Future<void> createOrderStaffNotification(
String title, String body) async {
bool isAllowed = await AwesomeNotifications().isNotificationAllowed();
if (!isAllowed) isAllowed = await displayNotificationRationale();
if (!isAllowed) return;
await AwesomeNotifications().createNotification(
content: NotificationContent(
id: -1, // -1 is replaced by a random number
channelKey: 'order_channel',
title: title,
body: body,
largeIcon:
'https://play-lh.googleusercontent.com/RIU1oM-b4OadLlOuvhwvuzjw1fVh54gHNq-CQfT2UdOzOG6rajBVqPm3wkkKirxyPr0=s220',
notificationLayout: NotificationLayout.Default,
),
);
}
static Future<void> createKitchenNotification(
String title, String body) async {
bool isAllowed = await AwesomeNotifications().isNotificationAllowed();
if (!isAllowed) isAllowed = await displayNotificationRationale();
if (!isAllowed) return;
await AwesomeNotifications().createNotification(
content: NotificationContent(
id: -1, // -1 is replaced by a random number
channelKey: 'kitchen_channel',
title: title,
body: body,
largeIcon:
'https://play-lh.googleusercontent.com/RIU1oM-b4OadLlOuvhwvuzjw1fVh54gHNq-CQfT2UdOzOG6rajBVqPm3wkkKirxyPr0=s220',
notificationLayout: NotificationLayout.Default,
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/util/connectivity_handler.dart | import 'dart:async';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
class ConnectivityHandler {
static final ConnectivityHandler _instance = ConnectivityHandler._internal();
factory ConnectivityHandler() {
return _instance;
}
ConnectivityHandler._internal();
late StreamSubscription<ConnectivityResult> _subscription;
bool _showLoading = false;
void startListening(BuildContext context) {
_subscription = Connectivity().onConnectivityChanged.listen(
(ConnectivityResult result) {
if (result == ConnectivityResult.none) {
showNoInternetToast();
if (!_showLoading) {
showLoadingScreen(context);
}
} else {
// Internet connection is restored
if (_showLoading) {
Navigator.pop(context);
_showLoading = false;
}
}
},
);
}
bool isShowingLoadingScreen() {
return _showLoading;
}
void setLoadingScreen(bool showLoading) {
_showLoading = showLoading;
}
void stopListening() {
_subscription.cancel();
}
void showNoInternetToast() {
Fluttertoast.showToast(
msg: 'Mất kết nối internet. Vui lòng thử lại sau.',
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 5,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 20.0,
);
}
void showLoadingScreen(BuildContext context) {
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
_showLoading = true;
return Center(
child: Container(
padding: const EdgeInsets.all(16.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10.0),
),
child: const DefaultTextStyle(
style: TextStyle(decoration: TextDecoration.none),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
CircularProgressIndicator(
backgroundColor: Colors.lightBlue,
valueColor: AlwaysStoppedAnimation<Color>(Colors.orange),
strokeWidth: 5.0,
),
SizedBox(height: 16.0),
Text(
'Loading...',
style: TextStyle(
color: Colors.orange,
fontSize: 16.0,
fontWeight: FontWeight.bold,
),
),
],
),
),
),
);
},
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/screen/homeUser.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_map/plugin_api.dart';
import 'package:flutter_map_animations/flutter_map_animations.dart';
import 'package:latlong2/latlong.dart';
import 'package:skysoft_taxi/global/global.dart';
import 'package:skysoft_taxi/models/user.model.dart';
import '../url/contants.dart';
import '../widgets/user/reviews.dart';
//import '../widgets/destination_information.dart';
import '../widgets/user/searchOnPanalBar.dart';
import 'package:sliding_up_panel/sliding_up_panel.dart';
import '../widgets/user/panel_bar.dart';
import '../widgets/user/ride_requested.dart';
import '../widgets/user/car_info.dart';
import '../widgets/user/price_car.dart';
import '../widgets/user/side_bar.dart';
import '../widgets/user/sidebar_toggle_button .dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/status.dart' as status;
class Home extends StatefulWidget {
const Home({super.key});
@override
State<Home> createState() => HomeState();
}
class HomeState extends State<Home> with TickerProviderStateMixin {
late final _animatedMapController = AnimatedMapController(vsync: this);
final TextEditingController _textFieldController = TextEditingController();
final panelController = PanelController();
bool isPanelVisible = true; // Hiển thị panal bar
bool isPanelOpen = false; // kéo lên xuống panal bar
//bool isDestination = false; // hiển thị màn hình destinatiion_information
bool isReviews = false; // hiển thị màn hình review
bool isRequested = false; // hiển thị màn hình request
bool isDriverInfo = false; // hiển thị màn hình carinfor
bool isPriceCar = false; // hiển thị màn hình priceCar
final GlobalKey<ScaffoldState> _scaffoldKey =
GlobalKey(); // hiển thị side_bar
late IOWebSocketChannel channel;
@override
void initState() {
super.initState();
// channel.sink.add(jsonEncode({
// "message": "Booking",
// "sender": "Phạm Đức Đông",
// "receiver": "" //người nhận
// //"points": "[21.03735349640734, 105.78897826869654]",
// }));
channel = IOWebSocketChannel.connect(
"$URL_WS${userModel.role}_${userModel.name}");
channel.stream.listen((message) {
// print("ChatScreen: " + message);
final Map<String, dynamic> messageData = jsonDecode(message);
final String receivedMessage = messageData['message'];
driverModel.name = messageData['sender'];
if (receivedMessage == "ACPECT") {
if (userModel.status == Status.NORMAL) {
isRequested = false;
isDriverInfo = true;
userModel.changeStatusWithMessage("ACPECT");
print("${userModel.status}_user");
channel.sink.add(jsonEncode({
"message": "OK",
"sender": userModel.name,
"receiver": driverModel.name, //người nhận
"type": "private",
//"points": "[21.03735349640734, 105.78897826869654]",
}));
setState(() {});
}
} else if (receivedMessage == "KETTHUC") {
if (userModel.status == Status.BUSY) {
isDriverInfo = false;
isReviews = true;
userModel.changeStatusWithMessage("ENDTRIP");
print("${userModel.status}_user");
setState(() {});
}
}
});
}
@override
void dispose() {
channel.sink.close(status.goingAway);
_textFieldController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
drawer: const SideBar(),
key: _scaffoldKey,
body: GestureDetector(
onTap: () {
if (isPanelVisible) {
if (isPanelOpen) {
panelController.close();
} else {
panelController.open();
}
setState(() {
isPanelOpen = !isPanelOpen;
});
}
},
child: Stack(
children: [
FlutterMap(
options: MapOptions(
onTap: (tapPosition, point) {},
zoom: 15,
maxZoom: 18,
minZoom: 3,
center: const LatLng(21.053306461723658, 105.77996412889881),
),
mapController: _animatedMapController.mapController,
children: [
TileLayer(
urlTemplate: "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
subdomains: const ['a', 'b', 'c'],
userAgentPackageName: 'dev.fleaflet.flutter_map.example',
),
],
),
SidebarToggleButton(
scaffoldKey: _scaffoldKey, // Pass the scaffoldKey to the widget
),
//search_onpanlbar
Visibility(
visible: isPanelVisible,
child: SlidingUpPanel(
minHeight: 110,
borderRadius:
const BorderRadius.vertical(top: Radius.circular(20.0)),
backdropEnabled: true,
controller: panelController,
panel: Material(
borderRadius:
const BorderRadius.vertical(top: Radius.circular(20.0)),
child: PanelBar(
panelController: panelController,
onTextFieldPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const Material(
child: SearchOnPanalBar(),
),
),
).then((value) {
if (value == 'startButtonPressed') {
isPanelVisible = false;
isPriceCar = true;
setState(() {});
}
});
},
)),
),
),
//màn hình reviews
Visibility(
visible: isReviews,
child: SlidingUpPanel(
minHeight: 300,
maxHeight: 600,
backdropEnabled: true,
controller: panelController,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(20.0),
topRight: Radius.circular(20.0),
),
panel: Material(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(20.0),
topRight: Radius.circular(20.0),
),
child: Reviews(
panelController: panelController,
onClose: () {
isReviews = false;
isPanelVisible = true;
setState(() {});
userModel.changeStatusWithMessage("ENDTRIP");
print("${driverModel.status}user");
},
),
),
),
),
//màn hình price car
Visibility(
visible: isPriceCar,
child: GestureDetector(
child: Stack(
children: [
Positioned(
top: 40.0,
left: 16.0,
right: 16.0,
child: TextField(
readOnly: true,
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const Material(
child: SearchOnPanalBar(),
),
),
);
},
controller: _textFieldController,
decoration: InputDecoration(
hintText: 'Hà Nội',
filled: true,
fillColor: Colors.grey[200],
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
),
suffixIcon: IconButton(
icon: const Icon(Icons.close),
onPressed: () {
_textFieldController.clear();
isPriceCar = false;
isDriverInfo = true;
//isPanelVisible = true;
// userModel.changeStatusWithMessage("ENDTRIP");
// print(driverModel.status.toString() + "user");
setState(() {});
},
),
),
),
),
SlidingUpPanel(
minHeight: 550,
maxHeight: 550,
isDraggable: false,
backdropEnabled: true,
borderRadius: const BorderRadius.vertical(
top: Radius.circular(20.0)),
panel: Material(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(20.0),
topRight: Radius.circular(20.0),
),
child: PriceCar(
//panelController: panelController,
onBookNow: () {
channel.sink.add(jsonEncode({
"message": "BOOKING",
"sender": userModel.name,
"receiver": driverModel.name, //người nhận
"type": "public",
//"points": "[21.03735349640734, 105.78897826869654]",
}));
isPriceCar = false;
isRequested = true;
print("${userModel.status}user");
print("${driverModel.status}driver");
setState(() {});
},
),
),
),
],
),
),
),
//màn hình ride requested
Visibility(
visible: isRequested,
child: SlidingUpPanel(
minHeight: 250,
maxHeight: 250,
isDraggable: false,
backdropEnabled: true,
borderRadius:
const BorderRadius.vertical(top: Radius.circular(20.0)),
panel: Material(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(20.0),
topRight: Radius.circular(20.0),
),
child: RideRequested(
onCancelRequest: () {
channel.sink.add(jsonEncode({
"message": "CANCELREQUEST",
"sender": userModel.name,
"receiver": driverModel.name, //người nhận
"type": "public",
//"points": "[21.03735349640734, 105.78897826869654]",
}));
isRequested = false;
isPriceCar = true;
setState(() {});
},
),
),
),
),
//màn hình DriverInfor
Visibility(
visible: isDriverInfo,
child: SlidingUpPanel(
minHeight: 500,
maxHeight: 500,
backdropEnabled: true,
borderRadius:
const BorderRadius.vertical(top: Radius.circular(20.0)),
panel: Material(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(20.0),
topRight: Radius.circular(20.0),
),
child: DriverInfo(
cancelTrip: () {
channel.sink.add(jsonEncode({
"message": "CANCELTRIP",
"sender": userModel.name,
"receiver": driverModel.name, //người nhận
"type": "public",
//"points": "[21.03735349640734, 105.78897826869654]",
}));
isDriverInfo = false;
isPanelVisible = true;
userModel.changeStatusWithMessage("ENDTRIP");
print("${userModel.status}user");
print("${driverModel.status}driver");
setState(() {});
},
),
),
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/screen/homeUser1.dart | import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'dart:typed_data';
import 'package:audio_session/audio_session.dart' as a_s;
import 'package:audioplayers/audioplayers.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_map/plugin_api.dart';
import 'package:flutter_map_animations/flutter_map_animations.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:latlong2/latlong.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:skysoft_taxi/global/global.dart';
import 'package:skysoft_taxi/models/user.model.dart';
import 'package:skysoft_taxi/url/contants.dart';
import 'package:skysoft_taxi/widgets/user/side_bar.dart';
import 'package:skysoft_taxi/widgets/user/sidebar_toggle_button%20.dart';
import 'package:sliding_up_panel/sliding_up_panel.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/status.dart' as status;
import 'package:flutter/services.dart' show rootBundle;
class Home1 extends StatefulWidget {
const Home1({super.key});
@override
State<Home1> createState() => HomeState();
}
typedef Fn = void Function();
class HomeState extends State<Home1> with TickerProviderStateMixin {
late final _animatedMapController = AnimatedMapController(vsync: this);
final TextEditingController _textFieldController = TextEditingController();
final panelController = PanelController();
bool isPanelVisible = false; // Hiển thị panal bar
bool isPanelOpen = false; // kéo lên xuống panal bar
bool isReviews = false; // hiển thị màn hình review
bool isRequested = false; // hiển thị màn hình request
bool isDriverInfo = false; // hiển thị màn hình carinfor
bool isPriceCar = false; // hiển thị màn hình priceCar
bool isSound = true;
final GlobalKey<ScaffoldState> _scaffoldKey =
GlobalKey(); // hiển thị side_bar
late IOWebSocketChannel channel;
final player = AudioPlayer();
String _tempDirectory = "";
final FlutterSoundRecorder _mRecorder = FlutterSoundRecorder();
Codec _codec = Codec.aacMP4;
String _mPath = 'tau_file.mp4';
bool _mRecorderIsInited = false;
double _mSubscriptionDuration = 0;
StreamSubscription? _recorderSubscription;
int pos = 0;
double dbLevel = 0;
Future<Uint8List> getAssetData(String path) async {
var asset = await rootBundle.load(path);
return asset.buffer.asUint8List();
}
Future<void> openTheRecorder() async {
await _mRecorder.openRecorder();
final session = await a_s.AudioSession.instance;
await session.configure(a_s.AudioSessionConfiguration(
avAudioSessionCategory: a_s.AVAudioSessionCategory.playAndRecord,
avAudioSessionCategoryOptions:
a_s.AVAudioSessionCategoryOptions.allowBluetooth |
a_s.AVAudioSessionCategoryOptions.defaultToSpeaker,
avAudioSessionMode: a_s.AVAudioSessionMode.spokenAudio,
avAudioSessionRouteSharingPolicy:
a_s.AVAudioSessionRouteSharingPolicy.defaultPolicy,
avAudioSessionSetActiveOptions: a_s.AVAudioSessionSetActiveOptions.none,
androidAudioAttributes: const a_s.AndroidAudioAttributes(
contentType: a_s.AndroidAudioContentType.speech,
flags: a_s.AndroidAudioFlags.none,
usage: a_s.AndroidAudioUsage.voiceCommunication,
),
androidAudioFocusGainType: a_s.AndroidAudioFocusGainType.gain,
androidWillPauseWhenDucked: true,
));
_mRecorderIsInited = true;
}
Future<void> init() async {
PermissionStatus status = await Permission.microphone.request();
if (status != PermissionStatus.granted) {
log("Chưa cấp quyền microphone");
}
status = await Permission.storage.request();
if (status != PermissionStatus.granted) {
log("Chưa cấp quyền thư mục");
}
_mRecorder.closeRecorder();
await openTheRecorder();
log("init 1");
_recorderSubscription = _mRecorder.onProgress!.listen((e) {
log("init _recorderSubscription");
setState(() {
pos = e.duration.inMilliseconds;
if (e.decibels != null) {
dbLevel = e.decibels as double;
}
});
});
}
void record(FlutterSoundRecorder? recorder) async {
await recorder!.startRecorder(
codec: Codec.aacMP4,
toFile: _tempDirectory + "/" + _mPath,
bitRate: 8000,
numChannels: 1,
sampleRate: 8000,
);
setState(() {});
}
Future<void> stopRecorder(FlutterSoundRecorder recorder) async {
await recorder.stopRecorder().then((value) {
log("record: ${value}");
});
;
}
Future<void> setSubscriptionDuration(
double d) async // v is between 0.0 and 2000 (milliseconds)
{
_mSubscriptionDuration = d;
setState(() {});
await _mRecorder.setSubscriptionDuration(
Duration(milliseconds: d.floor()),
);
}
@override
void initState() {
super.initState();
channel = IOWebSocketChannel.connect(
URL_CHAT + userModel.role + "_" + userModel.name);
channel.stream.listen((message) {
// print("ChatScreen: " + message);
final Map<String, dynamic> messageData = jsonDecode(message);
final String receivedMessage = messageData['message'];
driverModel.name = messageData['sender'];
if (receivedMessage == "ACPECT") {
if (userModel.status == Status.NORMAL) {
isRequested = false;
isDriverInfo = true;
userModel.changeStatusWithMessage("ACPECT");
print(userModel.status.toString() + "_" + "user");
channel.sink.add(jsonEncode({
"message": "OK",
"sender": userModel.name,
"receiver": driverModel.name, //người nhận
"type": "private",
//"points": "[21.03735349640734, 105.78897826869654]",
}));
setState(() {});
}
} else if (receivedMessage == "KETTHUC") {
if (userModel.status == Status.BUSY) {
isDriverInfo = false;
isReviews = true;
userModel.changeStatusWithMessage("ENDTRIP");
print(userModel.status.toString() + "_" + "user");
setState(() {});
}
}
});
getApplicationDocumentsDirectory().then((value) {
log("Path: ${value}");
_tempDirectory = value.path;
});
init().then((value) {
setState(() {
_mRecorderIsInited = true;
});
});
}
@override
void dispose() {
channel.sink.close(status.goingAway);
_textFieldController.dispose();
player.dispose();
stopRecorder(_mRecorder);
cancelRecorderSubscriptions();
// Be careful : you must `close` the audio session when you have finished with it.
_mRecorder.closeRecorder();
super.dispose();
}
void cancelRecorderSubscriptions() {
if (_recorderSubscription != null) {
_recorderSubscription!.cancel();
_recorderSubscription = null;
}
}
Fn? getPlaybackFn(FlutterSoundRecorder? recorder) {
if (!_mRecorderIsInited) {
log("getPlaybackFn: ${_mRecorderIsInited}");
return null;
}
return recorder!.isStopped
? () {
record(recorder);
}
: () {
stopRecorder(recorder).then((value) => setState(() {}));
};
}
@override
Widget build(BuildContext context) {
return Scaffold(
drawer: const SideBar(),
key: _scaffoldKey,
body: GestureDetector(
onTap: () {
if (isPanelVisible) {
if (isPanelOpen) {
panelController.close();
} else {
panelController.open();
}
setState(() {
isPanelOpen = !isPanelOpen;
});
}
},
child: Stack(
children: [
FlutterMap(
options: MapOptions(
onTap: (tapPosition, point) {},
zoom: 15,
maxZoom: 18,
minZoom: 3,
center: const LatLng(21.053306461723658, 105.77996412889881),
),
mapController: _animatedMapController.mapController,
children: [
TileLayer(
urlTemplate: "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
subdomains: const ['a', 'b', 'c'],
userAgentPackageName: 'dev.fleaflet.flutter_map.example',
),
],
),
SidebarToggleButton(
scaffoldKey: _scaffoldKey, // Pass the scaffoldKey to the widget
),
Visibility(
visible: isSound,
child: SlidingUpPanel(
minHeight: 110,
borderRadius:
const BorderRadius.vertical(top: Radius.circular(20.0)),
backdropEnabled: true,
controller: panelController,
panel: Material(
borderRadius:
const BorderRadius.vertical(top: Radius.circular(20.0)),
child: Column(
children: [
ElevatedButton(
onPressed: getPlaybackFn(_mRecorder),
child: Text(
_mRecorder.isRecording ? 'Stop' : 'Record')),
ElevatedButton(
onPressed: () async {
try {
FilePickerResult? result =
await FilePicker.platform.pickFiles();
if (result != null) {
log(result.files.single.path!);
// File file = File(result.files.single.path!);
} else {
// User canceled the picker
}
} catch (e) {
print(e);
}
},
child: Text("Choose file")),
ElevatedButton(
onPressed: () async {
try {
await player.play(UrlSource(
'http://192.168.1.75:8080/devxelo/rest/chat/1.mp3'));
} catch (e) {
print(e);
}
},
child: Text("Play sound")),
],
)),
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/screen/home.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_map/plugin_api.dart';
import 'package:flutter_map_animations/flutter_map_animations.dart';
import 'package:latlong2/latlong.dart';
import 'package:skysoft_taxi/global/global.dart';
import 'package:skysoft_taxi/models/user.model.dart';
import '../url/contants.dart';
import '../widgets/user/reviews.dart';
//import '../widgets/destination_information.dart';
import '../widgets/user/searchOnPanalBar.dart';
import 'package:sliding_up_panel/sliding_up_panel.dart';
import '../widgets/user/panel_bar.dart';
import '../widgets/user/ride_requested.dart';
import '../widgets/user/car_info.dart';
import '../widgets/user/price_car.dart';
import '../widgets/user/side_bar.dart';
import '../widgets/user/sidebar_toggle_button .dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/status.dart' as status;
class Home extends StatefulWidget {
const Home({super.key});
@override
State<Home> createState() => HomeState();
}
class HomeState extends State<Home> with TickerProviderStateMixin {
late final _animatedMapController = AnimatedMapController(vsync: this);
final TextEditingController _textFieldController = TextEditingController();
final panelController = PanelController();
bool isPanelVisible = true; // Hiển thị panal bar
bool isPanelOpen = false; // kéo lên xuống panal bar
//bool isDestination = false; // hiển thị màn hình destinatiion_information
bool isReviews = false; // hiển thị màn hình review
bool isRequested = false; // hiển thị màn hình request
bool isDriverInfo = false; // hiển thị màn hình carinfor
bool isPriceCar = false; // hiển thị màn hình priceCar
final GlobalKey<ScaffoldState> _scaffoldKey =
GlobalKey(); // hiển thị side_bar
late IOWebSocketChannel channel;
@override
void initState() {
super.initState();
// channel.sink.add(jsonEncode({
// "message": "Booking",
// "sender": "Phạm Đức Đông",
// "receiver": "" //người nhận
// //"points": "[21.03735349640734, 105.78897826869654]",
// }));
channel = IOWebSocketChannel.connect(
URL_CHAT + userModel.role + "_" + userModel.name);
channel.stream.listen((message) {
print("ChatScreen: " + message);
final Map<String, dynamic> messageData = jsonDecode(message);
final String receivedMessage = messageData['message'];
driverModel.name = messageData['sender'];
if (receivedMessage == "ACPECT") {
if (userModel.status == Status.BUSY) {
isRequested = false;
isDriverInfo = true;
setState(() {});
userModel.changeStatusWithMessage("ACPECT");
print(userModel.status.toString() + "user");
}
} else if (receivedMessage == "KETTHUC") {
if (userModel.status != Status.NORMAL) {
isDriverInfo = false;
isReviews = true;
setState(() {});
}
}
});
}
@override
void dispose() {
channel.sink.close(status.goingAway);
_textFieldController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
drawer: const SideBar(),
key: _scaffoldKey,
body: GestureDetector(
onTap: () {
if (isPanelVisible) {
if (isPanelOpen) {
panelController.close();
} else {
panelController.open();
}
setState(() {
isPanelOpen = !isPanelOpen;
});
}
},
child: Stack(
children: [
FlutterMap(
options: MapOptions(
onTap: (tapPosition, point) {},
zoom: 15,
maxZoom: 18,
minZoom: 3,
center: const LatLng(21.053306461723658, 105.77996412889881),
),
mapController: _animatedMapController.mapController,
children: [
TileLayer(
urlTemplate: "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
subdomains: const ['a', 'b', 'c'],
userAgentPackageName: 'dev.fleaflet.flutter_map.example',
),
],
),
SidebarToggleButton(
scaffoldKey: _scaffoldKey, // Pass the scaffoldKey to the widget
),
//search_onpanlbar
Visibility(
visible: isPanelVisible,
child: SlidingUpPanel(
minHeight: 110,
borderRadius:
const BorderRadius.vertical(top: Radius.circular(20.0)),
backdropEnabled: true,
controller: panelController,
panel: Material(
borderRadius:
const BorderRadius.vertical(top: Radius.circular(20.0)),
child: PanelBar(
panelController: panelController,
onTextFieldPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const Material(
child: SearchOnPanalBar(),
),
),
).then((value) {
if (value == 'startButtonPressed') {
isPanelVisible = false;
isPriceCar = true;
setState(() {});
userModel.changeStatusWithMessage("ACPECT");
print(userModel.status.toString() + "user");
}
});
},
),
),
),
),
//màn hình reviews
Visibility(
visible: isReviews,
child: SlidingUpPanel(
minHeight: 300,
maxHeight: 600,
backdropEnabled: true,
controller: panelController,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(20.0),
topRight: Radius.circular(20.0),
),
panel: Material(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(20.0),
topRight: Radius.circular(20.0),
),
child: Reviews(
panelController: panelController,
onClose: () {
isReviews = false;
isPanelVisible = true;
setState(() {});
userModel.changeStatusWithMessage("ENDTRIP");
print(driverModel.status.toString() + "user");
},
),
),
),
),
//màn hình price car
Visibility(
visible: isPriceCar,
child: GestureDetector(
child: Stack(
children: [
Positioned(
top: 40.0,
left: 16.0,
right: 16.0,
child: TextField(
readOnly: true,
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const Material(
child: SearchOnPanalBar(),
),
),
);
},
controller: _textFieldController,
decoration: InputDecoration(
hintText: 'Hà Nội',
filled: true,
fillColor: Colors.grey[200],
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
),
suffixIcon: IconButton(
icon: const Icon(Icons.close),
onPressed: () {
_textFieldController.clear();
//isReviews = true; //test man reviews.
//isRequested = true; //test man ride request
isPriceCar = false;
//isCarInfo = true;
isPanelVisible = true;
setState(() {});
},
),
),
),
),
SlidingUpPanel(
minHeight: 550,
maxHeight: 550,
isDraggable: false,
backdropEnabled: true,
borderRadius: const BorderRadius.vertical(
top: Radius.circular(20.0)),
panel: Material(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(20.0),
topRight: Radius.circular(20.0),
),
child: PriceCar(
//panelController: panelController,
onBookNow: () {
channel.sink.add(jsonEncode({
"message": "BOOKING",
"sender": userModel.name,
"receiver": driverModel.name //người nhận
//"points": "[21.03735349640734, 105.78897826869654]",
}));
isPriceCar = false;
isRequested = true;
setState(() {});
},
),
),
),
],
),
),
),
//màn hình ride requested
Visibility(
visible: isRequested,
child: SlidingUpPanel(
minHeight: 250,
maxHeight: 250,
isDraggable: false,
backdropEnabled: true,
borderRadius:
const BorderRadius.vertical(top: Radius.circular(20.0)),
panel: Material(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(20.0),
topRight: Radius.circular(20.0),
),
child: RideRequested(
onCancelRequest: () {
channel.sink.add(jsonEncode({
"message": "CANCELREQUEST",
"sender": userModel.name,
"receiver": driverModel.name //người nhận
//"points": "[21.03735349640734, 105.78897826869654]",
}));
isRequested = false;
isPriceCar = true;
setState(() {});
},
),
),
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/screen | mirrored_repositories/Skysoft_Taxi/lib/screen/xanh_sm_clone_User/user_chat_all.dart | import 'package:flutter/material.dart';
import 'package:skysoft_taxi/view/message_view.dart';
import '../../audiochat_widget/input_voice.dart';
import '../../global/global.dart';
import '../../services/ChatService.dart';
class UserChatAll extends StatefulWidget {
const UserChatAll({Key? key}) : super(key: key);
@override
State createState() => UserChatAllState();
}
class UserChatAllState extends State<UserChatAll>
with SingleTickerProviderStateMixin {
DateTime? time;
final List<MessageView> messages = [];
ScrollController? controller = ScrollController();
TextEditingController messageController = TextEditingController();
@override
void initState() {
super.initState();
getAll().then(
(List<dynamic>? value) {
if (value != null) {
for (var element in value) {
messages.add(MessageView(
content: element["chatId"],
rightSide: element["name"] == userModel.name));
}
setState(() {});
controller!.animateTo(
messages.length * 200,
duration: const Duration(milliseconds: 500),
curve: Curves.fastOutSlowIn,
);
}
},
);
}
@override
void dispose() {
messageController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
toolbarHeight: MediaQuery.of(context).size.height * 0.10,
backgroundColor: Colors.blue.shade600,
title: Text(
driverModel.name,
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
actions: const [
Padding(
padding: EdgeInsets.only(right: 16.0),
child: CircleAvatar(
radius: 40,
backgroundImage: NetworkImage(
'https://yt3.googleusercontent.com/-CFTJHU7fEWb7BYEb6Jh9gm1EpetvVGQqtof0Rbh-VQRIznYYKJxCaqv_9HeBcmJmIsp2vOO9JU=s900-c-k-c0x00ffffff-no-rj',
),
),
),
],
),
body: Padding(
padding: const EdgeInsets.only(bottom: 55),
child: Column(
children: <Widget>[
_buildMessageInputField(),
InputVoice(
onDone: (bool, String) {},
),
],
),
),
);
}
Widget _buildMessageInputField() {
return Container(
padding: const EdgeInsets.all(10.0),
child: Row(
children: [
IconButton(
icon: const Icon(
Icons.mic,
color: Colors.redAccent,
),
onPressed: () {},
),
Expanded(
child: TextField(
controller: messageController,
decoration: const InputDecoration(
hintText: 'Tin nhắn của bạn...',
),
),
),
IconButton(
icon: const Icon(
Icons.send,
color: Colors.blueAccent,
),
onPressed: () {},
),
],
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/screen | mirrored_repositories/Skysoft_Taxi/lib/screen/xanh_sm_clone_User/goi_xe.dart | import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:skysoft_taxi/global/global.dart';
import 'package:skysoft_taxi/models/banner_image_model.dart';
import 'package:skysoft_taxi/models/booking_type_model.dart';
import 'package:skysoft_taxi/screen/xanh_sm_clone_User/chon_diem_den.dart';
import 'package:skysoft_taxi/screen/xanh_sm_clone_User/luu_diem_don.dart';
import 'package:skysoft_taxi/screen/xanh_sm_clone_User/tim_diem_den%20_nhanh.dart';
import 'package:skysoft_taxi/widgets/imageWidget/banner_image.dart';
import 'package:skysoft_taxi/widgets/imageWidget/slide_image_horizontal.dart';
import 'package:skysoft_taxi/widgets/button/button_icon_booking_type.dart';
import 'package:skysoft_taxi/widgets/button/button_save_maker.dart';
import '../../models/save_marker_model.dart';
class BookingCar extends StatefulWidget {
const BookingCar({Key? key}) : super(key: key);
@override
State<BookingCar> createState() => _BookingCarState();
}
class _BookingCarState extends State<BookingCar> {
List<String> imageSlider = [
'https://www.ganeshawebtech.com/wp-content/uploads/2018/06/Get-your-taxi-business-an-edge-by-getting-a-Taxi-booking-apps.jpg',
'https://i.ytimg.com/vi/PN3YyMcHuhc/maxresdefault.jpg',
'https://fiverr-res.cloudinary.com/images/t_main1,q_auto,f_auto,q_auto,f_auto/gigs/263260978/original/01063a5489f4f3bccd2ae5db726c2f156dfbc6e0/taxi-booking-app-car-booking-app-taxi-app-uber-clone-app-car-rental-app.jpg',
'https://cdn.grabon.in/gograbon/images/merchant/1624792553223.jpg',
'https://couponswala.com/blog/wp-content/uploads/2021/08/goibibo-cab-coupons.jpg',
'https://www.icoderzsolutions.com/blog/wp-content/uploads/2021/03/5-Steps-In-Hiring-The-Best-Taxi-App-Development-Company.png',
];
// List options type vehicle
List<BookingTypeModel> listBookingType = [
BookingTypeModel(
imagePath: 'https://cdn-icons-png.flaticon.com/512/1801/1801444.png',
text: 'Ô tô'),
BookingTypeModel(
imagePath:
'https://cdn2.iconfinder.com/data/icons/transportation-colorized/64/transportation-vehicle-11-512.png',
text: 'Xe máy',
),
BookingTypeModel(
imagePath:
'https://icon-library.com/images/on-time-icon/on-time-icon-13.jpg',
text: 'Thuê xe theo giờ',
),
BookingTypeModel(
imagePath: 'https://www.airasia.com/aa/ride/images/icon-car.png',
text: 'Sân bay',
),
BookingTypeModel(
imagePath: 'https://cdn-icons-png.flaticon.com/512/4234/4234147.png',
text: 'Đặt xe cho bạn bè',
),
BookingTypeModel(
imagePath: 'https://cdn-icons-png.flaticon.com/512/6947/6947616.png',
text: 'Giao Hàng',
),
BookingTypeModel(
imagePath: 'https://cdn-icons-png.flaticon.com/512/776/776443.png',
text: 'Đồ ăn',
),
BookingTypeModel(
imagePath: 'https://cdn-icons-png.flaticon.com/512/5952/5952766.png',
text: 'Giao Hàng Ô tô',
),
];
late List<SaveMakerModel> listButtonSaveMaker;
// banner behind usernames
BannerImageModel bannerImageModel = BannerImageModel(
imageUrl:
"https://www.taxionthego.com/wp-content/uploads/2019/12/banner_1-min.jpg",
);
@override
void initState() {
super.initState();
listButtonSaveMaker = [
SaveMakerModel(
icon: Icons.home,
text: 'Nhà riêng',
onTap: () => {
log('Nhà riêng'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
)
},
),
SaveMakerModel(
icon: Icons.work,
text: 'Công ty',
onTap: () => {
log('Công ty'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.restaurant,
text: 'Nhà hàng',
onTap: () => {
log('Nhà hàng'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.coffee,
text: 'Coffee',
onTap: () => {
log('Coffee'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.hotel,
text: 'Khách sạn',
onTap: () => {
log('Khách sạn'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.shopping_cart,
text: 'Trung tâm thương mại',
onTap: () => {
log('Trung tâm thương mại'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.local_atm,
text: 'ATMs',
onTap: () => {
log('ATMs'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.emergency,
text: 'Bệnh viện',
onTap: () => {
log('Bệnh viện'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.medication,
text: 'Hiệu thuốc',
onTap: () => {
log('Hiệu thuốc'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.garage,
text: 'Nhà để xe',
onTap: () => {
log('Nhà để xe'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.local_gas_station,
text: 'Trạm xăng',
onTap: () => {
log('Trạm xăng'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.ev_station,
text: 'Trạm sạc điện',
onTap: () => {
log('Trạm sạc điện'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.pin_drop,
text: 'Thêm địa điểm',
onTap: () => {
log('Thêm địa điểm'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
];
}
@override
Widget build(BuildContext context) {
double screenHeight = MediaQuery.of(context).size.height;
return Scaffold(
body: Padding(
padding: const EdgeInsets.only(bottom: 50),
child: ListView(
shrinkWrap: true,
physics: const BouncingScrollPhysics(),
children: [
Container(
color: const Color.fromARGB(242, 244, 243, 255),
child: Stack(
children: [
Column(
children: [
SizedBox(
height: screenHeight / 4,
child: Stack(
children: [
BannerImage(imageUrl: bannerImageModel.imageUrl),
Positioned.fill(
child: Container(
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.5),
),
),
),
Positioned(
top: 90,
left: 20,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
'Xin chào ${userModel.name}',
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 22,
fontStyle: FontStyle.italic,
),
overflow: TextOverflow.ellipsis,
maxLines: 3,
),
const SizedBox(
width: 5,
),
const Icon(
Icons.waving_hand,
color: Colors.white,
),
],
)
],
),
),
],
),
),
const SizedBox(height: 50),
SizedBox(
width: 0.9 * MediaQuery.of(context).size.width,
height: 50,
child: ListView.builder(
physics: const BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
itemCount: listButtonSaveMaker.length,
itemBuilder: (context, index) {
SaveMakerModel item = listButtonSaveMaker[index];
return ButtonSaveMaker(
icon: item.icon,
text: item.text,
onTap: item.onTap,
);
},
),
),
const SizedBox(height: 30),
SizedBox(
width: 0.9 * MediaQuery.of(context).size.width,
height: 90,
child: ListView.builder(
physics: const BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
itemCount: listBookingType.length,
itemBuilder: (context, index) {
BookingTypeModel item = listBookingType[index];
return ButtonIconBookingType(
imagePath: item.imagePath,
text: item.text,
onTap: () {
log(item.text);
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const ChooseDestination();
},
),
);
},
);
},
),
),
const SizedBox(height: 10),
HorizontalImageSlider(
imageUrls: imageSlider,
),
],
),
Padding(
padding: EdgeInsets.symmetric(
horizontal: 0.05 * MediaQuery.of(context).size.width,
vertical: 0.22 * MediaQuery.of(context).size.height,
),
child: GestureDetector(
onTap: () {
log("Bạn muốn đi đâu ?");
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const ChooseDestination();
},
),
);
},
child: Container(
height: 52,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(15.0),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
spreadRadius: 0.1,
blurRadius: 20,
offset: const Offset(0, 10),
),
],
),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10.0,
vertical: 0.2,
),
child: Row(
children: [
const Icon(Icons.flag,
color: Color.fromARGB(255, 255, 64, 64)),
const SizedBox(width: 10),
const Text(
'Bạn muốn đi đâu ?',
style: TextStyle(
fontSize: 16,
color: Colors.black,
fontWeight: FontWeight.w400,
fontStyle: FontStyle.italic,
),
overflow: TextOverflow.ellipsis,
),
const Spacer(),
ElevatedButton(
onPressed: () {
log("bản đồ");
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const QuickFindPlaces();
},
),
);
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.grey.shade200,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0),
),
padding: const EdgeInsets.symmetric(
horizontal: 5, vertical: 8),
elevation: 0,
),
child: const Row(
children: [
Icon(
Icons.map,
size: 13,
color: Colors.black,
),
SizedBox(width: 2),
Text(
'Bản Đồ',
style: TextStyle(
fontSize: 12,
color: Colors.black,
fontWeight: FontWeight.w500,
),
),
],
),
),
],
),
),
),
),
),
],
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/screen | mirrored_repositories/Skysoft_Taxi/lib/screen/xanh_sm_clone_User/chon_diem_den.dart | import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:skysoft_taxi/models/save_marker_model.dart';
import 'package:skysoft_taxi/screen/xanh_sm_clone_User/luu_diem_don.dart';
import 'package:skysoft_taxi/screen/xanh_sm_clone_User/tim_diem_den%20_nhanh.dart';
import 'package:skysoft_taxi/widgets/button/button_save_maker.dart';
import 'package:skysoft_taxi/widgets/destination_header.dart';
import 'package:skysoft_taxi/widgets/history_widget.dart';
class ChooseDestination extends StatefulWidget {
const ChooseDestination({Key? key}) : super(key: key);
@override
_ChooseDestinationState createState() => _ChooseDestinationState();
}
class _ChooseDestinationState extends State<ChooseDestination> {
final TextEditingController _pickupController = TextEditingController();
final TextEditingController _destinationController = TextEditingController();
late List<SaveMakerModel> listButtonSaveMaker;
@override
void initState() {
super.initState();
listButtonSaveMaker = [
SaveMakerModel(
icon: Icons.home,
text: 'Nhà riêng',
onTap: () => {
log('Nhà riêng'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
)
},
),
SaveMakerModel(
icon: Icons.work,
text: 'Công ty',
onTap: () => {
log('Công ty'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.restaurant,
text: 'Nhà hàng',
onTap: () => {
log('Nhà hàng'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.coffee,
text: 'Coffee',
onTap: () => {
log('Coffee'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.hotel,
text: 'Khách sạn',
onTap: () => {
log('Khách sạn'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.shopping_cart,
text: 'Trung tâm thương mại',
onTap: () => {
log('Trung tâm thương mại'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.local_atm,
text: 'ATMs',
onTap: () => {
log('ATMs'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.emergency,
text: 'Bệnh viện',
onTap: () => {
log('Bệnh viện'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.medication,
text: 'Hiệu thuốc',
onTap: () => {
log('Hiệu thuốc'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.garage,
text: 'Nhà để xe',
onTap: () => {
log('Nhà để xe'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.local_gas_station,
text: 'Trạm xăng',
onTap: () => {
log('Trạm xăng'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.ev_station,
text: 'Trạm sạc điện',
onTap: () => {
log('Trạm sạc điện'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
SaveMakerModel(
icon: Icons.pin_drop,
text: 'Thêm địa điểm',
onTap: () => {
log('Thêm địa điểm'),
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const SaveMakerPlaces();
},
),
),
},
),
];
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: const EdgeInsets.all(10),
color: const Color.fromARGB(242, 244, 243, 255),
child: Column(
children: <Widget>[
DestinationHeader(
pickupController: _pickupController,
destinationController: _destinationController,
onBack: () {
Navigator.of(context).pop();
},
navigateToQuickFindPlaces: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const QuickFindPlaces();
},
),
);
},
),
SingleChildScrollView(
child: Column(
children: [
const SizedBox(height: 10),
const Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Đã lưu',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 15,
),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
Text(
'Tất cả',
style: TextStyle(
color: Colors.cyan,
fontWeight: FontWeight.w500,
fontSize: 15,
),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
],
),
SizedBox(
width: 0.9 * MediaQuery.of(context).size.width,
height: 50,
child: ListView.builder(
physics: const BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
itemCount: listButtonSaveMaker.length,
itemBuilder: (context, index) {
SaveMakerModel item = listButtonSaveMaker[index];
return ButtonSaveMaker(
icon: item.icon,
text: item.text,
onTap: item.onTap,
);
},
),
),
const SizedBox(height: 5),
const Row(
children: [
Text(
'Đã đi',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 15,
),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
],
),
],
),
),
Expanded(
child: ListView.builder(
physics: const BouncingScrollPhysics(),
itemCount: 3,
itemBuilder: (context, index) {
return Column(
children: [
HistoryWidget(
iconLeft: Icons.history,
text:
'Tầng 2, 21B5 GreenStars, Khu ĐT Tp Giao Lưu, P. Cổ Nhuế 1, Q. Bắc Từ Liêm, Hà Nội',
onTap: () {
log('Hạng thành viên');
},
),
],
);
},
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/screen | mirrored_repositories/Skysoft_Taxi/lib/screen/xanh_sm_clone_User/hoat_dong.dart | import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:skysoft_taxi/models/banner_image_model.dart';
import 'package:skysoft_taxi/models/circular_image_widget_model.dart';
import 'package:skysoft_taxi/screen/xanh_sm_clone_User/chon_diem_den.dart';
import 'package:skysoft_taxi/widgets/imageWidget/banner_image.dart';
import 'package:skysoft_taxi/widgets/imageWidget/circular_image_widget.dart';
class ActivityDaily extends StatefulWidget {
const ActivityDaily({Key? key}) : super(key: key);
@override
State<ActivityDaily> createState() => _ActivityDailyState();
}
class _ActivityDailyState extends State<ActivityDaily> {
BannerImageModel bannerImageModel = BannerImageModel(
imageUrl: "https://toataxis.co.uk/uploads/toa-banner-image-3.jpg.webp",
);
CircularImageModel circularImageModel = CircularImageModel(
imageUrl:
"https://image.winudf.com/v2/image1/Y29tLnNreXNvZnQuZ3BzX2ljb25fMTU1OTE4NzY5NF8wMjQ/icon.png?w=184&fakeurl=1",
);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
Container(
color: const Color.fromARGB(242, 244, 243, 255),
child: ListView(
physics: BouncingScrollPhysics(),
children: [
BannerImage(imageUrl: bannerImageModel.imageUrl),
Stack(
alignment: Alignment.center,
children: [
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(height: 40),
CircularImageWidget(
imageUrl: circularImageModel.imageUrl),
const SizedBox(height: 10),
const Text(
'Bạn đã trải nghiệm\nxe Xelo chưa?',
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 5),
const Text(
'Hơn 1 triệu chuyến đi đã được tài xế Xelo phục vụ chỉ \n trong 10 tuần đầu tiên.',
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.normal,
),
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 10),
ElevatedButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return const ChooseDestination();
},
),
);
log('Đặt xe ngay');
},
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(
vertical: 10,
horizontal:
MediaQuery.of(context).size.width * 0.1,
),
backgroundColor: Colors.green,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0),
),
),
child: const Text(
'Đặt xe ngay',
style: TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.normal,
),
),
),
],
),
],
),
],
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/screen | mirrored_repositories/Skysoft_Taxi/lib/screen/xanh_sm_clone_User/thongtin_coupon.dart | import 'dart:developer';
import 'package:flutter/material.dart';
class InfoCoupon extends StatelessWidget {
const InfoCoupon({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
leading: GestureDetector(
onTap: () {
Navigator.of(context).pop();
},
child: const Icon(
Icons.arrow_back_ios,
color: Colors.black,
),
),
actions: [
GestureDetector(
onTap: () {
log('shared the coupons');
},
child: const Padding(
padding: EdgeInsets.only(right: 16.0),
child: Icon(
Icons.share,
size: 22,
color: Colors.blue,
),
),
),
],
),
body: Padding(
padding: const EdgeInsets.only(bottom: 10),
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
width: 350,
height: 350,
decoration: const BoxDecoration(
shape: BoxShape.rectangle,
image: DecorationImage(
fit: BoxFit.fill,
image: NetworkImage(
'https://adanimate.com/wp-content/uploads/2021/10/TT023.jpg',
),
),
),
),
const SizedBox(height: 16),
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(height: 8),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
'Đồng giá 40K Xelo đưa bạn đi ăn trưa!',
style: TextStyle(
fontSize: 25,
color: Colors.green.shade500,
fontWeight: FontWeight.bold),
),
),
const SizedBox(height: 8),
const Padding(
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Row(
children: [
Icon(Icons.sell, color: Colors.blue, size: 16),
SizedBox(width: 8),
Expanded(
child: Text(
'Lên kèo đi chơi, lượn lờ phố phường, tận hưởng buổi trưa vui vẻ cùng người thân!',
style:
TextStyle(fontSize: 14, color: Colors.black),
// overflow: TextOverflow.ellipsis,
),
),
],
),
),
const SizedBox(height: 8),
const Padding(
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Row(
children: [
Icon(Icons.group, color: Colors.blueGrey, size: 16),
SizedBox(width: 8),
Text(
'Lượt sử dụng 1,8k',
style: TextStyle(fontSize: 14, color: Colors.black),
),
],
),
),
const SizedBox(height: 8),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Row(
children: [
Icon(Icons.star,
color: Colors.yellow.shade700, size: 16),
const SizedBox(width: 8),
const Text(
'Đánh giá 5 sao',
style: TextStyle(fontSize: 14, color: Colors.black),
),
],
),
),
],
),
SizedBox(
height: MediaQuery.of(context).size.height * 0.1,
),
ElevatedButton(
onPressed: () {
log('Sử dụng mã giảm giá');
},
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(
vertical: 20,
horizontal: MediaQuery.of(context).size.width * 0.22,
),
backgroundColor: Colors.green,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
),
child: const Text(
'Sử dụng mã giảm giá',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/screen | mirrored_repositories/Skysoft_Taxi/lib/screen/xanh_sm_clone_User/register_screen.dart | import 'package:flutter/material.dart';
import '../../util/connectivity_handler.dart';
import 'login_screen.dart';
class RegisterScreen extends StatefulWidget {
const RegisterScreen({super.key});
@override
State<RegisterScreen> createState() => _RegisterScreenState();
}
class _RegisterScreenState extends State<RegisterScreen> {
final _signUpEmailController = TextEditingController();
final _signUpPasswordController = TextEditingController();
final _confirmPasswordController = TextEditingController();
final _emailFocusNode = FocusNode();
final _passwordFocusNode = FocusNode();
final _confirmPasswordFocusNode = FocusNode();
bool isEmailFieldEmpty = true;
bool isPasswordFieldEmpty = true;
bool _obscurePassword = true;
bool _obscureConfirmPassword = true;
late ConnectivityHandler _connectivityHandler;
@override
void initState() {
super.initState();
_connectivityHandler = ConnectivityHandler();
_connectivityHandler.startListening(context);
}
@override
void dispose() {
_connectivityHandler.stopListening();
_emailFocusNode.dispose();
_passwordFocusNode.dispose();
_confirmPasswordFocusNode.dispose();
super.dispose();
}
bool _validatePassword() {
return _signUpPasswordController.text == _confirmPasswordController.text;
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color.fromARGB(255, 243, 243, 243),
resizeToAvoidBottomInset: true,
body: SafeArea(
child: Center(
child: SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(height: 50),
const LogoImage(imageUrl: '-assets/images/logo.png'),
const SizedBox(height: 10),
const Text(
'Skysoft Taxi',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
const SizedBox(height: 25),
// Email or Username
SizedBox(
height: 55,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 25),
child: TextFormField(
controller: _signUpEmailController,
focusNode: _emailFocusNode,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0),
borderSide: BorderSide(color: Colors.grey.shade400),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
borderSide: BorderSide(
color: Colors.grey.shade600, width: 2.0),
),
filled: true,
fillColor: Colors.grey.shade300,
hintText: "Email hoặc Tên Tài Khoản",
hintStyle: TextStyle(
color: Colors.grey.shade500, fontSize: 15),
suffixIcon: _signUpEmailController.text.isNotEmpty
? IconButton(
color: Colors.black,
icon: const Icon(Icons.cancel),
onPressed: () {
_signUpEmailController.clear();
setState(() {});
},
)
: null,
),
onChanged: (text) {
isEmailFieldEmpty = text.isEmpty;
setState(() {});
},
),
),
),
const SizedBox(height: 15),
//Passwords
SizedBox(
height: 55,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 25),
child: TextFormField(
controller: _signUpPasswordController,
focusNode: _passwordFocusNode,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0),
borderSide: BorderSide(color: Colors.grey.shade400),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
borderSide: BorderSide(
color: Colors.grey.shade600, width: 2.0),
),
filled: true,
fillColor: Colors.grey.shade300,
hintText: "Mật Khẩu",
hintStyle: TextStyle(
color: Colors.grey.shade500, fontSize: 15),
suffixIcon: isPasswordFieldEmpty
? null
: IconButton(
color: Colors.black,
icon: Icon(
_obscurePassword
? Icons.visibility
: Icons.visibility_off,
),
onPressed: () {
_obscurePassword = !_obscurePassword;
setState(() {});
},
),
),
obscureText: _obscurePassword,
onChanged: (text) {
isPasswordFieldEmpty = text.isEmpty;
setState(() {});
},
),
),
),
const SizedBox(height: 15),
// ConfirmPassword
SizedBox(
height: 55,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 25),
child: TextFormField(
controller: _confirmPasswordController,
focusNode: _confirmPasswordFocusNode,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0),
borderSide: BorderSide(color: Colors.grey.shade400),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
borderSide: BorderSide(
color: Colors.grey.shade600, width: 2.0),
),
filled: true,
fillColor: Colors.grey.shade300,
hintText: "Xác nhận mật khẩu",
hintStyle: TextStyle(
color: Colors.grey.shade500, fontSize: 15),
suffixIcon: isPasswordFieldEmpty
? null
: IconButton(
color: Colors.black,
icon: Icon(
_obscureConfirmPassword
? Icons.visibility
: Icons.visibility_off,
),
onPressed: () {
_obscureConfirmPassword =
!_obscureConfirmPassword;
setState(() {});
},
),
),
obscureText: _obscureConfirmPassword,
onChanged: (text) {
isPasswordFieldEmpty = text.isEmpty;
setState(() {});
},
),
),
),
const SizedBox(height: 15),
//sign in button
GestureDetector(
onTap: () => {
if (_validatePassword())
{
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text(
'Skysoft Taxi',
style: TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
),
),
content: const Text('Đăng ký thành công!'),
actions: [
ElevatedButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) =>
const LoginScreen(),
),
);
},
child: const Text('OK'),
),
],
);
},
),
}
else
{
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text(
'Lỗi !',
style: TextStyle(
color: Colors.red,
fontWeight: FontWeight.bold,
),
),
content: const Text('Mật khẩu không trùng.'),
actions: [
ElevatedButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('OK'),
),
],
);
},
),
},
},
child: Container(
padding: const EdgeInsets.all(15),
margin: const EdgeInsets.symmetric(horizontal: 25),
decoration: BoxDecoration(
color: Colors.deepOrange,
borderRadius: BorderRadius.circular(8),
),
child: const Center(
child: Text(
'Đăng ký',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 17,
),
),
),
),
),
const SizedBox(height: 10),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 25),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Đã có tài khoản ứng dụng ?',
style:
TextStyle(color: Colors.grey[600], fontSize: 12),
),
const SizedBox(
width: 5,
),
GestureDetector(
onTap: () => {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const LoginScreen(),
),
),
},
child: Text(
'Đăng Nhập',
style: TextStyle(
color: Colors.blue[900],
fontWeight: FontWeight.bold,
fontSize: 17),
),
),
],
),
),
],
),
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/screen | mirrored_repositories/Skysoft_Taxi/lib/screen/xanh_sm_clone_User/home_user_xanh_sm.dart | import 'dart:async';
import 'dart:io';
import 'dart:isolate';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:screen_state/screen_state.dart';
import '../../global/global.dart';
import '../../util/connectivity_handler.dart';
import 'goi_xe.dart';
import 'hoat_dong.dart';
import 'tai_khoan.dart';
import 'thong_bao.dart';
import 'user_chat_all.dart';
class HomeUserXanhSm extends StatefulWidget {
const HomeUserXanhSm({Key? key}) : super(key: key);
@override
_HomeUserXanhSmState createState() => _HomeUserXanhSmState();
}
class _HomeUserXanhSmState extends State<HomeUserXanhSm> {
int _currentIndex = 0;
bool isRequested = false;
bool isDriverInfo = false;
bool isReviews = false;
late ConnectivityHandler _connectivityHandler;
final List<Widget> _pages = [
const BookingCar(),
const ActivityDaily(),
const UserChatAll(),
const NotificationPage(),
const ProfilePage(),
];
ReceivePort? _receivePort;
Screen? _screen;
StreamSubscription<ScreenStateEvent>? screenSubscription;
HomeUserXanhSm() {
_screen = Screen();
// Kiểm tra _screen có phải là null hay không
if (_screen != null) {
// Kiểm tra _screenSubscription có phải là null hay không
screenSubscription = _screen!.screenStateStream?.listen((event) {
if (event == ScreenStateEvent.SCREEN_OFF) {
_startForegroundTask();
}
});
}
}
@override
void initState() {
super.initState();
_connectivityHandler = ConnectivityHandler();
_connectivityHandler.startListening(context);
webSocketService.connectToServer();
//ví dụ send
// webSocketService.sendMessage(jsonEncode({
// "message": "ping",
// "sender": "Duong ga",
// "receiver": "Tung ga",
// "type": "public",
// "received": "received"
// }));
WidgetsBinding.instance.addPostFrameCallback(
(_) async {
await _requestPermissionForAndroid();
_initForegroundTask();
_startForegroundTask();
// You can get the previous ReceivePort without restarting the service.
if (await FlutterForegroundTask.isRunningService) {
final newReceivePort = FlutterForegroundTask.receivePort;
_registerReceivePort(newReceivePort);
}
},
);
}
@override
void dispose() {
//channel.sink.close(status.goingAway);
_closeReceivePort();
super.dispose();
}
Future<void> _requestPermissionForAndroid() async {
if (!Platform.isAndroid) {
return;
}
if (!await FlutterForegroundTask.canDrawOverlays) {
// This function requires `android.permission.SYSTEM_ALERT_WINDOW` permission.
await FlutterForegroundTask.openSystemAlertWindowSettings();
}
// Android 12 or higher, there are restrictions on starting a foreground service.
if (!await FlutterForegroundTask.isIgnoringBatteryOptimizations) {
// This function requires `android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` permission.
await FlutterForegroundTask.requestIgnoreBatteryOptimization();
}
// Android 13 and higher, you need to allow notification permission to expose foreground service notification.
final NotificationPermission notificationPermissionStatus =
await FlutterForegroundTask.checkNotificationPermission();
if (notificationPermissionStatus != NotificationPermission.granted) {
await FlutterForegroundTask.requestNotificationPermission();
}
}
void _initForegroundTask() {
FlutterForegroundTask.init(
androidNotificationOptions: AndroidNotificationOptions(
id: 500,
channelId: 'foreground_service',
channelName: 'Foreground Service Notification',
channelDescription:
'This notification appears when the foreground service is running.',
channelImportance: NotificationChannelImportance.LOW,
priority: NotificationPriority.LOW,
iconData: const NotificationIconData(
resType: ResourceType.mipmap,
resPrefix: ResourcePrefix.ic,
name: 'launcher',
backgroundColor: Colors.orange,
),
buttons: [
const NotificationButton(
id: 'sendButton',
text: 'Send',
textColor: Colors.orange,
),
const NotificationButton(
id: 'testButton',
text: 'Test',
textColor: Colors.grey,
),
],
),
iosNotificationOptions: const IOSNotificationOptions(
showNotification: true,
playSound: false,
),
foregroundTaskOptions: const ForegroundTaskOptions(
interval: 5000,
isOnceEvent: false,
autoRunOnBoot: true,
allowWakeLock: true,
allowWifiLock: true,
),
);
}
Future<bool> _startForegroundTask() async {
// You can save data using the saveData function.
await FlutterForegroundTask.saveData(key: 'customData', value: 'hello');
// Register the receivePort before starting the service.
final ReceivePort? receivePort = FlutterForegroundTask.receivePort;
final bool isRegistered = _registerReceivePort(receivePort);
if (!isRegistered) {
print('Failed to register receivePort!');
return false;
}
if (await FlutterForegroundTask.isRunningService) {
return FlutterForegroundTask.restartService();
} else {
return FlutterForegroundTask.startService(
notificationTitle: 'Foreground Service is running',
notificationText: 'Tap to return to the app',
callback: startCallback,
);
}
}
Future<bool> _stopForegroundTask() {
return FlutterForegroundTask.stopService();
}
bool _registerReceivePort(ReceivePort? newReceivePort) {
if (newReceivePort == null) {
return false;
}
_closeReceivePort();
_receivePort = newReceivePort;
_receivePort?.listen((data) {
if (data is int) {
print('eventCount: $data');
} else if (data is String) {
if (data == 'onNotificationPressed') {
Navigator.of(context).pushNamed('/resume-route');
}
} else if (data is DateTime) {
print('timestamp: ${data.toString()}');
}
});
return _receivePort != null;
}
void _closeReceivePort() {
_receivePort?.close();
_receivePort = null;
}
void onConnectivityChanged(ConnectivityResult result) {
if (result != ConnectivityResult.none &&
_connectivityHandler.isShowingLoadingScreen()) {
Navigator.pop(context);
_connectivityHandler.setLoadingScreen(false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
Positioned.fill(child: _pages[_currentIndex]),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: Container(
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
spreadRadius: 0.1,
blurRadius: 20,
offset: const Offset(0, -10),
),
],
),
child: ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(25),
topRight: Radius.circular(25),
),
child: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: _currentIndex,
onTap: (index) {
_currentIndex = index;
setState(() {});
},
showSelectedLabels: true,
showUnselectedLabels: true,
iconSize: 25,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.local_taxi,
color: _currentIndex == 0
? Colors.blue.shade700
: Colors.grey),
label: 'Gọi xe',
),
BottomNavigationBarItem(
icon: Icon(Icons.schedule,
color: _currentIndex == 1
? Colors.blue.shade700
: Colors.grey),
label: 'Hoạt động',
),
BottomNavigationBarItem(
icon: Icon(Icons.group,
color: _currentIndex == 2
? Colors.blue.shade700
: Colors.grey),
label: 'Trò chuyện',
),
BottomNavigationBarItem(
icon: Icon(Icons.notifications_active,
color: _currentIndex == 3
? Colors.blue.shade700
: Colors.grey),
label: 'Thông báo',
),
BottomNavigationBarItem(
icon: Icon(Icons.account_circle,
color: _currentIndex == 4
? Colors.blue.shade700
: Colors.grey),
label: 'Tài Khoản',
),
],
selectedItemColor: Colors.blue.shade700,
unselectedItemColor: Colors.grey,
),
),
),
),
],
),
);
}
}
@pragma('vm:entry-point')
void startCallback() {
// The setTaskHandler function must be called to handle the task in the background.
FlutterForegroundTask.setTaskHandler(MyTaskHandler());
}
class MyTaskHandler extends TaskHandler {
SendPort? sendPort;
// Called when the task is started.
@override
void onStart(DateTime timestamp, SendPort? sendPort) async {
sendPort = sendPort;
// You can use the getData function to get the stored data.
final customData =
await FlutterForegroundTask.getData<String>(key: 'customData');
print('customData: $customData');
}
// Called every [interval] milliseconds in [ForegroundTaskOptions].
@override
void onRepeatEvent(DateTime timestamp, SendPort? sendPort) async {
// Không làm gì ở ForeGround
// FlutterForegroundTask.updateService(
// notificationTitle: 'MyTaskHandler',
// notificationText: 'eventCount: $_eventCount',
// );
// // Send data to the main isolate.
// sendPort?.send(_eventCount);
// _eventCount++;
}
// Called when the notification button on the Android platform is pressed.
@override
void onDestroy(DateTime timestamp, SendPort? sendPort) async {
print('onDestroy');
}
// Called when the notification button on the Android platform is pressed.
@override
void onNotificationButtonPressed(String id) {
print('onNotificationButtonPressed >> $id');
}
// Called when the notification itself on the Android platform is pressed.
//
// "android.permission.SYSTEM_ALERT_WINDOW" permission must be granted for
// this function to be called.
@override
void onNotificationPressed() {
// Note that the app will only route to "/resume-route" when it is exited so
// it will usually be necessary to send a message through the send port to
// signal it to restore state when the app is already started.
// FlutterForegroundTask.launchApp("/resume-route");
// _sendPort?.send('onNotificationPressed');
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/screen | mirrored_repositories/Skysoft_Taxi/lib/screen/xanh_sm_clone_User/tim_diem_den _nhanh.dart | import 'dart:developer';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_map_location_marker/flutter_map_location_marker.dart';
import 'package:geolocator/geolocator.dart';
import 'package:latlong2/latlong.dart';
import 'package:location/location.dart';
class QuickFindPlaces extends StatefulWidget {
const QuickFindPlaces({Key? key}) : super(key: key);
@override
State<QuickFindPlaces> createState() => _QuickFindPlacesState();
}
class _QuickFindPlacesState extends State<QuickFindPlaces>
with TickerProviderStateMixin {
final MapController _mapController = MapController();
late AnimationController _animationController;
late Animation<double> _movementAnimation;
final TextEditingController _pickupController = TextEditingController();
final TextEditingController _destinationController = TextEditingController();
LatLng markerLocation = const LatLng(21.03276589493197, 105.83989509524008);
@override
void initState() {
handleLocationButtonPress();
super.initState();
_animationController = AnimationController(
vsync: this,
duration: const Duration(seconds: 3),
);
_movementAnimation = Tween<double>(begin: 0, end: 1)
.chain(CurveTween(curve: Curves.easeInOut))
.animate(_animationController);
}
void handleLocationButtonPress() {
requestLocationPermission().then(
(bool hasPermission) {
if (hasPermission) {
getCurrentLocation().then(
(LatLng currentLocation) {
setState(() {
markerLocation = currentLocation;
});
_animateToCurrentLocation(currentLocation);
},
);
} else {
if (kDebugMode) {
print("Permission not granted");
}
}
},
);
}
void _animateToCurrentLocation(LatLng currentLocation) {
final startingCenter = _mapController.center;
_animationController.forward(from: 0);
_movementAnimation.addListener(
() {
final newCenter = LatLng(
lerpDouble(startingCenter.latitude, currentLocation.latitude,
_movementAnimation.value)!,
lerpDouble(startingCenter.longitude, currentLocation.longitude,
_movementAnimation.value)!,
);
_mapController.move(newCenter, _mapController.zoom * 2);
},
);
}
Future<bool> requestLocationPermission() async {
Location location = Location();
bool serviceEnabled = await location.serviceEnabled();
if (!serviceEnabled) {
serviceEnabled = await location.requestService();
if (!serviceEnabled) {
return false;
}
}
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
}
return permission == LocationPermission.whileInUse ||
permission == LocationPermission.always;
}
Future<LatLng> getCurrentLocation() async {
LocationData locationData = await Location().getLocation();
return LatLng(locationData.latitude!, locationData.longitude!);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
leading: IconButton(
icon: const Icon(
Icons.arrow_back_ios,
color: Colors.black,
),
onPressed: () {
Navigator.of(context).pop();
},
),
title: const Text(
'Chọn điểm đến',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 16,
),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
),
body: Stack(
children: [
FlutterMap(
options: MapOptions(
maxZoom: 18,
minZoom: 3,
),
mapController: _mapController,
nonRotatedChildren: const [
Center(
child: Icon(
Icons.location_on,
size: 30,
color: Colors.orangeAccent,
),
),
],
children: [
TileLayer(
urlTemplate: "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
),
CurrentLocationLayer(),
],
),
InputText(
pickupController: _pickupController,
destinationController: _destinationController,
onBack: () {
Navigator.of(context).pop();
},
),
Positioned(
top: MediaQuery.of(context).size.height * 0.65,
left: MediaQuery.of(context).size.width * 0.85,
right: 0,
child: FloatingActionButton(
backgroundColor: Colors.white,
onPressed: () {
handleLocationButtonPress();
},
mini: true,
child: const Icon(
color: Colors.black,
Icons.my_location,
size: 20,
),
),
),
Positioned(
top: MediaQuery.of(context).size.height * 0.75,
left: 0,
right: 0,
child: Center(
child: ElevatedButton(
onPressed: () {
log('Xác nhận điểm');
},
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(
vertical: MediaQuery.of(context).size.height * 0.02,
horizontal: MediaQuery.of(context).size.width * 0.3,
),
backgroundColor: Colors.cyan,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
),
child: const Text(
'Xác nhận điểm',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
),
),
],
),
);
}
}
class InputText extends StatefulWidget {
final TextEditingController pickupController;
final TextEditingController destinationController;
final void Function() onBack;
const InputText({
Key? key,
required this.pickupController,
required this.destinationController,
required this.onBack,
}) : super(key: key);
@override
State<InputText> createState() => _InputTextState();
}
class _InputTextState extends State<InputText> {
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
const SizedBox(height: 20),
Center(
child: Container(
width: MediaQuery.of(context).size.width * 0.85,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
color: Colors.grey.shade200,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 7,
offset: const Offset(0, 3),
),
],
),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
color: Colors.white,
),
child: Padding(
padding: const EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
buildTextField(
controller: widget.pickupController,
prefixIcon: const Icon(
Icons.boy,
color: Colors.blue,
),
hintText: 'Nhập điểm đón ...',
),
const Divider(
thickness: 1,
color: Colors.cyan,
indent: 20,
endIndent: 20,
),
buildTextField(
controller: widget.destinationController,
prefixIcon: const Icon(
Icons.location_on,
color: Colors.orangeAccent,
),
hintText: 'Nhập điểm đến ...',
),
],
),
),
),
),
),
],
);
}
Widget buildTextField({
required TextEditingController controller,
required Icon prefixIcon,
required String hintText,
}) {
return TextField(
controller: controller,
onChanged: (text) {
setState(() {});
},
decoration: InputDecoration(
prefixIcon: prefixIcon,
hintText: hintText,
border: InputBorder.none,
suffixIcon: controller.text.isNotEmpty
? GestureDetector(
onTap: () {
controller.clear();
setState(() {});
},
child: const Icon(Icons.clear),
)
: null,
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/screen | mirrored_repositories/Skysoft_Taxi/lib/screen/xanh_sm_clone_User/login_screen.dart | import 'package:flutter/material.dart';
import 'package:skysoft_taxi/global/global.dart';
import 'package:skysoft_taxi/models/user.model.dart';
import 'package:skysoft_taxi/screen/xanh_sm_clone_User/home_user_xanh_sm.dart';
import 'package:skysoft_taxi/util/connectivity_handler.dart';
import 'register_screen.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({super.key});
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
final _emailFocusNode = FocusNode();
final _passwordFocusNode = FocusNode();
late UserModel user;
bool isEmailFieldEmpty = true;
bool isPasswordFieldEmpty = true;
bool _obscurePassword = true;
late ConnectivityHandler _connectivityHandler;
@override
void initState() {
super.initState();
_connectivityHandler = ConnectivityHandler();
_connectivityHandler.startListening(context);
}
@override
void dispose() {
_connectivityHandler.stopListening();
_emailFocusNode.dispose();
_passwordFocusNode.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
resizeToAvoidBottomInset: true,
body: SafeArea(
child: Center(
child: SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(height: 50),
const LogoImage(imageUrl: '-assets/images/logo.png'),
const SizedBox(height: 10),
const Text(
'Skysoft Taxi',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
const SizedBox(height: 25),
SizedBox(
height: 55,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 25),
child: TextFormField(
controller: _emailController,
focusNode: _emailFocusNode,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0),
borderSide: BorderSide(color: Colors.grey.shade400),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
borderSide: BorderSide(
color: Colors.grey.shade600, width: 2.0),
),
filled: true,
fillColor: Colors.grey.shade300,
hintText: "Email hoặc Tên Tài Khoản",
hintStyle: TextStyle(
color: Colors.grey.shade500, fontSize: 15),
suffixIcon: _emailController.text.isNotEmpty
? IconButton(
color: Colors.black,
icon: const Icon(Icons.cancel),
onPressed: () {
_emailController.clear();
setState(() {});
},
)
: null,
),
onChanged: (text) {
isEmailFieldEmpty = text.isEmpty;
setState(() {});
},
),
),
),
const SizedBox(height: 15),
SizedBox(
height: 55,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 25),
child: TextFormField(
controller: _passwordController,
focusNode: _passwordFocusNode,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8.0),
borderSide: BorderSide(color: Colors.grey.shade400),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
borderSide: BorderSide(
color: Colors.grey.shade600, width: 2.0),
),
filled: true,
fillColor: Colors.grey.shade300,
hintText: "Mật Khẩu",
hintStyle: TextStyle(
color: Colors.grey.shade500, fontSize: 15),
suffixIcon: isPasswordFieldEmpty
? null
: IconButton(
color: Colors.black,
icon: Icon(
_obscurePassword
? Icons.visibility
: Icons.visibility_off,
),
onPressed: () {
_obscurePassword = !_obscurePassword;
setState(() {});
},
),
),
obscureText: _obscurePassword,
onChanged: (text) {
isPasswordFieldEmpty = text.isEmpty;
setState(() {});
},
),
),
),
const SizedBox(height: 15),
GestureDetector(
onTap: () async {
String enteredUsername = _emailController.text;
List<String> temp = enteredUsername.split(".");
String role = temp.first;
String userName = temp.last;
if (role == "user") {
userModel.name = userName;
Navigator.of(context).push(MaterialPageRoute(
builder: (context) {
return const HomeUserXanhSm();
},
));
userModel.changeStatusWithMessage("ENDTRIP");
} else if (role == "driver") {
driverModel.name = userName;
// Navigator.of(context).push(
// MaterialPageRoute(
// builder: (context) {
// return const HomeDriver();
// },
// ),
// );
driverModel.changeStatusWithMessage("ENDTRIP");
} else {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text(
'Lỗi !',
style: TextStyle(
color: Colors.red,
fontWeight: FontWeight.bold,
),
),
content: const Text('Lỗi đăng nhập tài khoản.'),
actions: [
ElevatedButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('OK'),
),
],
);
},
);
}
},
child: Container(
padding: const EdgeInsets.all(15),
margin: const EdgeInsets.symmetric(horizontal: 25),
decoration: BoxDecoration(
color: Colors.deepOrange,
borderRadius: BorderRadius.circular(8),
),
child: const Center(
child: Text(
'Đăng Nhập',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 17,
),
),
),
),
),
const SizedBox(height: 20),
Padding(
padding: const EdgeInsets.all(5.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Người dùng mới sử dụng?',
style:
TextStyle(color: Colors.grey[600], fontSize: 12),
),
const SizedBox(
width: 5,
),
GestureDetector(
onTap: () => {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const RegisterScreen(),
),
)
},
child: Text(
'Đăng ký',
style: TextStyle(
color: Colors.blue[900],
fontWeight: FontWeight.bold,
fontSize: 17),
),
),
],
),
),
],
),
),
),
),
),
);
}
}
class LogoImage extends StatelessWidget {
final String imageUrl;
const LogoImage({Key? key, required this.imageUrl}) : super(key: key);
@override
Widget build(BuildContext context) {
return Image.asset(
'assets/images/logo.png', // Update with the correct path to your image
height: 100,
width: 100,
fit: BoxFit.cover,
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/screen | mirrored_repositories/Skysoft_Taxi/lib/screen/xanh_sm_clone_User/thong_bao.dart | import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:skysoft_taxi/screen/xanh_sm_clone_User/thongtin_coupon.dart';
class NotificationPage extends StatefulWidget {
const NotificationPage({Key? key}) : super(key: key);
@override
State<NotificationPage> createState() => _NotificationPageState();
}
class _NotificationPageState extends State<NotificationPage> {
bool showCheckbox = false;
List<bool> checkboxStates = List.filled(10, false);
List<Coupon> couponList = [
Coupon(
id: 0,
dateTime: DateTime.now(),
showCheckbox: false,
onCheckboxChanged: (bool isChecked) {},
),
Coupon(
id: 2,
dateTime: DateTime.now(),
showCheckbox: false,
onCheckboxChanged: (bool isChecked) {},
),
Coupon(
id: 3,
dateTime: DateTime.now(),
showCheckbox: false,
onCheckboxChanged: (bool isChecked) {},
),
Coupon(
id: 4,
dateTime: DateTime.now(),
showCheckbox: false,
onCheckboxChanged: (bool isChecked) {},
),
Coupon(
id: 5,
dateTime: DateTime.now(),
showCheckbox: false,
onCheckboxChanged: (bool isChecked) {},
),
Coupon(
id: 6,
dateTime: DateTime.now(),
showCheckbox: false,
onCheckboxChanged: (bool isChecked) {},
),
Coupon(
id: 7,
dateTime: DateTime.now(),
showCheckbox: false,
onCheckboxChanged: (bool isChecked) {},
),
];
void handleRemoveButtonPressed() {
// Get the indices of checked items
List<int> checkedIndices = [];
for (int i = 0; i < checkboxStates.length; i++) {
if (checkboxStates[i]) {
checkedIndices.add(i);
}
}
// Remove the checked items from the couponList
for (int index in checkedIndices) {
// Ensure the index is within the bounds of the list
if (index >= 0 && index < couponList.length) {
couponList.removeAt(index);
}
}
// Clear checkboxStates after removal
checkboxStates = List.filled(couponList.length, false);
showCheckbox = false;
setState(() {});
}
//show or hide the checkboxes in the list
void toggleCheckboxVisibility() {
showCheckbox = !showCheckbox;
setState(() {});
}
//the state of a checkbox changes
void handleCheckboxChanged(int index, bool isChecked) {
checkboxStates[index] = isChecked;
setState(() {});
}
//checks whether at least one checkbox is checked
bool isAnyCheckboxChecked() {
return checkboxStates.any((element) => element);
}
@override
Widget build(BuildContext context) {
double screenHeight = MediaQuery.of(context).size.height;
double buttonTopPosition = screenHeight * 0.65;
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
centerTitle: true,
title: const Text(
'Thông báo',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
elevation: 0,
actions: [
IconButton(
color: Colors.red,
icon: const Icon(Icons.delete_outlined),
onPressed: () {
toggleCheckboxVisibility();
},
),
],
),
body: Stack(
children: [
Container(
color: const Color.fromARGB(242, 244, 243, 255),
child: Padding(
padding: const EdgeInsets.only(bottom: 60),
child: ListView.builder(
physics: const BouncingScrollPhysics(),
itemCount: couponList.length,
itemBuilder: (context, index) => Coupon(
id: index,
dateTime: couponList[index].dateTime,
showCheckbox: showCheckbox,
onCheckboxChanged: (isChecked) {
handleCheckboxChanged(index, isChecked);
},
),
),
),
),
Positioned(
top: buttonTopPosition,
bottom: 0,
left: 0,
right: 0,
child: Visibility(
visible: showCheckbox && isAnyCheckboxChecked(),
child: Center(
child: ElevatedButton(
onPressed: handleRemoveButtonPressed,
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(
vertical: 15,
horizontal: MediaQuery.of(context).size.width * 0.2,
),
backgroundColor: Colors.red,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
),
child: const Text(
'Xóa thông báo',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
),
),
),
],
),
);
}
}
// ITEMS IN CONTAINER
class Coupon extends StatelessWidget {
final DateTime dateTime;
final bool showCheckbox;
final Function(bool) onCheckboxChanged;
final int id;
const Coupon({
Key? key,
required this.dateTime,
required this.showCheckbox,
required this.onCheckboxChanged,
required this.id,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final formattedDateTime = DateFormat('MM/dd/yyyy HH:mm').format(dateTime);
return GestureDetector(
onTap: () => {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => const InfoCoupon()),
),
},
child: Container(
margin: const EdgeInsets.all(8),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Visibility(
visible: showCheckbox,
child: CheckboxExample(
isChecked: false,
onCheckboxChanged: onCheckboxChanged,
),
),
SizedBox(
width: 40,
height: 40,
child: FittedBox(
fit: BoxFit.contain,
child: Image.network(
'https://image.winudf.com/v2/image1/Y29tLnNreXNvZnQuZ3BzX2ljb25fMTU1OTE4NzY5NF8wMjQ/icon.png?w=184&fakeurl=1',
width: 120,
height: 120,
),
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
formattedDateTime,
style: const TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: Colors.blueGrey,
),
),
const SizedBox(height: 8),
Text(
'Đồng giá 40K Xelo đưa bạn đi ăn trưa!',
style: TextStyle(
fontSize: 16,
color: Colors.green.shade500,
fontWeight: FontWeight.bold),
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 8),
const Row(
children: [
Icon(Icons.sell, color: Colors.blue, size: 16),
SizedBox(width: 8),
Expanded(
child: Text(
'Lên kèo đi chơi, lượn lờ phố phường, tận hưởng buổi trưa vui vẻ cùng người thân!',
style: TextStyle(fontSize: 14, color: Colors.black),
overflow: TextOverflow.ellipsis,
),
),
],
),
const SizedBox(height: 8),
const Row(
children: [
Icon(Icons.group, color: Colors.blueGrey, size: 16),
SizedBox(width: 8),
Text(
'Lượt sử dụng 1,8k',
style: TextStyle(fontSize: 14, color: Colors.black),
),
],
),
const SizedBox(height: 8),
Row(
children: [
Icon(Icons.star, color: Colors.yellow.shade700, size: 16),
const SizedBox(width: 8),
const Text(
'Đánh giá 5 sao',
style: TextStyle(fontSize: 14, color: Colors.black),
),
],
),
],
),
),
],
),
),
);
}
}
// CHECK BOX
class CheckboxExample extends StatefulWidget {
final bool isChecked;
final Function(bool) onCheckboxChanged;
const CheckboxExample({
Key? key,
required this.isChecked,
required this.onCheckboxChanged,
}) : super(key: key);
@override
State<CheckboxExample> createState() => _CheckboxExampleState();
}
class _CheckboxExampleState extends State<CheckboxExample> {
late bool isChecked;
@override
void initState() {
super.initState();
isChecked = false; // Set the initial value here if needed
}
@override
Widget build(BuildContext context) {
Color getColor(Set<MaterialState> states) {
const Set<MaterialState> interactiveStates = <MaterialState>{
MaterialState.pressed,
MaterialState.hovered,
MaterialState.focused,
};
if (states.any(interactiveStates.contains)) {
return Colors.blue;
}
return Colors.white54;
}
return Checkbox(
checkColor: Colors.blue,
fillColor: MaterialStateProperty.resolveWith(getColor),
value: isChecked,
onChanged: (bool? value) {
isChecked = value!;
widget.onCheckboxChanged(isChecked);
setState(() {});
},
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/screen | mirrored_repositories/Skysoft_Taxi/lib/screen/xanh_sm_clone_User/luu_diem_don.dart | import 'dart:developer';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_map_location_marker/flutter_map_location_marker.dart';
import 'package:geolocator/geolocator.dart';
import 'package:latlong2/latlong.dart';
import 'package:location/location.dart';
class SaveMakerPlaces extends StatefulWidget {
const SaveMakerPlaces({Key? key}) : super(key: key);
@override
State<SaveMakerPlaces> createState() => _SaveMakerPlacesState();
}
class _SaveMakerPlacesState extends State<SaveMakerPlaces>
with TickerProviderStateMixin {
final MapController _mapController = MapController();
late AnimationController _animationController;
late Animation<double> _movementAnimation;
final TextEditingController _pickupController = TextEditingController();
final TextEditingController _destinationController = TextEditingController();
LatLng markerLocation = const LatLng(21.03276589493197, 105.83989509524008);
@override
void initState() {
// handleLocationButtonPress();
super.initState();
_animationController = AnimationController(
vsync: this,
duration: const Duration(seconds: 3),
);
_movementAnimation = Tween<double>(begin: 0, end: 1)
.chain(CurveTween(curve: Curves.easeInOut))
.animate(_animationController);
}
void handleLocationButtonPress() {
requestLocationPermission().then(
(bool hasPermission) {
if (hasPermission) {
getCurrentLocation().then(
(LatLng currentLocation) {
markerLocation = currentLocation;
setState(() {});
_animateToCurrentLocation(currentLocation);
},
);
} else {
if (kDebugMode) {
print("Permission not granted");
}
}
},
);
}
void _animateToCurrentLocation(LatLng currentLocation) {
final startingCenter = _mapController.center;
_animationController.forward(from: 0);
_movementAnimation.addListener(
() {
final newCenter = LatLng(
lerpDouble(startingCenter.latitude, currentLocation.latitude,
_movementAnimation.value)!,
lerpDouble(startingCenter.longitude, currentLocation.longitude,
_movementAnimation.value)!,
);
_mapController.move(newCenter, _mapController.zoom * 2);
},
);
}
Future<bool> requestLocationPermission() async {
Location location = Location();
bool serviceEnabled = await location.serviceEnabled();
if (!serviceEnabled) {
serviceEnabled = await location.requestService();
if (!serviceEnabled) {
return false;
}
}
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
}
return permission == LocationPermission.whileInUse ||
permission == LocationPermission.always;
}
Future<LatLng> getCurrentLocation() async {
LocationData locationData = await Location().getLocation();
return LatLng(locationData.latitude!, locationData.longitude!);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
leading: IconButton(
icon: const Icon(
Icons.arrow_back_ios,
color: Colors.black,
),
onPressed: () {
Navigator.of(context).pop();
},
),
title: const Text(
'Thêm địa điểm để lưu',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 16,
),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
),
body: Stack(
children: [
FlutterMap(
options: MapOptions(
maxZoom: 18,
minZoom: 3,
),
mapController: _mapController,
nonRotatedChildren: const [
Center(
child: Icon(
Icons.location_on,
size: 30,
color: Colors.blue,
),
),
],
children: [
TileLayer(
urlTemplate: "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
),
CurrentLocationLayer(),
],
),
InputText(
pickupController: _pickupController,
destinationController: _destinationController,
onBack: () {
Navigator.of(context).pop();
},
),
Positioned(
top: MediaQuery.of(context).size.height * 0.65,
left: MediaQuery.of(context).size.width * 0.85,
right: 0,
child: FloatingActionButton(
backgroundColor: Colors.white,
onPressed: () {
handleLocationButtonPress();
},
mini: true,
child: const Icon(
color: Colors.black,
Icons.my_location,
size: 20,
),
),
),
Positioned(
top: MediaQuery.of(context).size.height * 0.75,
left: 0,
right: 0,
child: Center(
child: ElevatedButton(
onPressed: () {
log('Xác nhận điểm');
},
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(
vertical: MediaQuery.of(context).size.height * 0.02,
horizontal: MediaQuery.of(context).size.width * 0.3,
),
backgroundColor: Colors.cyan,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
),
child: const Text(
'Xác nhận điểm',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
),
),
],
),
);
}
}
class InputText extends StatefulWidget {
final TextEditingController pickupController;
final TextEditingController destinationController;
final void Function() onBack;
const InputText({
Key? key,
required this.pickupController,
required this.destinationController,
required this.onBack,
}) : super(key: key);
@override
State<InputText> createState() => _InputTextState();
}
class _InputTextState extends State<InputText> {
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
SizedBox(height: MediaQuery.of(context).size.height * 0.03),
Center(
child: Container(
width: MediaQuery.of(context).size.width * 0.85,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
color: Colors.grey.shade200,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 7,
offset: const Offset(0, 3),
),
],
),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
color: Colors.white,
),
child: Padding(
padding: const EdgeInsets.all(5),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
buildTextField(
controller: widget.pickupController,
prefixIcon: const Icon(
Icons.location_on,
color: Colors.blue,
),
hintText: 'Điểm đánh dấu ...',
),
],
),
),
),
),
),
],
);
}
Widget buildTextField({
required TextEditingController controller,
required Icon prefixIcon,
required String hintText,
}) {
return TextField(
controller: controller,
onChanged: (text) {
setState(() {});
},
decoration: InputDecoration(
prefixIcon: prefixIcon,
hintText: hintText,
border: InputBorder.none,
suffixIcon: controller.text.isNotEmpty
? GestureDetector(
onTap: () {
controller.clear();
setState(() {});
},
child: const Icon(Icons.clear),
)
: null,
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib/screen | mirrored_repositories/Skysoft_Taxi/lib/screen/xanh_sm_clone_User/tai_khoan.dart | import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:skysoft_taxi/global/global.dart';
import 'package:skysoft_taxi/screen/xanh_sm_clone_User/login_screen.dart';
import 'package:skysoft_taxi/widgets/menu_widget_profile.dart';
import '../../models/user.model.dart';
class ProfilePage extends StatefulWidget {
const ProfilePage({Key? key}) : super(key: key);
@override
State<ProfilePage> createState() => _ProfilePageState();
}
Future<bool> _stopForegroundTask() {
return FlutterForegroundTask.stopService();
}
class _ProfilePageState extends State<ProfilePage> {
@override
Widget build(BuildContext context) {
double screenHeight = MediaQuery.of(context).size.height;
return Scaffold(
body: Padding(
padding: const EdgeInsets.only(bottom: 50),
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Container(
color: const Color.fromARGB(242, 244, 243, 255),
child: Stack(
children: [
Column(
children: [
Container(
height: screenHeight / 4,
decoration: const BoxDecoration(
image: DecorationImage(
image: NetworkImage(
'https://www.pyramidions.com/blog/wp-content/uploads/2018/10/Big-Data.jpg',
),
fit: BoxFit.cover,
),
),
),
const SizedBox(height: 55),
Padding(
padding: EdgeInsets.symmetric(
horizontal: 0.05 * MediaQuery.of(context).size.width,
),
child: GestureDetector(
onTap: () {
log('Bạn đã đóng góp:');
},
child: Container(
height: 100,
width: 5 * MediaQuery.of(context).size.width,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
spreadRadius: 0.1,
blurRadius: 20,
offset: const Offset(0, 10),
),
],
image: const DecorationImage(
image: NetworkImage(
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRWDZbxpoLXAkM6Ycqn_zElPOIIke5_Jw7Eug&usqp=CAU',
),
fit: BoxFit.cover,
),
color: Colors.white,
borderRadius: BorderRadius.circular(15.0),
),
child: const Padding(
padding: EdgeInsets.fromLTRB(15, 0, 0, 0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Bạn đã đóng góp:',
style: TextStyle(
fontSize: 16,
color: Colors.black,
fontWeight: FontWeight.normal,
),
),
Text(
'O VNĐ',
style: TextStyle(
fontSize: 16,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
Text(
'Cho quỹ vì tương lai Xelo Taxi',
style: TextStyle(
fontSize: 16,
color: Colors.black,
fontWeight: FontWeight.normal,
),
),
],
),
),
),
),
),
const SizedBox(height: 10),
Padding(
padding: EdgeInsets.symmetric(
horizontal: 0.05 * MediaQuery.of(context).size.width,
),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(15.0),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
spreadRadius: 0.1,
blurRadius: 20,
offset: const Offset(0, 10),
),
],
),
child: Column(
children: [
MenuWidget(
iconLeft: Icons.military_tech,
text: 'Hạng thành viên',
iconRight: Icons.chevron_right,
onTap: () {
log('Hạng thành viên');
},
),
MenuWidget(
iconLeft: Icons.person_add,
text: 'Giới thiệu bạn bè',
iconRight: Icons.chevron_right,
onTap: () {
log('Giới thiệu bạn bè');
},
),
MenuWidget(
iconLeft: Icons.credit_card,
text: 'Thanh toán',
iconRight: Icons.chevron_right,
onTap: () {
log('Thanh toán');
},
),
MenuWidget(
iconLeft: Icons.receipt_long,
text: 'Thông tin đơn',
iconRight: Icons.chevron_right,
onTap: () {
log('Thông tin đơn');
},
),
MenuWidget(
iconLeft: Icons.pin_drop,
text: 'Địa chỉ đã lưu',
iconRight: Icons.chevron_right,
onTap: () {
log('Địa chỉ đã lưu');
},
isLast: true,
),
],
),
),
),
const SizedBox(height: 10),
Padding(
padding: EdgeInsets.symmetric(
horizontal: 0.05 * MediaQuery.of(context).size.width,
),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(15.0),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
spreadRadius: 0.1,
blurRadius: 20,
offset: const Offset(0, 10),
),
],
),
child: Column(
children: [
MenuWidget(
iconLeft: Icons.help,
text: 'Trung tâm hỗ trợ',
iconRight: Icons.chevron_right,
onTap: () {
log('Trung tâm hỗ trợ');
},
),
MenuWidget(
iconLeft: Icons.policy,
text: 'Điều khoản và chính sách',
iconRight: Icons.chevron_right,
onTap: () {
log('Điều khoản và chính sách');
},
),
MenuWidget(
iconLeft: Icons.language,
text: 'Ngôn Ngữ (Language)',
iconRight: Icons.chevron_right,
onTap: () {
log('Ngôn Ngữ (Language)');
},
),
MenuWidget(
iconLeft: Icons.logout,
text: 'Đăng xuất',
iconRight: Icons.chevron_right,
onTap: () {
log('Đăng xuất');
_stopForegroundTask();
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const LoginScreen(),
),
);
},
isLast: true,
),
],
),
),
),
const SizedBox(height: 10),
Padding(
padding: EdgeInsets.symmetric(
horizontal: 0.05 * MediaQuery.of(context).size.width,
),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(15.0),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
spreadRadius: 0.1,
blurRadius: 20,
offset: const Offset(0, 10),
),
],
),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
MenuWidget(
iconLeft: Icons.mail,
text: 'Email CSKH',
iconRight: Icons.chevron_right,
onTap: () {
log('Email CSKH');
},
isLast: true,
),
MenuWidget(
iconLeft: Icons.support_agent,
text: '1900 2097',
iconRight: Icons.chevron_right,
onTap: () {
log('1900 2097');
},
isLast: true,
),
],
),
],
),
),
),
const SizedBox(height: 10),
const Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Skysoft Taxi - System 20042',
style: TextStyle(
fontSize: 16,
color: Colors.grey,
fontWeight: FontWeight.bold,
),
overflow: TextOverflow.ellipsis,
),
Text(
'V2.0.42/13 - build: 92',
style: TextStyle(
fontSize: 16,
color: Colors.grey,
fontWeight: FontWeight.bold,
),
overflow: TextOverflow.ellipsis,
),
],
),
const SizedBox(height: 20),
],
),
Padding(
padding: EdgeInsets.symmetric(
horizontal: 0.05 * MediaQuery.of(context).size.width,
vertical: 0.2 * screenHeight,
),
child: GestureDetector(
onTap: () {
log("USER INFO");
},
child: Container(
height: 83,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(15.0),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.1),
spreadRadius: 0.1,
blurRadius: 20,
offset: const Offset(0, 10),
),
],
),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10.0,
vertical: 0.2,
),
child: Row(
children: [
const CircleAvatar(
radius: 35,
backgroundImage: NetworkImage(
'https://yt3.googleusercontent.com/-CFTJHU7fEWb7BYEb6Jh9gm1EpetvVGQqtof0Rbh-VQRIznYYKJxCaqv_9HeBcmJmIsp2vOO9JU=s900-c-k-c0x00ffffff-no-rj',
),
),
const SizedBox(width: 20),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
userModel.name,
style: const TextStyle(
fontSize: 16,
color: Colors.black,
fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic,
),
overflow: TextOverflow.ellipsis,
maxLines: 2,
),
const SizedBox(height: 5),
const Text(
'037.455.1092',
style: TextStyle(
fontSize: 12,
color: Colors.blue,
fontWeight: FontWeight.bold,
),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
],
),
),
const Spacer(),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
onPressed: () {
log("Điều hướng trang Profile");
},
icon: const Icon(
Icons.chevron_right,
size: 25,
color: Colors.black,
),
),
],
),
],
),
),
),
),
),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/audiochat_widget/input_voice.dart | import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'dart:typed_data';
import 'package:bluetooth_connector/bluetooth_connector.dart';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'package:http/http.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:audio_session/audio_session.dart' as a_s;
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:logger/logger.dart' show Level;
import 'package:flutter_sound_platform_interface/flutter_sound_recorder_platform_interface.dart';
import 'package:skysoft_taxi/global/global.dart';
import 'package:skysoft_taxi/url/contants.dart';
// ignore: must_be_immutable
class InputVoice extends StatefulWidget {
Function(bool, String) onDone;
InputVoice({super.key, required this.onDone});
@override
State<InputVoice> createState() => _InputVoiceState();
}
typedef Fn = void Function();
class _InputVoiceState extends State<InputVoice> {
// final List<ChatMessage> messages = [];
final FlutterSoundRecorder _mRecorder =
FlutterSoundRecorder(logLevel: Level.nothing);
final Codec _codec = Codec.aacMP4;
String _mPath = 'temp.mp4';
bool _mRecorderIsInited = false;
double mSubscriptionDuration = 0;
StreamSubscription? _recorderSubscription;
int pos = 0;
Timer? timer;
double dbLevel = 0;
String _tempDirectory = "";
//DND
bool isRecord = false;
bool isDelete = false;
bool isHold = false;
bool isActiveHold = false;
bool isConnectBlueToothLoudspeaker = false;
Icon holdButton = const Icon(Icons.lock, color: Colors.green);
Icon delelteButton = const Icon(Icons.delete, color: Colors.red);
Icon recordButton = const Icon(Icons.mic, color: Colors.blue, size: 30);
Icon sendButton = const Icon(Icons.send, color: Colors.blue);
Icon tempButton = const Icon(Icons.mic, color: Colors.blue, size: 30);
Future<void> openTheRecorder() async {
await _mRecorder.openRecorder();
final session = await a_s.AudioSession.instance;
await session.configure(a_s.AudioSessionConfiguration(
avAudioSessionCategory: a_s.AVAudioSessionCategory.playAndRecord,
avAudioSessionCategoryOptions:
a_s.AVAudioSessionCategoryOptions.allowBluetooth |
a_s.AVAudioSessionCategoryOptions.defaultToSpeaker,
avAudioSessionMode: a_s.AVAudioSessionMode.spokenAudio,
avAudioSessionRouteSharingPolicy:
a_s.AVAudioSessionRouteSharingPolicy.defaultPolicy,
avAudioSessionSetActiveOptions: a_s.AVAudioSessionSetActiveOptions.none,
androidAudioAttributes: const a_s.AndroidAudioAttributes(
contentType: a_s.AndroidAudioContentType.speech,
flags: a_s.AndroidAudioFlags.none,
usage: a_s.AndroidAudioUsage.voiceCommunication,
),
androidAudioFocusGainType: a_s.AndroidAudioFocusGainType.gain,
androidWillPauseWhenDucked: true,
));
_mRecorderIsInited = true;
session.devicesChangedEventStream.listen((event) {
log('Devices added: ${event.devicesAdded}');
log('Devices removed: ${event.devicesRemoved}');
});
Set<a_s.AudioDevice> listDeviceLoudspeaker = await session.getDevices();
for (var element in listDeviceLoudspeaker) {
if (element.type.toString().contains("bluetooth")) {
isConnectBlueToothLoudspeaker = true;
break;
}
}
if (isConnectBlueToothLoudspeaker) {
BluetoothConnector flutterbluetoothconnector = BluetoothConnector();
List<BtDevice> listDevice = await flutterbluetoothconnector.getDevices();
bool started = await flutterbluetoothconnector.startServer();
if (started) {
// for (var element in listDevice) {
// if (element.name == "B02PTT-080F" || element.name == "B02PTT-03DD") {
// address = element.address!;
// break;
// }
// bool connected = await flutterbluetoothconnector.startClient(
// listDevice.indexOf(element), false);
// log("${element.address} - ${element.name}: $connected");
// }
BluetoothDevice? selectedDevice =
await _showBluetoothDeviceSelectionDialog(listDevice);
if (selectedDevice != null) {
log("address: ${selectedDevice.address}");
bluetoothConnect(selectedDevice.address);
} else {
log("Mic được lấy từ điện thoại");
}
}
}
}
Future<BluetoothDevice?> _showBluetoothDeviceSelectionDialog(
List<BtDevice> listDevice) async {
BluetoothDevice? selectedDevice = await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Chọn Thiết Bị Bluetooth"),
content: Container(
width: double.maxFinite,
child: ListView(
shrinkWrap: true,
children:
listDevice.map((device) => _buildDeviceItem(device)).toList(),
),
),
);
},
);
return selectedDevice;
}
Widget _buildDeviceItem(BtDevice device) {
return GestureDetector(
onTap: () {
Navigator.pop(
context,
BluetoothDevice(
name: device.name, address: device.address.toString()));
},
child: Container(
padding: EdgeInsets.symmetric(vertical: 12.0),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: Colors.grey)),
),
child: Text(
device.name.toString(),
style: TextStyle(fontSize: 16.0),
),
),
);
}
void turnOnOffSco(bool start) {
if (start) {
a_s.AndroidAudioManager().startBluetoothSco();
} else {
a_s.AndroidAudioManager().stopBluetoothSco();
}
a_s.AndroidAudioManager().setBluetoothScoOn(start);
}
Future<void> bluetoothConnect(String address) async {
//08:21:05:05:08:0F
// Some simplest connection :F
try {
if (connection != null) {
connection!.finish();
connection = null;
}
if (connection == null) {
connection = await BluetoothConnection.toAddress(address);
print('Connected to the device');
connection!.input!.listen((Uint8List data) {
String command = ascii.decode(data);
print('Data incoming: ${command} - ${data.toList()}');
connection!.output.add(data); // Sending data
if (command == "+PTT=P") {
turnOnOffSco(true);
isRecord = true;
startRecord();
setState(() {});
}
if (command == "+PTT=R") {
turnOnOffSco(false);
uploadRecord(_mRecorder);
isRecord = false;
setState(() {});
}
if (ascii.decode(data).contains('!')) {
connection!.finish(); // Closing connection
print('Disconnecting by local host');
}
}).onDone(() {
print('Disconnected by remote request');
});
}
} catch (exception) {
print('Cannot connect, exception occured');
}
}
Future<void> init() async {
PermissionStatus status = await Permission.microphone.request();
if (status != PermissionStatus.granted) {
log("Chưa cấp quyền microphone");
}
PermissionStatus storageStatus = await Permission.storage.request();
if (storageStatus != PermissionStatus.granted) {
log("Chưa cấp quyền thư mục");
}
PermissionStatus bluetoothStatus = await Permission.bluetooth.request();
if (bluetoothStatus != PermissionStatus.granted) {
log("Chưa cấp quyền Bluetooth");
}
await openTheRecorder();
_recorderSubscription = _mRecorder.onProgress!.listen((e) {
setState(() {
pos = e.duration.inMilliseconds;
if (e.decibels != null) {
dbLevel = e.decibels as double;
}
});
});
}
void record(FlutterSoundRecorder? recorder) async {
if (recorder!.isRecording) return;
recorder.startRecorder(
codec: _codec,
toFile: _tempDirectory + "/" + _mPath,
// bitRate: 8000,
// numChannels: 1,
// sampleRate: 8000,
audioSource: AudioSource.microphone);
// timer?.cancel();
// pos = 0;
timer = Timer.periodic(Duration(seconds: 1), (Timer t) {
pos += 1000;
setState(() {});
});
}
Future<void> uploadRecord(FlutterSoundRecorder recorder) async {
if (pos < 1000) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Cảnh báo'),
content: Text('Thời lượng âm thanh quá ngắn.'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('OK'),
),
],
);
},
);
cancelRecording(recorder);
return;
} else {
String? pathFile = await recorder.stopRecorder();
if (pathFile == null || pathFile == "") {
log("uploadRecord fail");
return;
}
File file = File(pathFile);
if (!file.existsSync()) {
log("File not exists: $pathFile");
return;
}
// Upload file
String? chatId = await uploadAudioFile(file);
// Delete file
await file.delete();
log("Recording file deleted");
if (chatId == null) return;
widget.onDone(true, chatId);
}
}
Future<void> cancelRecording(FlutterSoundRecorder recorder) async {
String? pathFile = await recorder.stopRecorder();
if (pathFile == null) {
log("CancelRecording fail");
return;
}
log("Recording canceled");
// xóa file khi cần
// String audioFilePath = '$_tempDirectory/$_mPath';
// File audioFile = File(audioFilePath);
// if (audioFile.existsSync()) {
// await audioFile.delete();
// log("Recording file deleted");
// }
}
// ignore: body_might_complete_normally_nullable
Future<String?> uploadAudioFile(File audioFile) async {
try {
List<int> fileBytes = await audioFile.readAsBytes();
String base64Data = base64Encode(fileBytes);
Map<String, String> body = {
"name": userModel.name,
"data": base64Data,
};
Response response = await post(
Uri.parse(URL_CHAT_UPLOAD),
body: body,
);
if (response.statusCode == 200) {
print('Upload thành công');
final Map<String, dynamic> responseData = jsonDecode(response.body);
return responseData["chatId"].toString();
} else {
print('Upload thất bại. Mã lỗi: ${response.statusCode}');
}
} catch (e) {
print('Lỗi: $e');
}
}
Future<void> setSubscriptionDuration(double d) async {
mSubscriptionDuration = d;
setState(() {});
await _mRecorder.setSubscriptionDuration(
Duration(milliseconds: d.floor()),
);
}
void cancelRecorderSubscriptions() {
if (_recorderSubscription != null) {
_recorderSubscription!.cancel();
_recorderSubscription = null;
}
}
Fn? getPlaybackFn(FlutterSoundRecorder? recorder) {
if (!_mRecorderIsInited) {
log("getPlaybackFn: ${_mRecorderIsInited}");
return null;
}
return recorder!.isStopped
? () {
record(recorder);
}
: () {
uploadRecord(recorder).then((value) => setState(() {}));
};
}
Widget setTile(bool isRecord, bool isDelete, bool isHold) {
if (isRecord && isDelete) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: EdgeInsets.all(5),
child: Text("${pos ~/ 1000}s"),
),
Padding(
padding: EdgeInsets.all(10.0),
child: Text("Xóa tệp ghi âm"),
)
],
);
}
if (isRecord && isHold) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(padding: EdgeInsets.all(5), child: Text("${pos ~/ 1000}s")),
Padding(
padding: EdgeInsets.all(10.0),
child: Text("Chế độ rảnh tay"),
)
],
);
}
if (isRecord) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(padding: EdgeInsets.all(5), child: Text("${pos ~/ 1000}s")),
Padding(
padding: EdgeInsets.all(10.0),
child: Text("Sang trái để xóa, sang phải để rảnh tay"),
)
],
);
}
return const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: EdgeInsets.all(20.0),
child: Text("Nhấn và giữ để ghi âm"),
)
],
);
}
@override
void initState() {
super.initState();
getApplicationDocumentsDirectory()
.then((value) => _tempDirectory = value.path);
init().then((value) {
_mRecorderIsInited = true;
setState(() {});
});
isRecord = false;
}
@override
void dispose() {
cancelRecording(_mRecorder);
cancelRecorderSubscriptions();
connection?.finish();
timer?.cancel();
_mRecorder.closeRecorder();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 50),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
setTile(isRecord, isDelete, isHold),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
DragTarget(
onAccept: (data) {
log("onAccept Delete");
cancelRecording(_mRecorder);
isDelete = false;
isRecord = false;
isActiveHold = false;
tempButton = recordButton;
setState(() {});
},
onWillAccept: (data) {
tempButton = delelteButton;
isDelete = true;
setState(() {});
return true;
},
onLeave: (data) {
log("onLeave");
tempButton = recordButton;
isDelete = false;
setState(() {});
},
builder: (context, candidateData, rejectedData) {
return isRecord && !isHold
? Container(
width: 80,
height: 80,
decoration: BoxDecoration(
border:
Border.all(color: Colors.red, width: 2),
borderRadius: BorderRadius.circular(50)),
child: const Icon(Icons.delete,
color: Colors.red, size: 30))
: isActiveHold
? Container(
width: 80,
height: 80,
decoration: BoxDecoration(
border: Border.all(
color: Colors.red, width: 2),
borderRadius:
BorderRadius.circular(50)),
child: GestureDetector(
child: IconButton(
onPressed: () async {
await cancelRecording(_mRecorder);
log("onclick Delete");
isDelete = false;
isRecord = false;
isActiveHold = false;
isHold = false;
tempButton = recordButton;
setState(() {});
},
icon: const Icon(Icons.delete,
color: Colors.red, size: 30)),
))
: Container();
},
),
],
),
),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Draggable<int>(
data: 1,
feedback: Container(),
childWhenDragging: Container(
width: 80,
height: 80,
decoration: BoxDecoration(
border: Border.all(color: Colors.blue, width: 2),
borderRadius: BorderRadius.circular(50)),
child: tempButton),
onDragEnd: (details) {
if (isHold) {
log("isHold: $isHold");
tempButton = sendButton;
setState(() {});
}
},
child: GestureDetector(
onTapDown: (data) async {
if (isActiveHold && isRecord) {
await uploadRecord(_mRecorder);
isActiveHold = false;
isRecord = false;
isDelete = false;
isHold = false;
tempButton = recordButton;
setState(() {});
return;
}
log("onTapDown:");
startRecord();
setState(() {});
},
onTapUp: (details) async {
if (!isActiveHold) {
// pos = 0;
//timer?.cancel;
await uploadRecord(_mRecorder);
log("onTapUp:");
isRecord = false;
setState(() {});
}
},
child: Container(
width: 80,
height: 80,
decoration: BoxDecoration(
border: Border.all(color: Colors.blue, width: 2),
borderRadius: BorderRadius.circular(50)),
child: tempButton,
),
),
),
],
),
),
Expanded(
child: !isActiveHold
? Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
DragTarget(
onAccept: (data) {
log("onAccept Hold");
isHold = true;
isActiveHold = true;
setState(() {});
},
onWillAccept: (data) {
tempButton = holdButton;
isHold = true;
setState(() {});
return true;
},
onLeave: (data) {
log("onLeave");
tempButton = recordButton;
isHold = false;
setState(() {});
},
builder: (context, candidateData, rejectedData) {
return isRecord && !isDelete
? Container(
width: 80,
height: 80,
decoration: BoxDecoration(
border: Border.all(
color: Colors.green, width: 2),
borderRadius:
BorderRadius.circular(50)),
child: const Icon(Icons.lock_open,
color: Colors.green, size: 30))
: Container();
},
),
],
)
: Container(),
),
],
),
SizedBox(height: 25),
],
),
);
}
void startRecord() {
pos = 0;
timer?.cancel();
record(_mRecorder);
isRecord = true;
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/services/ChatService.dart | import 'dart:convert';
import 'package:http/http.dart';
import 'package:skysoft_taxi/url/contants.dart';
Future<List<dynamic>> getAll() async {
Response response = await get(Uri.parse(URL_CHAT_GETALL));
if (response.statusCode == 200) {
final Map<String, dynamic> responseData = jsonDecode(response.body);
return responseData["chats"];
} else {
print('Upload thất bại. Mã lỗi: ${response.statusCode}');
}
return [];
}
| 0 |
mirrored_repositories/Skysoft_Taxi/lib | mirrored_repositories/Skysoft_Taxi/lib/services/WebSocketService.dart | import 'dart:convert';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:web_socket_channel/io.dart';
const String SENDER = "sender";
const String MESSAGE = "message";
const String NAMEDEFAULT = "serverWs";
class WebSocketService {
String url;
IOWebSocketChannel? webSocket;
String content = "";
Map<String, ValueNotifier<String>> queue = {
"owner": ValueNotifier<String>("")
};
final Map<String, String> _bindExchange = {};
WebSocketService({required this.url});
void connectToServer() {
if (webSocket != null) {
return;
}
try {
webSocket = IOWebSocketChannel.connect(url);
bindExchangeDefautl();
startListener();
} catch (e) {
print(e);
}
}
void startListener() {
if (webSocket == null) {
print("Web socket not init");
return;
}
webSocket?.stream.listen((message) {
final Map<String, dynamic> messageData = jsonDecode(message);
log(message);
String sender = messageData[SENDER];
content = messageData[MESSAGE];
queue[_bindExchange[sender]]?.value = content;
});
}
void bindExchangeDefautl() {
bindExchange("owner", NAMEDEFAULT);
}
void bindExchange(String nameQueue, String nameExchange) {
_bindExchange[nameExchange] = nameQueue;
}
void sendMessage(String mes) {
webSocket!.sink.add(mes);
}
Map<String, ValueNotifier<String>> addQueueListener(String nameQueue) {
if (!queue.containsKey(nameQueue)) {
queue[nameQueue] = ValueNotifier<String>("");
}
return queue;
}
ValueNotifier<String>? getQueueListener(String nameQueue) {
if (!queue.containsKey(nameQueue)) throw Exception("Not found Queue");
return queue[nameQueue];
}
}
| 0 |
mirrored_repositories/Skysoft_Taxi | mirrored_repositories/Skysoft_Taxi/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:skysoft_taxi/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter_radio_list_tile | mirrored_repositories/flutter_radio_list_tile/lib/main.dart | import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: FirstScreen(),
);
}
}
class FirstScreen extends StatefulWidget {
const FirstScreen({Key? key}) : super(key: key);
@override
State<FirstScreen> createState() => _FirstScreenState();
}
class _FirstScreenState extends State<FirstScreen> {
String gender = 'male';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Radio List Tile'),
),
body: Center(child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
RadioListTile(
title: const Text('آقا'),
value: 'male',
groupValue: gender,
onChanged: (value) {
setState(() {
gender = value.toString();
});
},
), RadioListTile(
title: const Text('خانم'),
value: 'female',
groupValue: gender,
onChanged: (value) {
setState(() {
gender = value.toString();
});
},
), RadioListTile(
title: const Text('دیگر'),
value: 'other',
groupValue: gender,
onChanged: (value) {
setState(() {
gender = value.toString();
});
},
),
],
),),
);
}
}
| 0 |
mirrored_repositories/flutter_radio_list_tile | mirrored_repositories/flutter_radio_list_tile/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_radio_button/main.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-bloc-hackathon-starter | mirrored_repositories/flutter-bloc-hackathon-starter/lib/main_staging.dart | // Copyright (c) 2021, Very Good Ventures
// https://verygood.ventures
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import 'package:flutter_bloc_hackathon_starter/app/app.dart';
import 'package:flutter_bloc_hackathon_starter/bootstrap.dart';
void main() {
bootstrap(() => const App());
}
| 0 |
mirrored_repositories/flutter-bloc-hackathon-starter | mirrored_repositories/flutter-bloc-hackathon-starter/lib/main_production.dart | // Copyright (c) 2021, Very Good Ventures
// https://verygood.ventures
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import 'package:flutter_bloc_hackathon_starter/app/app.dart';
import 'package:flutter_bloc_hackathon_starter/bootstrap.dart';
void main() {
bootstrap(() => const App());
}
| 0 |
mirrored_repositories/flutter-bloc-hackathon-starter | mirrored_repositories/flutter-bloc-hackathon-starter/lib/bootstrap.dart | // Copyright (c) 2021, Very Good Ventures
// https://verygood.ventures
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import 'dart:async';
import 'dart:developer';
import 'package:bloc/bloc.dart';
import 'package:flutter/widgets.dart';
class AppBlocObserver extends BlocObserver {
@override
void onChange(BlocBase bloc, Change change) {
super.onChange(bloc, change);
log('onChange(${bloc.runtimeType}, $change)');
}
@override
void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
log('onError(${bloc.runtimeType}, $error, $stackTrace)');
super.onError(bloc, error, stackTrace);
}
}
Future<void> bootstrap(FutureOr<Widget> Function() builder) async {
//Bloc. = AppBlocObserver();
FlutterError.onError = (details) {
log(details.exceptionAsString(), stackTrace: details.stack);
};
await runZonedGuarded(
() async => runApp(await builder()),
(error, stackTrace) => log(error.toString(), stackTrace: stackTrace),
);
}
| 0 |
mirrored_repositories/flutter-bloc-hackathon-starter | mirrored_repositories/flutter-bloc-hackathon-starter/lib/main_development.dart | // Copyright (c) 2021, Very Good Ventures
// https://verygood.ventures
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import 'package:flutter_bloc_hackathon_starter/app/app.dart';
import 'package:flutter_bloc_hackathon_starter/bootstrap.dart';
void main() {
bootstrap(() => const App());
}
| 0 |
mirrored_repositories/flutter-bloc-hackathon-starter/lib | mirrored_repositories/flutter-bloc-hackathon-starter/lib/app/app.dart | // Copyright (c) 2021, Very Good Ventures
// https://verygood.ventures
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
export 'view/app.dart';
| 0 |
mirrored_repositories/flutter-bloc-hackathon-starter/lib | mirrored_repositories/flutter-bloc-hackathon-starter/lib/app/app_router.dart | class AppRouter {}
| 0 |
mirrored_repositories/flutter-bloc-hackathon-starter/lib/app | mirrored_repositories/flutter-bloc-hackathon-starter/lib/app/view/app.dart | // Copyright (c) 2021, Very Good Ventures
// https://verygood.ventures
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import 'package:flutter/material.dart';
import 'package:flutter_bloc_hackathon_starter/l10n/l10n.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
class App extends StatelessWidget {
const App({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
appBarTheme: const AppBarTheme(color: Color(0xFF13B9FF)),
colorScheme: ColorScheme.fromSwatch(
accentColor: const Color(0xFF13B9FF),
),
),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
);
}
}
| 0 |
mirrored_repositories/flutter-bloc-hackathon-starter/lib | mirrored_repositories/flutter-bloc-hackathon-starter/lib/l10n/l10n.dart | // Copyright (c) 2021, Very Good Ventures
// https://verygood.ventures
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import 'package:flutter/widgets.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
export 'package:flutter_gen/gen_l10n/app_localizations.dart';
extension AppLocalizationsX on BuildContext {
AppLocalizations get l10n => AppLocalizations.of(this);
}
| 0 |
mirrored_repositories/flutter-bloc-hackathon-starter/test/app | mirrored_repositories/flutter-bloc-hackathon-starter/test/app/view/app_test.dart | // Copyright (c) 2021, Very Good Ventures
// https://verygood.ventures
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import 'package:flutter_bloc_hackathon_starter/app/app.dart';
import 'package:flutter_bloc_hackathon_starter/presentation/view/counter/counter.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('App', () {
testWidgets('renders CounterPage', (tester) async {
await tester.pumpWidget(const App());
expect(find.byType(CounterPage), findsOneWidget);
});
});
}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.