A collection of useful code snippets, configurations, and utilities from my GitHub Gists. These are real-world solutions I use in my projects.
1// ... StatefulWidget
2
3int quantity = 0;
4final int maxQuantity = 1000;
5StreamSubscription<int>? _increaseSubscription;
6
7Stream<int> createAcceleratingIncreasingStream() {
8 return Stream.periodic(const Duration(milliseconds: 100), (count) {
9 int increment;
10 if (count < 20) {
11 // First 2 seconds (20 * 100ms)
12 increment = 1;
13 } else if (count < 40) {
14 // Next 2 seconds
15 increment = 10;
16 } else {
17 // After 4 seconds total
18 increment = 100;
19 }
20 return quantity + increment;
21 }).takeWhile((value) => value <= maxQuantity);
22 }
23
24void _startIncreasing() {
25 _increaseSubscription = createAcceleratingIncreasingStream().listen((
26 value,
27 ) {
28 setState(() {
29 if (value <= widget.stock.quantity) {
30 quantity = value;
31 } else {
32 _increaseSubscription?.cancel();
33 ScaffoldMessenger.of(context).showSnackBar(
34 SnackBar(
35 content: Text("Maximum quantity is $maxQuantity"),
36 backgroundColor: Colors.red[300],
37 ),
38 );
39 }
40 });
41 });
42 }
43
44 void _stopIncreasing() {
45 _increaseSubscription?.cancel();
46 }
47
48// ... build method and a GestureDetector for example
49 return GestureDetector(
50 onLongPressStart: (_) => _startDecreasing(),
51 onLongPressEnd: (_) => _stopDecreasing(),
52 child: // child here...
53 )
1keytool -genkey -v -keystore ~/upload-keystore.jks -keyalg RSA -keysize 2048 -validity 10000 -alias upload
1import { Injectable } from '@nestjs/common';
2import { deleteFile, uploadFile } from '.';
3import { TransactionManager } from './transaction_manager.service';
4
5@Injectable()
6export class FileDbTransaction {
7 constructor(private readonly transactionManager: TransactionManager) {}
8
9 async createWithFileAndDb<T>(
10 file: Express.Multer.File,
11 folder: string,
12 dbOperation: (imageUrl: string) => Promise<T>,
13 ): Promise<T> {
14 return this.transactionManager.executeTransaction(async () => {
15 // Step 1: Upload file
16 const imageUrl = this.transactionManager.addStep(
17 uploadFile(file, folder),
18 () => {
19 try {
20 deleteFile(imageUrl);
21 } catch (error) {
22 console.error('Failed to delete file during rollback:', error);
23 }
24 },
25 );
26
27 // Step 2: Database operation
28 const result: T = (await this.transactionManager.addStep(
29 dbOperation(imageUrl),
30 )) as T;
31
32 return result;
33 });
34 }
35}
36
1import { Injectable } from '@nestjs/common';
2
3@Injectable()
4export class TransactionManager {
5 private steps: Array<{ result: any; rollback?: () => void }> = [];
6
7 async executeTransaction<T>(operation: () => Promise<T>): Promise<T> {
8 try {
9 const result = await operation();
10 this.steps = []; // Clear steps on success
11 return result;
12 } catch (error) {
13 this.rollback();
14 throw error;
15 }
16 }
17
18 addStep<T>(result: T, rollback?: () => void): T {
19 this.steps.push({ result, rollback });
20 return result;
21 }
22
23 private rollback() {
24 // Rollback in reverse order
25 for (let i = this.steps.length - 1; i >= 0; i--) {
26 const step = this.steps[i];
27 if (step.rollback) {
28 try {
29 step.rollback();
30 } catch (rollbackError) {
31 console.error('Rollback failed:', rollbackError);
32 }
33 }
34 }
35 this.steps = [];
36 }
37}
38
1#!/bin/bash
2
3# CONFIG
4DOMAIN="example.com"
5HOST="@" # Use "@" for root domain or "home" for home.yourdomain.com
6PASSWORD="YOUR_PASSWORD_HERE"
7SUBDOMAINS=("@" "subdomain1" "subdomain2" "subdomain3")
8# EXECUTE
9for HOST in "${SUBDOMAINS[@]}"; do
10 curl -s "https://dynamicdns.park-your-domain.com/update?host=$HOST&domain=$DOMAIN&password=$PASSWORD"
11done
1import 'package:flutter/material.dart';
2
3class ClipShadowPath extends StatelessWidget {
4 final Shadow shadow;
5 final CustomClipper<Path> clipper;
6 final Widget child;
7
8 const ClipShadowPath({
9 Key? key,
10 required this.shadow,
11 required this.clipper,
12 required this.child,
13 }) : super(key: key);
14
15
16 Widget build(BuildContext context) {
17 return CustomPaint(
18 painter: _ClipShadowShadowPainter(
19 clipper: clipper,
20 shadow: shadow,
21 ),
22 child: ClipPath(child: child, clipper: clipper),
23 );
24 }
25}
26
27class _ClipShadowShadowPainter extends CustomPainter {
28 final Shadow shadow;
29 final CustomClipper<Path> clipper;
30
31 _ClipShadowShadowPainter({required this.shadow, required this.clipper});
32
33
34 void paint(Canvas canvas, Size size) {
35 var paint = shadow.toPaint();
36 var clipPath = clipper.getClip(size).shift(shadow.offset);
37 canvas.drawPath(clipPath, paint);
38 }
39
40
41 bool shouldRepaint(CustomPainter oldDelegate) {
42 return true;
43 }
44}
11. **Learn Dart Basics:**
2 - Start by understanding the fundamentals of the Dart programming language since Flutter development is based on Dart.
3 - Utilize resources like the [Dart official website](https://dart.dev/tutorials) for tutorials and documentation.
4 - Supplement your learning with video tutorials available on platforms like YouTube.
5
62. **Set Up Flutter Environment:**
7 - Install Flutter on your machine and ensure it's correctly configured by running `flutter doctor`.
8 - Resolve any issues flagged by `flutter doctor` to ensure a smooth development experience.
9 - Seek help from online communities if you encounter difficulties during setup.
10
113. **Understand Flutter Structure and Widgets:**
12 - Get familiar with the Flutter framework's structure and how [widgets](https://docs.flutter.dev/ui/layout) are utilized to build UI components.
13 - Study different types of widgets available in Flutter and their usage patterns.
14 - Learn about [state management](https://docs.flutter.dev/data-and-backend/state-mgmt/intro) in Flutter, especially utilizing StatefulWidget for managing [dynamic UI](https://youtu.be/p5dkB3Mrxdo?si=Fja5KcXZTfn44nYN) elements.
15
164. **Explore Flutter Engine and Event Loop:**
17 - Dive deeper into the Flutter engine to understand its workings, including the [event loop](https://medium.com/dartlang/dart-asynchronous-programming-isolates-and-event-loops-bffc3e296a6a).
18 - Gain insights into asynchronous programming in Flutter and how it relates to managing user interactions and data fetching.
19 - Explore concepts like [Futures and Streams](https://dart.dev/codelabs/async-await), which are essential for handling [asynchronous operations](https://youtu.be/MlvqmRXKXyo?si=YqMi0wgjohal86z4) in Flutter.
20
215. **Build Simple Flutter Projects:**
22 - Start building simple Flutter projects to apply what you've learned so far.
23 - Begin with basic UI designs and gradually introduce more complex interactions.
24 - Experiment with different widgets and state management techniques in your projects to solidify your understanding.
25
266. **Explore Intermediate Concepts:**
27 - Once comfortable with the basics, explore more intermediate-level concepts such as navigation, animations, and platform integration.
28 - Learn about Flutter's routing system for navigating between screens and managing app navigation flows.
29 - Experiment with animations to create engaging UI transitions and effects.
30 - Explore how to integrate Flutter with platform-specific features like accessing device hardware or utilizing platform-specific APIs.
31
327. **Continuous Learning and Practice:**
33 - Keep exploring advanced Flutter topics and stay updated with the latest developments in the Flutter ecosystem.
34 - Engage with the Flutter community through forums, social media, and developer events to share knowledge and learn from others.
35 - Continuously practice by working on personal projects or contributing to open-source Flutter projects to enhance your skills further.
36 - Here's a [list of apps](https://github.com/ilies-space/app-ideas) you can build to strenghten your skills
37 -
38By following this roadmap, you'll gradually progress from learning the basics of Dart and Flutter to building your own Flutter projects and expanding your expertise in app development. Remember to stay patient, practice regularly, and don't hesitate to seek help or resources whenever needed. Happy Fluttering!
1exports.indexMessageToElasticsearch = functions.firestore
2 .document('Rooms/{roomId}/messages/{messageId}')
3 .onCreate(async (snap, context) => {
4 const roomId = context.params.roomId;
5 const messageId = context.params.messageId;
6 const messageData = snap.data();
7
8
9
10 const indexParams = {
11 index: 'search-messages',
12 body: {
13 // Customize the document structure based on your needs
14 roomId: roomId,
15 messageId: messageId,
16 message: messageData.message,
17 senderId: messageData.senderId,
18 receiverId: messageData.receiverId,
19 timestamp: messageData.timestamp,
20 type: messageData.type,
21 isRead: messageData.isRead,
22 // ...
23 },
24 };
25
26 try {
27 await elasticClient.index(indexParams);
28 console.log('Document indexed in Elasticsearch');
29 } catch (error) {
30 console.error('Error indexing document:', error);
31 }
32 });
1exports.sendNotification = functions.https.onCall(async (data, context) => {
2 const title = data.title;
3 const body = data.body;
4 const token = data.token;
5
6 try {
7 const payload = {
8 token: token,
9 notification: {
10 title: title,
11 body: body,
12 image: "https://firebasestorage.googleapis.com/v0/b/chatbox-3dac1.appspot.com/o/FCMImages%2FApp%20icon.png?alt=media&token=13eeecc5-afba-4cf7-a4dc-9814c32289a4",
13 },
14 data: {
15 image:"https://firebasestorage.googleapis.com/v0/b/chatbox-3dac1.appspot.com/o/FCMImages%2FApp%20icon.png?alt=media&token=13eeecc5-afba-4cf7-a4dc-9814c32289a4",
16 body: body,
17 },
18 };
19
20 return fcm.send(payload).then((response) => {
21 return {success: true, response: "Succefully sent message: " + response};
22 }).catch((error) => {
23 return {error: error};
24 });
25 } catch (error) {
26 throw new functions.https.HttpsError("invalid-argument", "error:" +error);
27 }
28});
1Future<UserCredential> signInWithGoogle({required String token}) async {
2 final GoogleSignInAccount? googleAccount = await GoogleSignIn().signIn();
3
4 final GoogleSignInAuthentication googleAuth =
5 await googleAccount!.authentication;
6
7 final credential = GoogleAuthProvider.credential(
8 accessToken: googleAuth.accessToken,
9 idToken: googleAuth.idToken,
10 );
11 UserCredential userCred =
12 await FirebaseAuth.instance.signInWithCredential(credential);
13 UserModel userModel = UserModel(
14 uid: userCred.user!.uid,
15 name: userCred.user!.displayName,
16 email: userCred.user!.email,
17 status: "online",
18 profilePhoto: userCred.user!.photoURL ??
19 "https://firebasestorage.googleapis.com/v0/b/chatbox-3dac1.appspot.com/o/Images%2FProfile-Dark.png?alt=media&token=14a7aa82-5323-4903-90fc-a2738bd42577",
20 token: [token]);
21 var value = await FirebaseFirestore.instance
22 .collection("Users")
23 .where("UserId", isEqualTo: userCred.user!.uid)
24 .get();
25 if (value.docs.isEmpty) {
26 FirebaseFirestore.instance.collection("Users").add(userModel.toMap());
27 }
28 return userCred;
29 }
1const DrawApple = (context, appleX, appleY, radius, alpha1, alpha2, alpha3) => {
2 const drawCircle = (x, y, r) => {
3 context.moveTo(x + r, y);
4 context.arc(x, y, r, 0, Math.PI * 2);
5 };
6
7 context.fillStyle = `rgba(67, 217, 173, ${alpha1})`;
8 context.beginPath();
9 drawCircle(appleX, appleY, radius);
10 context.fill();
11
12 context.fillStyle = `rgba(67, 217, 173, ${alpha2})`;
13 context.beginPath();
14 drawCircle(appleX, appleY, radius * 2);
15 context.fill();
16
17 context.fillStyle = `rgba(67, 217, 173, ${alpha3})`;
18 context.beginPath();
19 drawCircle(appleX, appleY, radius * 3);
20 context.fill();
21};
22
1//! Not Implemented cause lots of bugs !!!
2Future<Response<dynamic>> getDaylyForecastWeatherApi(
3 double lat, double lon, int day) async {
4 bool future;
5 future = DateTime.now().weekday < day ? true : false;
6 Response<dynamic> response;
7 final nowDate = DateTime.now().toString().split(" ")[0];
8 int newDay = int.parse(nowDate.split("-")[2]) + day - DateTime.now().weekday;
9 final newDate = "${nowDate.split("-")[0]}-${nowDate.split("-")[1]}-$newDay";
10 print(newDate);
11 if (future) {
12 response = await Dio().get(
13 "api.openweathermap.org/data/2.5/forecast/daily?lat=$lat&lon=$lon&cnt=7&appid=288215c433ffb3a0177d455c0c0b2375");
14 } else {
15 response = await Dio().get(
16 "http://api.weatherapi.com/v1/history.json?key=82f75908511d41dc8bb154417231003&q=$lat,$lon&dt=$newDate");
17 }
18 return response;
19}
1void _checkStatus(ConnectivityResult result) async {
2 bool isOnline = false;
3 try {
4 final result = await InternetAddress.lookup('example.com');
5 isOnline = result.isNotEmpty && result[0].rawAddress.isNotEmpty;
6 } on SocketException catch (_) {
7 isOnline = false;
8 }
9 _controller.sink.add({result: isOnline});
10 }
1Future<Response<dynamic>> getHourlyForecastWeatherApi(
2 double lat, double lon) async {
3 var response = await Dio().get(
4 'http://api.weatherapi.com/v1/forecast.json?key=$key&q=$lat,$lon&days=1&aqi=no&alerts=no');
5 return response;
6}
1Future<String> getUserLocation(Position myLocation) async {
2 LocalStorage storage = MyHomePage.getLocalStorage();
3 await storage.ready;
4 MyHomePage.getLocalStorage().getItem("Location") == null
5 ? MyHomePage.setFirstTimeLoading(true)
6 : MyHomePage.setFirstTimeLoading(false);
7 if (MyHomePage.getFirstTimeLoading()) {
8 List<Placemark> placemarks = await placemarkFromCoordinates(
9 myLocation.latitude, myLocation.longitude);
10 Placemark place = placemarks[0];
11 storage.setItem("Location", place.administrativeArea);
12 return place.administrativeArea!;
13 }
14 return storage.getItem("Location");
15}
Check out my GitHub profile for more code snippets, projects, and contributions.
Visit My GitHub