-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflutter_snippets
1106 lines (886 loc) · 38.3 KB
/
flutter_snippets
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
=================================================================================================
Install flutter
=================================================================================================
1. Follow step 1 to 3 from below link
https://flutter.dev/docs/get-started/install/macos
2. Run command flutter in terminal it will download dart sdk
3. Update the environment path.
Open terminal.
vim $HOME/.zshrc
Press "I" key for going to insert mode.
add the following line in the opened file:
export PATH="$PATH:/YOUR_FLUTTER_DIR/flutter/bin"
Press "Esc" then write :wq! in terminal and press enter to exit vim.
Reopen the terminal and check "flutter doctor"
if flutter doctor is showing any then its also shows command to solve that issue
***** alternative way ***
run this command in terminal to find available versions of jdk in your system
/usr/libexec/java_home -V | grep jdk
add jdk version in gradle.properties file
org.gradle.java.home=/Users/ervinod/Library/Java/JavaVirtualMachines/corretto-1.8.0_302/Contents/Home
=================================================================================================
git : Device not configured
=================================================================================================
In your project go to .git/config and add after username :password
before : https://[email protected]/repo.git
afetr : https://username:[email protected]/repo.git
=================================================================================================
Set alignment of Widgets
=================================================================================================
Center vertically
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[ ... ],
)
Center horizontally
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[ ... ],
)
But if the column is hugging its content then just wrap it in a Center widget
Center(
child: Column(
children: <Widget>[ ... ],
),
)
=================================================================================================
Change Flutter App Name
=================================================================================================
Android
Open AndroidManifest.xml (located at android/app/src/main)
<application
android:label="App Name" ...> // Your app name here
iOS
Open info.plist (located at ios/Runner)
<key>CFBundleName</key>
<string>App Name</string> // Your app name here
Don't forget to run
flutter clean
=================================================================================================
Add delay
=================================================================================================
new Future.delayed(const Duration(seconds: 1)); //recommend
new Timer(const Duration(seconds: 1), ()=>print("1 second later."));
sleep(const Duration(seconds: 1)); //import 'dart:io';
new Stream.periodic(const Duration(seconds: 1), (_) => print("1 second later.")).first.then((_)=>print("Also 1 second later."));
=================================================================================================
Show AlertDialog
=================================================================================================
void _showSignoutDialog(BuildContext context, GlobalKey<ScaffoldState> formKey, SharedPreferences sharedPreferences){
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text(TextFile.SIGNOUT_TITLE, style: TextStyle(color: Colors.black.withOpacity(0.8))),
content: new Text(TextFile.SIGNOUT_DESCRIPTION),
actions: <Widget>[
new FlatButton(
child: new Text(TextFile.BUTTON_CANCEL),
onPressed: () async {
Navigator.of(context).pop();
},
),
new FlatButton(
child: new Text(TextFile.BUTTON_SIGNOUT),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
=================================================================================================
Change button color if text entered in textfield is valid
=================================================================================================
https://stackoverflow.com/a/58691020
show hide widget on UI using Bloc
https://stackoverflow.com/a/55594815
=================================================================================================
Change button color if text entered in textfield is valid
=================================================================================================
1. In your pubspec.yaml file add this:
dependencies:
device_info: ^0.4.0+4
2. Create a method:
Future<String> _getId() async {
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
if (Theme.of(context).platform == TargetPlatform.iOS) {
IosDeviceInfo iosDeviceInfo = await deviceInfo.iosInfo;
return iosDeviceInfo.identifierForVendor; // unique ID on iOS
} else {
AndroidDeviceInfo androidDeviceInfo = await deviceInfo.androidInfo;
return androidDeviceInfo.androidId; // unique ID on Android
}
}
3. Use it like:
String deviceId = await _getId();
//or u can call below function to get more device info
static Future<List<String>> getDeviceDetails() async {
String deviceName;
String deviceVersion;
String identifier;
final DeviceInfoPlugin deviceInfoPlugin = new DeviceInfoPlugin();
try {
if (Platform.isAndroid) {
var build = await deviceInfoPlugin.androidInfo;
deviceName = build.model;
deviceVersion = build.version.toString();
identifier = build.androidId; //UUID for Android
} else if (Platform.isIOS) {
var data = await deviceInfoPlugin.iosInfo;
deviceName = data.name;
deviceVersion = data.systemVersion;
identifier = data.identifierForVendor; //UUID for iOS
}
} on PlatformException {
print('Failed to get platform version');
}
//if (!mounted) return;
return [deviceName, deviceVersion, identifier];
}
=================================================================================================
Make specific parts of a text clickable (spannable/ rich text)
=================================================================================================
Widget build(BuildContext context) {
TextStyle defaultStyle = TextStyle(color: Colors.grey, fontSize: 20.0);
TextStyle linkStyle = TextStyle(color: Colors.blue);
return RichText(
text: TextSpan(
style: defaultStyle,
children: <TextSpan>[
TextSpan(text: 'By clicking Sign Up, you agree to our '),
TextSpan(
text: 'Terms of Service',
style: linkStyle,
recognizer: TapGestureRecognizer()
..onTap = () {
print('Terms of Service"');
}),
TextSpan(text: ' and that you have read our '),
TextSpan(
text: 'Privacy Policy',
style: linkStyle,
recognizer: TapGestureRecognizer()
..onTap = () {
print('Privacy Policy"');
}),
],
),
);
}
=================================================================================================
Password TextField toggle
=================================================================================================
1. Declase boolean variable to keep track of visibility
bool _obscurePassword = true;
2. Write function to toggle boolean variable
void _togglePasswordVisibility() {
setState(() {
_obscurePassword = !_obscurePassword;
});
}
3. Configure TextFormField widget
TextFormField(
obscureText: _obscurePassword,
decoration: InputDecoration(
hintText: "Enter your password",
suffixIcon: IconButton(
onPressed: () => _togglePasswordVisibility(),
icon: Icon(Icons.remove_red_eye, color: this._obscurePassword ? Colors.blue : Colors.grey,),
),
),
)
=================================================================================================
build production/release apk for flutter project
=================================================================================================
1. create key.properties file and modify build.gradle file according to below link
https://flutter.dev/docs/deployment/android
2. use below command to build release apk
flutter build apk --release
=================================================================================================
call post api as raw request body
=================================================================================================
Map data = {
'mobile_no': mobile_no,
'otp': enteredOTP,
};
//encode Map to JSON
var requestBody = json.encode(data);
debugPrint(requestBody);
if(response.statusCode==200){
// api success
Map<String , dynamic> jsonResopnse = json.decode(response.body);
http.Response response = await http.post(ApiConstants.VERIFYOTP, body: requestBody);
}else {
// api error
}
=================================================================================================
Manage sqlite db version in flutter
=================================================================================================
Future<Database> initDb() async {
final databasesPath = await getDatabasesPath();
final path = join(databasesPath, "database.db");
var db = await openDatabase(path);
//if database does not exist yet it will return version 0
if (await db.getVersion() < NEW_DB_VERSION) {
db.close();
//delete the old database so you can copy the new one
await deleteDatabase(path);
try {
await Directory(dirname(path)).create(recursive: true);
} catch (_) {}
//copy db from assets to database folder
ByteData data = await rootBundle.load("assets/databases/database.db");
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await File(path).writeAsBytes(bytes, flush: true);
//open the newly created db
db = await openDatabase(path);
//set the new version to the copied db so you do not need to do it manually on your bundled database.db
db.setVersion(NEW_DB_VERSION);
}
return db;
}
}
=================================================================================================
Get today's formated date
=================================================================================================
import 'package:intl/intl.dart';
DateTime now = new DateTime.now();
DateTime date = new DateTime(now.year, now.month, now.day);
final customDateFormat = new DateFormat('yyyy-MM-dd');
var mDate = customDateFormat.format(date);
String getFormattedDate(String dateString){
try{
DateTime now = DateTime.parse(dateString);
//String mDate = DateFormat().addPattern("yyyy-MM-dd HH:mm:ss").format(now);
String mDate = DateFormat().addPattern("dd-MM-yyyy").format(now);
//final customDateFormat = new DateFormat('dd-MM-yyyy');
//var mDate = customDateFormat.format(now);
return mDate.toString();
}catch(_){
return dateString;
}
}
=================================================================================================
Parse JSON Object
=================================================================================================
List<dynamic> _declarationList = [];
var userDetails = _declarationList[index]["user_details"];
var user_name = userDetails["name"];
var userDetails = json.decode(_declarationList[index]["user_details"]);
var user_name = userDetails["name"];
Map<String, dynamic> userDetails = json.decode(optionArray);
var user_name = userDetails["name"];
=================================================================================================
Add press back agait to exit app message
=================================================================================================
//add dependency to show toast message
fluttertoast: 4.0.1
DateTime currentBackPressTime;
@override
Widget build(BuildContext context) {
return Scaffold(
...
body: WillPopScope(child: getBody(), onWillPop: onWillPop),
);
}
Future<bool> onWillPop() {
DateTime now = DateTime.now();
if (currentBackPressTime == null ||
now.difference(currentBackPressTime) > Duration(seconds: 2)) {
currentBackPressTime = now;
Fluttertoast.showToast(msg: "Press BACK again to exit...");
return Future.value(false);
}
return Future.value(true);
}
=================================================================================================
Show timer inside dialog (alert dialog)
=================================================================================================
1. Add code in intiState()
@override
void initState() {
super.initState();
super.init(context, _scaffoldState, state: this);
_events = new StreamController<int>.broadcast();
_events.add(5);// 5 second timer
}
2. create timer
Timer _timer;
StreamController<int> _events;//state level declaration
void _startTimer() {
_counter = 5;
if (_timer != null) {
_timer.cancel();
}
_timer = Timer.periodic(Duration(seconds: 1), (timer) {
//setState(() {
(_counter > 0) ? _counter-- : _timer.cancel();
//});
print(_counter);
_events.add(_counter);
});
}
3. declare function to show AlertDialog
void showAlertDialog(BuildContext ctx) {
var alert = AlertDialog(
// title: Center(child:Text('Enter Code')),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0))),
backgroundColor: Colors.grey[100],
elevation: 0.0,
content: StreamBuilder<int>(
stream: _events.stream,
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
bool isVisible = false;
if(snapshot.data!=null && snapshot.data.toString()=="0"){
isVisible = true;
}
print(snapshot.data.toString());
return Container(
height: 215,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
top: 10, left: 10, right: 10, bottom: 15),
child: Text(
'Enter Code',
style: TextStyle(
color: Colors.green[800],
fontWeight: FontWeight.bold,
fontSize: 16),
)),
Container(
height: 70,
width: 180,
child: TextFormField(
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.green, width: 0.0)),
),
keyboardType: TextInputType.number,
maxLength: 10,
),
),
SizedBox(
height: 1,
),
Text(snapshot.hasData?'00:${snapshot.data.toString()}':'00:00'),
SizedBox(
height: 15,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.circular(25),
child: Material(
child: InkWell(
onTap: () {
//Navigator.of(ctx).pushNamed(SignUpScreenSecond.routeName);
},
child: Container(
width: 100,
height: 50,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25),
gradient: LinearGradient(
colors: [
Colors.green,
Colors.grey,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight),
),
child: Center(
child: Text(
'Validate',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold),
)),
),
),
),
),
Visibility(
visible: isVisible,
child: ClipRRect(
borderRadius: BorderRadius.circular(25),
child: Material(
child: InkWell(
onTap: () {},
child: Container(
width: 100,
height: 50,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25),
gradient: LinearGradient(
colors: [
Colors.grey,
Colors.green,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight),
),
child: Center(
child: Text(
'Resend',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold),
)),
),
),
),
),
)
],
), //new column child
],
),
);
}));
showDialog(
context: ctx,
builder: (BuildContext c) {
return alert;
});
}
4. show AlertDialog
_startTimer();//to start timer
showAlert(context);//to show dialog
=================================================================================================
Lock Screen Rotation of entire app
=================================================================================================
1. Create following mixin PortraitModeMixin.dart file
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// Forces portrait-only mode application-wide
/// Use this Mixin on the main app widget i.e. app.dart
/// Flutter's 'App' has to extend Stateless widget.
///
/// Call `super.build(context)` in the main build() method
/// to enable portrait only mode
mixin PortraitModeMixin on StatelessWidget {
@override
Widget build(BuildContext context) {
_portraitModeOnly();
return null;
}
}
/// Forces portrait-only mode on a specific screen
/// Use this Mixin in the specific screen you want to
/// block to portrait only mode.
///
/// Call `super.build(context)` in the State's build() method
/// and `super.dispose();` in the State's dispose() method
mixin PortraitStatefulModeMixin<T extends StatefulWidget> on State<T> {
@override
Widget build(BuildContext context) {
_portraitModeOnly();
return null;
}
@override
void dispose() {
_enableRotation();
}
}
/// blocks rotation; sets orientation to: portrait
void _portraitModeOnly() {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
}
void _enableRotation() {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
}
2. Use this mixin in main.dart file
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget with PortraitModeMixin{
@override
Widget build(BuildContext context) {
super.build(context);//important
return MaterialApp(
title: "Demo App",
debugShowCheckedModeBanner: false,
initialRoute: SplashScreen.routeName,
routes: routes,
);
}
}
To block rotation in a specific screen implement PortraitStatefulModeMixin<SampleScreen> in
the specific screen's state. Remember to call super.build(context) in the State's build() method
and super.dispose() in dispose() method. If your screen is a StatelessWidget - simply repeat the
App's solution (previous example) i.e. use PortraitModeMixin.
/// Specific screen
class SampleScreen extends StatefulWidget {
SampleScreen() : super();
@override
State<StatefulWidget> createState() => _SampleScreenState();
}
class _SampleScreenState extends State<SampleScreen>
with PortraitStatefulModeMixin<SampleScreen> {
@override
Widget build(BuildContext context) {
super.build(context);
return Text("Flutter - Block screen rotation example");
}
@override
void dispose() {
super.dispose();
}
}
=================================================================================================
Configure ImagePicker plugin for iOS build
=================================================================================================
add below lines in end of info.plist file (i.e. just above tag </dict>)
//file location - <project root>/ios/Runner/Info.plist
<key>NSPhotoLibraryUsageDescription</key>
<string>Need to upload image</string>
<key>NSCameraUsageDescription</key>
<string>Need to upload image</string>
<key>NSMicrophoneUsageDescription</key>
<string>Need to upload image</string>
=================================================================================================
NDK version issue solution
=================================================================================================
Error: No version of NDK matched the requested version 20.0.5594570. Versions available locally: 21.0.6113669
Step 1. Upgrade gradle plugin version - android -> build.gradle
classpath 'com.android.tools.build:gradle:4.1.2'
Step 2. Change gradle distribution url - android->gradle->wrapper->gradle-wrapper.properties
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip
Step 3. Remove NDK path from local.properties
Step 4. Clean , pub get and run
or you can explictly set ndk version in build.gradle
android {
compileSdkVersion 29
ndkVersion "21.0.6113669"
=================================================================================================
Trim String
=================================================================================================
String link = 'http://sales.local/api/v1/payments/454/ticket/verify?token=jhvycygvjhbknm.eyJpc3MiOiJodH';
String delimiter = '/ticket';
int lastIndex = link.indexOf(delimiter);
String trimmed = link.substring(0,lastIndex);
print(trimmed);
=================================================================================================
Get remaining time by comparing 2 dates
=================================================================================================
String _getRemainingTime(Duration duration) {
//if you want like 02 hours instead of 2 hours
//String twoDigits(int n) => n.toString().padLeft(2, "0");
/*String twoDigits(int n) => n.toString();
String twoDigitDays = twoDigits(duration.inDays.remainder(7));
String twoDigitHours = twoDigits(duration.inHours.remainder(24));
String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));*/
int twoDigits(int n) => n;
int daysRemain = twoDigits(duration.inDays.remainder(7));
int hoursRemain = twoDigits(duration.inHours.remainder(24));
int minutesRemain = twoDigits(duration.inMinutes.remainder(60));
int secondsRemain = twoDigits(duration.inSeconds.remainder(60));
if(daysRemain==0){
return "$hoursRemain Hours left";
}
if(daysRemain>0){
return "$daysRemain Days $hoursRemain hours left";
}
if(daysRemain==0 && hoursRemain==0 ){
return 'Less than a hour left';
}
return "$daysRemain Days $hoursRemain hours left";
}
=================================================================================================
Get ago time by comparing 2 dates
=================================================================================================
static String timeAgo(DateTime date, {bool numericDates = true}) {
if (date == null) return "";
final date2 = DateTime.now();
final difference = date2.difference(date);
// print('day dff : ${difference.inDays}');
if (difference.inSeconds < 2) {
return 'Just now';
} else if (difference.inSeconds <= 59) {
return '${difference.inSeconds} Sec ago';
} else if (difference.inMinutes <= 1) {
return numericDates ? '1 Min ago' : 'A min ago';
} else if (difference.inMinutes <= 59) {
return '${difference.inMinutes} Min ago';
} else if (difference.inHours == 1) {
return numericDates ? '1 Hr ago' : 'An Hr ago';
} else if (difference.inHours <= 24) {
return '${difference.inHours}h ago';
} else if (difference.inDays <= 1) {
return numericDates ? '1d ago' : 'Yesterday';
} else if (difference.inDays <= 6) {
return '${difference.inDays}d ago';
} else if ((difference.inDays / 7).floor() <= 1) {
return numericDates ? '1 week ago' : 'Last week';
} else if ((difference.inDays / 7).floor() <= 4) {
return '${(difference.inDays / 7).floor()} weeks ago';
} else if ((difference.inDays / 30).floor() <= 1) {
return numericDates ? '1 month ago' : 'Last month';
} else if ((difference.inDays / 30).floor() <= 11) {
return '${(difference.inDays / 30).floor()} months ago';
} else if ((difference.inDays / 365).floor() <= 1) {
return numericDates ? '1 yr ago' : 'Last year';
} else {
return '${(difference.inDays / 365).floor()} years ago';
}
}
=================================================================================================
Get .apk from .aab file
=================================================================================================
If you want to install apk from your aab to your device for testing purpose then you need to edit
the configuration(app is default) before running it on the connected device.
or
For Debug apk command,
bundletool build-apks --bundle=/MyApp/my_app.aab --output=/MyApp/my_app.apks
For Release apk command,
bundletool build-apks --bundle=/MyApp/my_app.aab --output=/MyApp/my_app.apks
--ks=/MyApp/keystore.jks
--ks-pass=file:/MyApp/keystore.pwd
--ks-key-alias=MyKeyAlias
--key-pass=file:/MyApp/key.pwd
=================================================================================================
show loader
=================================================================================================
void showLoader() {
showDialog(
context: context,
barrierDismissible: false,///dismiss on touch outside loader
builder: (BuildContext context) {
return WillPopScope(
onWillPop: () async => false,///to dismiss loader on backbutton key press
child: Center(
child: SizedBox(
width: 30,
height: 30,
child: CircularProgressIndicator(
),
),
),
);
},
);
}
=================================================================================================
get comma seperated string from List<String>
=================================================================================================
List cities = ['NY', 'LA', 'Tokyo'];
String formattedString = getCommaSeparatedString(cities);
print(formattedString);
String getCommaSeparatedString(List list) {
String formattedStr ='';
for(var i in list) {
formattedStr += '$i, ';
}
return formattedStr.replaceRange(formattedStr.length -2, formattedStr.length, '');
}
String getCommaSeparatedString(List<String> arguments) {
String str = cities.join(', ');
return str;
}
=================================================================================================
Detect left/right swipe on page/widget
=================================================================================================
1. wrap widget with GestureDetector
2. detect swipe in onPanUpdate method
GestureDetector(
onPanUpdate: (details) {
// Swiping in right direction.
if (details.delta.dx > 0) {
EasyDebounce.debounce(
"swipe_backward_debounce",
const Duration(milliseconds: 200),
() {
log("swipe to right, go back");
},
);
} else if (details.delta.dx < 0) {
EasyDebounce.debounce(
"swipe_forward_debounce",
const Duration(milliseconds: 200),
() {
log("swipe to left, go forward");
},
);
}
},
child: Container(),
)
=================================================================================================
Generate SHA key for flutter project
=================================================================================================
*** GUI method ***
1. Open Project in Android Studio in PROJECT view
2. Reveal android folder
3. Right click "gradlew" file and select Open in Terminal
4. Go to the terminal view and paste: ./gradlew signingReport gradlew signingReport if you're using Unix-based system like Mac or a PowerShell.
5. Press enter and scroll to "Variant: release" to get the SHA1 key
`*** Terminal method ***
Go to the project folder in the terminal.
Mac keytool -list -v -keystore ./android/debug.keystore -alias androiddebugkey -storepass android -keypass android
Windows keytool -list -v -keystore "\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
Linux keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
=================================================================================================
Create keystore for Android build
=================================================================================================
1. Create Keystore
To create Keystore run this command
move to your directoty - yourapp/android and run below command
keytool -genkey -v -keystore keystore.jks -storepass Android@123 -alias android -keypass Android@123 -keyalg RSA -keysize 2048 -validity 10000
Then fill the required details asked in commandline
Enter keystore password: javacaps
What is your first and last name?
[Unknown]: development.sun.com
What is the name of your organizational unit?
[Unknown]: Development
what is the name of your organization?
[Unknown]: Sun
What is the name of your City or Locality?
[Unknown]: Monrovia
What is the name of your State or Province?
[Unknown]: California
What is the two-letter country code for this unit?
[Unknown]: US
Is<CN=development.sun.com, OU=Development, O=Sun, L=Monrovia, ST=California,
C=US> correct?
[no]: yes
Enter key password for <client>
(RETURN if same as keystore password):
2. Create key.properties file in android directory and add below content to it
storePassword=MyApp@2024
keyPassword=MyApp@2024
keyAlias=myapp
storeFile=../keystore.jks
3. use keys created in step 2 to generate release build
open app/build.gradle file and add release config
//=============== Keystore Config ===============
def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}
//=============== ===============
// this code should ideally be added above appy plugin section
// apply plugin: 'com.android.application'
Add below code below defaultConfig{} section
signingConfigs {
release {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
storePassword keystoreProperties['storePassword']
}
}
buildTypes {
release {
signingConfig signingConfigs.release
minifyEnabled true
shrinkResources true
}
debug{
signingConfig signingConfigs.debug
}
}
=================================================================================================
Create app build (while using app flavors)
=================================================================================================
set appropriate version code in pubspec.yaml (ex 1.0.0+1)
Command to run App
flutter run --flavor PROD -t lib/main_prod.dart