Google search engine
Home Blog Page 13

Automated Testing in Flutter with CI/CD: A Developer’s Comprehensive Guide

0

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table of Contents

Introduction

The Fundamentals of Automated Testing

CI/CD in Flutter: Accelerating Development with Automation

Achieving Automated Testing in Flutter with CI/CD

Overcoming Challenges in Flutter CI/CD Automation

Future Trends and Opportunities in CI/CD for Flutter

Conclusion

References


Introduction

Maintaining code quality while keeping up with the fast-paced release cycles is a challenge in modern app development. This is where automation testing and CI/CD (Continuous Integration and Continuous Deployment) come into play. Together, they offer developers a robust way to ensure their Flutter applications remain stable, bug-free, and production-ready with every new update. This guide dives deep into the essentials of automation testing and CI/CD in Flutter, covering their importance, setup, best practices, challenges, and future possibilities.

1. The Fundamentals of Automated Testing

What is Automated Testing?
Automated testing is the process of running tests on your application’s codebase using scripts, which allows you to verify application functionality, detect bugs, and check for regression. In Flutter, automated testing is divided into three main types:

  • Unit Testing: Focuses on individual functions or methods, validating their logic and performance.
  • Widget Testing: Tests individual UI components, such as buttons and widgets, for behavior and appearance.
  • Integration Testing: Verifies end-to-end scenarios across the app to confirm various modules work well together.

Benefits of Automated Testing in Flutter:
For Flutter apps, automated testing speeds up development, improves code quality, and reduces manual verification. Automated testing enhances developer productivity by allowing early detection of issues, efficient code verification, and consistent performance across devices.

Why CI/CD Matters in Automated Testing:
CI/CD adds immense value to automated testing by integrating test runs into every code change, automating repetitive tasks, and enabling a continuous feedback loop. When automated testing is combined with CI/CD, teams can:

  • Detect and address issues early in the development lifecycle
  • Improve code quality with consistent testing and feedback
  • Streamline the deployment process for faster, more reliable updates

2. CI/CD in Flutter: Accelerating Development with Automation

Understanding CI/CD Concepts
CI/CD, or Continuous Integration and Continuous Delivery/Deployment, is a set of practices that automate code integration, testing, and deployment. Here’s a breakdown:

  • Continuous Integration (CI): Automatically integrates code changes into a shared repository, triggering automated tests and ensuring the codebase remains functional.
  • Continuous Delivery (CD): Extends CI by automating the deployment of tested code changes to production, streamlining the release process.

The Role of CI/CD in Flutter Development

Flutter’s rapid development process requires a robust CI/CD system to manage code changes, run tests automatically, and deploy features quickly. For Flutter applications, CI/CD helps maintain code quality, minimizes manual testing, and reduces deployment risks.

1. Build and Test Automation

Automating build and test processes is critical for any Flutter project aiming for rapid and consistent development. When manual intervention is minimized, code quality improves, and potential errors are caught early, leading to a more efficient workflow.

  • Automated Builds: With CI/CD, builds are automatically compiled, significantly reducing errors that stem from manual handling.
  • Seamless Testing: CI/CD pipelines allow for various automated testing, including integration and UI tests, that detect issues early in the process.

Automating these steps ensures quality checks at each stage, helping developers confidently deploy reliable code and reducing the likelihood of regressions.

2. Proactive Bug Identification

Identifying bugs early can prevent costly fixes later. CI/CD pipelines allow for continuous code analysis, enabling developers to catch bugs as they commit code changes to a shared repository.

  • Automated Code Analysis: By scanning the codebase for syntax errors and potential security issues, CI/CD pipelines ensure only quality code moves forward.
  • Immediate Feedback Loops: Real-time feedback on code changes enables faster decision-making, reducing time spent troubleshooting later.

This proactive approach to bug detection results in faster, more robust app development, paving the way for a more stable and secure application.

3. Accelerated Delivery of Features

CI/CD pipelines not only help in faster app releases but also streamline the rollout of new features. By reducing the dependency on manual processes, CI/CD makes it possible to deliver incremental updates rapidly, keeping users engaged.

  • Iterative Releases: Small, continuous releases improve agility, enabling developers to introduce and test new features regularly.
  • Rapid Feedback: Automated testing helps gather quick feedback on new features, allowing for swift adjustments.

With CI/CD, time-to-market decreases, providing a competitive edge in the app market while maintaining high development standards.

4. Cost Optimization

CI/CD significantly cuts down on operational costs by minimizing manual processes and optimizing resource allocation. By reducing errors and downtime, teams can focus more on development and less on firefighting issues.

  • Reduced Manual Effort: Automation reduces the need for extensive human resources and leads to consistent results.
  • Optimized Resource Allocation: Effective resource utilization across build, test, and deployment stages maximizes productivity while controlling infrastructure costs.

This results in fewer maintenance expenses, making CI/CD an ideal choice for businesses looking to scale Flutter applications without inflated budgets.

5. Enhanced Feedback and Iteration

CI/CD pipelines promote a continuous feedback loop, which is essential for iterating on user feedback, optimizing the app, and improving user experience. In Flutter development, where user-centric design is crucial, this rapid feedback enables constant improvements.

  • Real-Time Analytics: Testing and analytics help gather insights into user pain points, preferences, and app performance.
  • Frequent Updates: With automated feedback, developers can push updates swiftly, making it easy to refine existing features and implement new ones based on user demands.

3. Achieving Automated Testing in Flutter with CI/CD

Implementing automated testing in Flutter’s CI/CD pipeline is essential for maintaining code quality and ensuring a reliable user experience. This section will guide you through setting up CI/CD pipelines for unit, widget, and integration testing in Flutter.

Configuring CI/CD for Flutter Testing

  1. Unit Testing with CI/CD:
    Unit tests validate the behavior of individual functions or methods to ensure they produce the expected results. Automating these tests as part of your CI pipeline helps catch regressions early.

Example Code:

// add.dart
int add(int a, int b) => a + b;

Unit Test:

// test/utils/calculator_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/utils/calculator.dart';

void main() {
group('Calculator Tests', () {
test('Addition test', () {
final calc = Calculator();
expect(calc.add(2, 3), 5);
});

test('Subtraction test', () {
final calc = Calculator();
expect(calc.subtract(5, 2), 3);
});
});
}

CI Configuration Steps for Unit Testing:

  • Ensure your CI pipeline runs the flutter test command to execute unit tests automatically.
  • Set up code coverage reporting for better insights.

2. Widget Testing with CI/CD

Widget tests ensure UI components behave as expected when rendered and interacted with. This type of testing helps verify that widgets display correctly and react as designed.

Example Code:

// example_widget.dart
import 'package:flutter/material.dart';

class ExampleWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Text('Hello, Flutter!');
}
}

Widget Test:

// test/widget_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'example_widget.dart';

void main() {
testWidgets('Displays Hello, Flutter text', (WidgetTester tester) async {
await tester.pumpWidget(ExampleWidget());
expect(find.text('Hello, Flutter!'), findsOneWidget);
});
}

CI Configuration Tips for Widget Testing:

  • Run widget tests as part of your build pipeline to validate UI components with each code change.

3. Integration Testing and End-to-End Automation

Integration tests ensure that an app functions as a whole, covering UI interactions, data flow, and backend calls. They are essential for detecting complex issues that unit and widget tests might not catch.

Example Integration Test:

// integration_test/app_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:my_app/main.dart';

void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();

testWidgets('Navigate to detail page test', (WidgetTester tester) async {
await tester.pumpWidget(MyApp());

// Tap the navigation button
await tester.tap(find.byKey(Key('navigateButton')));
await tester.pumpAndSettle();

// Check if the detail page is displayed
expect(find.text('Detail Page'), findsOneWidget);
});
}

Running Integration Tests on Firebase Test Lab:
Firebase Test Lab allows you to run integration tests across multiple devices, providing valuable insights into real-world app performance.

Choosing the Right CI/CD Tools for Flutter

Selecting the right CI/CD tool depends on your project’s specific needs and existing infrastructure. Here are some popular options:

  • GitHub Actions: Ideal for seamless GitHub integration and YAML-based workflows.
  • GitLab CI: Known for advanced CI/CD features, including built-in security tools.
  • Bitrise: A mobile-centric platform that simplifies CI/CD for mobile apps.
  • Codemagic: Designed specifically for Flutter, with optimized build and test configurations.

Each tool has unique features; the choice depends on your team’s needs and existing workflows.

Why GitHub Actions?

  • Seamless integration with GitHub repositories.
  • Simple configuration with YAML files.
  • Extensive community support and prebuilt actions.

Setting Up CI/CD for Flutter with GitHub Actions:

Step 1: Create a Workflow File

 Create a .github/workflows/flutter_ci.yml file in your project directory.

name: Flutter CI/CD

on:
push:
branches:
- main
pull_request:
branches:
- main

jobs:
build:
runs-on: ubuntu-latest

steps:
# Step 1: Check out the code
- name: Check out code
uses: actions/checkout@v3
# Explanation: This step uses the `actions/checkout` action to clone the repository and check out the code on the runner. It ensures the workflow has access to the project's code for subsequent steps.

# Step 2: Set up Flutter environment
- name: Set up Flutter
uses: subosito/flutter-action@v2
with:
flutter-version: 'stable'
# Explanation: This step sets up Flutter on the runner using the `subosito/flutter-action`. The `flutter-version: 'stable'` ensures the latest stable version of Flutter is installed, keeping your workflow environment consistent.

# Step 3: Install Flutter dependencies
- name: Install dependencies
run: flutter pub get
# Explanation: Runs the `flutter pub get` command to download and install all the dependencies specified in the `pubspec.yaml` file.

# Step 4: Run Flutter tests and check coverage
- name: Run tests
run: flutter test --coverage
# Explanation: Runs the Flutter unit tests and collects code coverage data. The `--coverage` flag generates a coverage report in the `coverage/lcov.info` file.

# Step 5: Generate code coverage report
- name: Generate code coverage report
run: flutter pub global run lcov_to_html coverage/lcov.info -o coverage/html
# Explanation: Converts the `lcov.info` coverage report into an HTML format using the `lcov_to_html` package and outputs it to `coverage/html`. This step helps create a human-readable version of the code coverage report for review.

# Step 6: Upload test results as artifacts
- name: Upload test results
uses: actions/upload-artifact@v3
with:
name: coverage-report
path: coverage/html/
# Explanation: This step uploads the generated HTML code coverage report as an artifact using the `actions/upload-artifact` action. The `name: coverage-report` gives a name to the artifact, and `path: coverage/html/` specifies the location of the report.

Explanation:

  • runs-on: ubuntu-latest: Specifies the environment for job execution.
  • uses: subosito/flutter-action@v2: Sets up Flutter for the pipeline.
  • flutter test --coverage: Runs tests and generates a code coverage report.

Step 2: Cache Dependencies

Reduces time by caching dependencies across builds.

- name: Cache Pub packages
uses: actions/cache@v3
with:
path: ${{ runner.cacheDir }}/pub-cache
key: ${{ runner.os }}-pub-cache-${{ hashFiles('pubspec.yaml') }}

Step 3: Linting and Code Quality

Ensures code follows best practices and coding standards.

- name: Run Dart analysis
run: flutter analyze
https://docs.flutter.dev/deployment/cd

 Deploying Your Flutter App with CI/CD(Windows)

Web Deployment Using Firebase Hosting

  1. Install Firebase CLI globally:
npm install -g firebase-tools

2.Login and configure Firebase:

firebase login
firebase init

GitHub Actions Deployment Script:

deploy:
runs-on: windows-latest
needs: build

steps:
# Step 1: Check out the repository code
- name: Checkout code
uses: actions/checkout@v3
# Explanation: This step uses the `actions/checkout` action to clone the repository and check out the code on the runner. It ensures the workflow has access to the codebase for further steps.

# Step 2: Set up Node.js
- name: Set up Node.js for Windows
uses: actions/setup-node@v3
with:
node-version: '16'
# Explanation: This step sets up Node.js (version 16) on the Windows runner using the `actions/setup-node` action. This is necessary because the Firebase CLI requires Node.js to run.

# Step 3: Deploy to Firebase Hosting
- name: Deploy to Firebase Hosting
run: firebase deploy --only hosting
env:
FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}
# Explanation:
# - `run: firebase deploy --only hosting`: Runs the Firebase CLI command to deploy the project to Firebase Hosting. The `--only hosting` flag ensures that only the hosting portion of the project is deployed, preventing accidental deployment of other Firebase services.
# - `env: FIREBASE_TOKEN`: The `FIREBASE_TOKEN` environment variable is used for authentication. This token should be stored as a secret in your GitHub repository (`Settings > Secrets and Variables > Actions > New repository secret`). It allows the GitHub Action to authenticate and deploy to Firebase without requiring user input.

Explanation:

  • FIREBASE_TOKEN: Securely stored in GitHub Secrets for authentication.
https://firebase.google.com/docs/hosting/frameworks/flutter

Mobile Deployment Example Using Fastlane:

Deploy your Flutter app to the Play Store and App Store with Fastlane:

Example Script:

- name: Deploy to Play Store
run: fastlane supply --json_key ${{ secrets.GOOGLE_PLAY_JSON_KEY }}

- name: Deploy to App Store
run: fastlane pilot upload --api_key_path ${{ secrets.APPLE_API_KEY_PATH }}

Explanation:

  • Fastlane handles complex deployment scripts for both iOS and Android, simplifying the process.
https://docs.fastlane.tools

4. Overcoming Challenges in Flutter CI/CD Automation

While CI/CD provides substantial benefits, setting it up for Flutter comes with challenges. Here are a few common issues and solutions:

  • Device Compatibility: Test your app on emulators and real devices to ensure it works across Android and iOS environments.
  • Caching Dependencies: Cache frequently used packages to improve CI/CD performance.
  • Managing Sensitive Data: Securely store and manage API keys and environment variables using secret management tools.

5. Future Trends and Opportunities in CI/CD for Flutter

AI-Enhanced Testing: Tools are increasingly using AI to detect and fix flaky tests, offering predictions on test failure rates based on historical data.

Automated Test Generation: Tools like Applitools use visual AI testing to automatically generate UI tests based on screenshots, which could be adapted for Flutter UI testing.

Predictive Analytics: Predictive analytics will soon allow developers to analyze the CI/CD pipeline data to optimize testing frequency and detect bottlenecks proactively.


6. Conclusion

This guide highlights the steps, tools, and best practices necessary to implement automated testing and CI/CD in Flutter. Whether you’re just beginning or optimizing an existing pipeline, mastering these concepts allows developers to produce high-quality, reliable applications that can quickly adapt to user needs and marketplace changes.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


7. Reference:

Testing Flutter apps
Learn more about the different types of testing and how to write them.docs.flutter.dev

Continuous delivery with Flutter
How to automate continuous building and releasing of your Flutter app.docs.flutter.dev

fastlane
Documentation for fastlane tools, the easiest way to automate building and releasing your iOS and Android appsdocs.fastlane.tools

Integrate Flutter Web | Firebase Hosting
With the Firebase framework-aware CLI, you can deploy your Flutter application to Firebase. Note: Framework-aware…firebase.google.com


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Security Best Practices for Flutter Apps

0

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.

Table of Contents

Introduction

Why do we need it?

How we can secure the application?

Limitations

Conclusion

References


Introduction

When creating an application it is essential not to just write the code but to secure it as well. Securing your app includes maintaining privacy, and preventing breaches that could damage and harm your brand. For developers using Flutter, a popular cross-platform framework, ensuring security may feel challenging, but with careful planning and the right tools, it can be effectively managed.

In this article we’ll discuss that why do we need to ensure the safety of your application with the possible practices which can prevent your application from any kind of breach and attack.


Why do we need it?

We need security best practices in Flutter apps because mobile apps often handle sensitive and private user information, making them a target for cyber attacks as well as security vulnerabilities. Failing to secure an application can lead to serious consequences, both for the users and the app developers or companies behind it. Here’s a breakdown of the reasons why security is essential:

  1. Protect Sensitive Data: Apps handle personal information (e.g., names, emails, financial data) that, if exposed, can be exploited for identity theft, fraud, or unauthorized access to other accounts or services. Encryption and secure data handling prevent such leaks.
  2. Build User Trust: Users trust apps to keep their information safe. If an app is breached or mishandles data, it erodes user trust, damages brand reputation, and can result in losing customers.
  3. Comply with Regulations: Many regions have strict data privacy laws (e.g., GDPR in the EU, CCPA in California) that require apps to secure user data properly. Non-compliance can lead to hefty fines and legal issues for the app’s developers or owners.
  4. Prevent Unauthorized Access: Secure authentication ensures that only authorized users access the app. This is critical for protecting data and resources, especially in apps that deal with financial transactions or private information.
  5. Avoid Financial and Reputational Damage: Security breaches can lead to direct financial losses and a negative public image. For businesses, this can mean compensating affected users and spending significant resources to repair security gaps and reputation damage.

Security best practices protect both users and developers by ensuring data confidentiality, integrity, and availability. They help maintain trust, comply with legal standards, and mitigate risks that could result in severe damage if left unaddressed.


How we can secure the application?

There are many techniques and practices available using which we can make the application more secure to save it from attacks and data breach. Here are some common and useful techniques which are easy to implement and follow.

1. Data Encryption: Safeguarding Data at Rest and in Transit

Encryption is one of the core practices for protecting sensitive information in any application. In a Flutter app, this means ensuring that data is encrypted both while it’s stored (data at rest) and while it’s sent across the internet (data in transit).

  • Data-at-Rest Encryption: Sensitive data stored on a user’s device, like passwords or tokens, should be encrypted to protect against unauthorized access. The flutter_secure_storage package is an excellent tool for this, as it uses platform-specific secure storage (Keychain for iOS and Keystore for Android). This package allows you to store key-value pairs securely, and it automatically encrypts data. Avoid storing sensitive data in local preferences or plain text files, as these methods are easily accessible if the device is compromised.

Example: Storing Data Securely

class AuthStorage {
final FlutterSecureStorage _storage = FlutterSecureStorage();
// Save the auth token
Future<void> saveAuthToken(String token) async {
await _storage.write(key: 'authToken', value: token);
}
// Retrieve the auth token
Future<String?> getAuthToken() async {
return await _storage.read(key: 'authToken');
}
}
  • Data-in-Transit Encryption: When your app communicates with a server, the data being sent should be encrypted with HTTPS. HTTPS (Hypertext Transfer Protocol Secure) secures data using SSL/TLS protocols, which help prevent interception by unauthorized parties. When using HTTP libraries like dio or http, ensure you configure them to use HTTPS endpoints. Also, consider adding SSL pinning to protect against man-in-the-middle attacks by verifying the server’s SSL certificate. This process ensures that the app only trusts your server’s specific certificate.

Example: HTTPS Request Using Dio

class ApiService { 
final Dio _dio = Dio();
ApiService() {
_dio.options.baseUrl = 'https://your-secure-api.com';
// Optional: Set any default headers, timeouts, etc. _dio.options.connectTimeout = Duration(seconds: 10); // Set a connection timeout
_dio.options.receiveTimeout = Duration(seconds: 10); // Set a receive timeout
}
Future<Response?> getRequest(String endpoint, {Map<String, dynamic>? queryParams}) async {
try {
final response = await _dio.get(endpoint, queryParameters: queryParams); return response;
}
on DioError catch (e) {
// Handle Dio-specific errors here
if (e.response != null) {
print('Error: ${e.response?.statusCode} - ${e.response?.data}');
}
else {
print('Error: ${e.message}');
} return null; // Return null or handle error as needed
}
catch (e) {
print('Unexpected error: $e'); return null; } } }

2. Secure User Authentication: Ensuring Only Authorized Access

Proper authentication mechanisms are essential to keep unauthorized users out of your app. Flutter provides several tools to implement secure user authentication, including support for OAuth, biometrics, and secure token storage.

  • OAuth2 and OpenID Connect: OAuth2 and OpenID Connect are popular protocols for user authentication. By using identity providers like Google, Facebook, or custom solutions, you can enable secure login mechanisms. Firebase Authentication is a straightforward way to integrate OAuth providers with Flutter. For custom implementations, use the oauth2 package for token handling and secure user sessions.

Example: Using Firebase Authentication

class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn _googleSignIn = GoogleSignIn();
// Sign in with Google
Future<User?> signInWithGoogle() async {
try {
// Trigger the Google Sign-In flow
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
if (googleUser == null) {
print("Google sign-in aborted by user.");
return null;
}
// Obtain the authentication details from the request
final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
// Create a new credential
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
// Sign in to Firebase with the Google user credential
final UserCredential userCredential = await _auth.signInWithCredential(credential);
print("User signed in: ${userCredential.user?.displayName}");
return userCredential.user;
} on FirebaseAuthException catch (e) {
print("Firebase Auth Error: ${e.message}");
return null;
} catch (e) {
print("Unexpected error during Google sign-in: $e");
return null;
}
}
}

Biometric Authentication: Adding biometric authentication (fingerprint, Face ID) provides users with an extra layer of security. The local_auth package in Flutter allows you to implement biometrics easily. Biometric checks are particularly useful for apps that handle highly sensitive data, such as financial or health applications, as they require users to prove their identity before gaining access to critical information.

Example: Implementing Biometric Authentication

final LocalAuthentication auth = LocalAuthentication();
Future<bool> authenticateUser() async {
try {
bool isAuthenticated = await auth.authenticate(
localizedReason: 'Please authenticate to access secure data',
options: const AuthenticationOptions(
useErrorDialogs: true,
stickyAuth: true,
),
);
return isAuthenticated;
} catch (e) {
print('Authentication error: $e');
return false;
}
}
  • Token Management: Managing authentication tokens securely is essential. Avoid storing tokens in insecure storage like Shared Preferences or local files. Instead, use flutter_secure_storage for this purpose. Be mindful to refresh tokens regularly to keep sessions secure and prevent unauthorized access.

Example: Storing a Token

class TokenStorageService {
final FlutterSecureStorage _storage = FlutterSecureStorage();
// Save the JWT token
Future<void> saveAuthToken(String token) async {
await _storage.write(key: 'authToken', value: token);
}
// Retrieve the JWT token
Future<String?> getAuthToken() async {
return await _storage.read(key: 'authToken');
}
// Delete the JWT token
Future<void> deleteAuthToken() async {
await _storage.delete(key: 'authToken');
}
}

usage:

final tokenStorage = TokenStorageService();
// Save token
await tokenStorage.saveAuthToken('your_jwt_token');
// Retrieve token
String? token = await tokenStorage.getAuthToken();
print('Stored Token: $token');
// Delete token
await tokenStorage.deleteAuthToken();
print('Token deleted');

3. Protecting Against Common Vulnerabilities

Flutter apps, like any other apps, are vulnerable to a variety of attacks. Preventing common vulnerabilities requires proactive coding practices and a solid understanding of security risks.

  • Input Validation and Sanitization: Injection attacks, such as SQL injection or cross-site scripting (XSS), often exploit improper input handling. Always validate and sanitize user input to ensure it adheres to expected formats. In Dart, use regular expressions and type checking to enforce strict input rules, and avoid directly embedding user input into API requests or database queries.

Example: Basic Email Validation Using Regex

bool isValidEmail(String email) {
final emailRegex = RegExp(r'^[^@]+@[^@]+\.[^@]+');
return emailRegex.hasMatch(email);
}

usage:

String email = 'user@example.com';
if (!isValidEmail(email)) {
print('Invalid email format');
} else {
print('Valid email format');
}
  • Minimize Third-Party Dependencies: While Flutter has a rich ecosystem of third-party libraries, each dependency adds potential risks. Use only well-maintained, trusted packages, and be cautious with unverified packages. Regularly update dependencies to the latest versions, as updates often include security patches.
  • Code Obfuscation: Code obfuscation makes it more difficult for attackers to reverse-engineer your app. Flutter apps can be decompiled, so it’s essential to obfuscate your Dart code before deployment. On Android, you can enable ProGuard or R8 for obfuscation; on iOS, symbolicate your builds. This helps protect against attackers who may try to analyze or tamper with your code.

Example: Enable ProGuard for Release Builds

buildTypes {
release {
minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),'proguard-rules.pro'
}
}
  • App Permissions: Request only the permissions your app truly needs. Over-requesting permissions not only impacts user trust but also increases security risks. Avoid requesting sensitive permissions unless absolutely necessary, and follow the principle of least privilege by limiting what each part of the app can access.

Example: Request Camera Permission Conditionally

Future<void> requestCameraPermission() async {
if (await Permission.camera.request().isGranted) {
// Camera access granted
}
else {
print("Camera access denied"); } }

4. Securing APIs: Strong Protections for Backend Communications

If your app communicates with a backend server, securing API requests is paramount. Your APIs should be robustly secured to prevent unauthorized access, data leakage, and abuse.

  • JWT (JSON Web Token) for Stateless Authentication: JWTs allow stateless, secure authentication between your app and backend servers. Once a user is authenticated, your server issues a JWT, which is included in each API request to verify the user’s identity. Ensure JWTs are stored securely in flutter_secure_storage and expire periodically to maintain security. Avoid exposing sensitive data in JWT payloads, as they are easily decoded.

Example: Sending a JWT with Dio

class ApiService {
final Dio _dio = Dio();
final FlutterSecureStorage _storage = FlutterSecureStorage();
ApiService() {
_dio.options.baseUrl = 'https://your-secure-api.com';
// Optional: Set up any default configurations, like timeouts
_dio.options.connectTimeout = Duration(seconds: 10);
_dio.options.receiveTimeout = Duration(seconds: 10);
}
// Fetch data from a secure endpoint
Future<Response?> getData(String endpoint) async {
try {
// Retrieve the auth token
String? token = await _storage.read(key: 'authToken');
if (token != null) {
// Set the Authorization header
_dio.options.headers['Authorization'] = 'Bearer $token';
} else {
print("No auth token found.");
return null; // Handle as needed if no token is found
}
// Perform the GET request
final response = await _dio.get(endpoint);
return response;
} on DioError catch (e) {
// Handle Dio errors here
print("Dio error: ${e.message}");
return null;
} catch (e) {
// Handle any other errors here
print("Unexpected error: $e");
return null;
}
}
}
  • Rate Limiting and Throttling: Implement rate limiting to prevent abuse of your APIs. Rate limiting restricts the number of requests a user can make within a certain timeframe, which can help prevent brute force attacks and reduce server load.
  • CORS Configuration: Cross-Origin Resource Sharing (CORS) defines how resources on your backend are shared with different domains. Correctly configuring CORS settings in your API server ensures that only requests from allowed domains can access your resources, protecting your API from cross-origin requests that could be malicious.

5. Conducting Regular Security Testing

Security is an ongoing process that requires regular testing and assessments to uncover vulnerabilities before they become serious threats. Here are a few strategies to maintain your app’s security posture:

  • Static Code Analysis: Use static analysis tools to catch potential vulnerabilities during development. In Flutter, tools like dart_code_metrics can help you enforce best practices, identify code smells, and catch insecure code patterns. Static analysis is a low-cost method for catching issues early in the development cycle.
  • Penetration Testing: Penetration testing simulates attacks on your app to reveal weaknesses that attackers might exploit. While automated tests are valuable, manual pen testing by a skilled security professional can reveal hidden vulnerabilities and improve your overall security.
  • Regular Dependency Updates: Libraries and frameworks constantly evolve, and updates often include security patches. Regularly update Flutter SDK, Dart, and any dependencies to minimize vulnerabilities. Consider using tools like Dependabot or Renovate to automate dependency updates.

6. Manage Dependencies Wisely

  • Building your app’s foundation requires careful selection and vigilant maintenance of dependencies.
  • Avoid the temptation to fixate on specific versions, as this can expose you to security risks.
  • Periodically review your dependencies and align them with the most recent offerings to bolster your app’s security.

7. Staying Informed and Adapting to New Threats

Security is a dynamic field with constantly evolving threats. Stay informed by following reputable security blogs, reading Flutter security documentation, and joining developer communities where security best practices are discussed. Participating in ongoing education and remaining vigilant about emerging threats can help you protect your app and its users.


Limitations

Despite implementing best practices, there are some limitations and challenges in securing Flutter apps. Here are a few notable ones:

1. Platform-Specific Security Limitations

  • OS-Level Differences: Flutter apps run on multiple platforms (Android, iOS, Web, etc.), each with its own security implementations and limitations. For example, iOS has tighter sandboxing and Keychain support, while Android’s security varies based on OS versions and device manufacturers.
  • Limited Control over Native Code: Although Flutter is cross-platform, it doesn’t fully control native code execution. For more granular security controls, developers might need to write native code, which increases complexity and potential vulnerabilities.

2. Obfuscation and Reverse Engineering

  • Limited Protection from Reverse Engineering: Obfuscation and code minification make reverse engineering harder but not impossible. Skilled attackers can still decompile and analyze obfuscated code with reverse engineering tools.
  • Flutter’s Obfuscation Limitations: Flutter’s obfuscation options are not as advanced as native app development options. Obfuscation can also complicate debugging and error tracking, making it harder to maintain the app.

3. Dependency Management and Package Security

  • Risk of Vulnerable Packages: Flutter relies on many third-party packages, which could contain vulnerabilities if not maintained properly. It’s not always feasible to audit each dependency, and vulnerabilities may arise after a package is included.
  • Delayed Updates and Bug Fixes: Open-source packages can sometimes delay updates or fixes for vulnerabilities, potentially leaving the app exposed if relying on outdated packages.

4. Limited Access to Advanced Security Features

  • Missing Advanced Security Plugins: Flutter might not have plugins for all advanced security features available in native environments (e.g., some biometric authentication options or hardware-backed security).
  • Hardware Security Modules (HSMs): Access to hardware-backed security features like HSMs (for example, on Android’s Trusted Execution Environment) is limited or challenging in Flutter compared to native development.

5. Network Security Constraints

  • Challenges with Certificate Pinning: Implementing and maintaining certificate pinning is complex and may lead to connectivity issues if not managed carefully (e.g., in cases where certificates rotate).
  • Exposure of API Endpoints: Mobile apps often expose endpoints in ways that are more susceptible to inspection and reverse engineering compared to server-only apps, increasing the risk of API abuse.

6. Client-Side Vulnerabilities

  • Client-Side Data Storage Risks: Even with encryption, any data stored on a mobile device is vulnerable if the device is rooted or jailbroken. Rooted/jailbroken devices compromise the security of any locally stored data, as well as secure storage mechanisms.
  • Limitations of Local Storage Encryption: While encryption protects data, if keys are managed on the device (e.g., in local storage or memory), attackers can sometimes access or extract these keys.

7. Authentication Challenges

  • OAuth and Token Storage Vulnerabilities: Storing access tokens on the client device always carries some risk, as tokens can potentially be accessed through reverse engineering or malicious software.
  • Challenges with Biometric Authentication: While biometric authentication adds security, it can also create accessibility issues or dependency on device-specific hardware. Implementing fallback mechanisms for unsupported devices adds complexity.

8. Security Testing Limitations

  • Testing Across Platforms: Flutter’s cross-platform nature makes it challenging to ensure security consistency across all platforms and devices.
  • Limited Automated Security Testing Tools: Most mobile security testing tools are designed for native applications, making automated security assessments for Flutter apps less comprehensive.

9. Backend Dependency and Network Exposure

  • Backend Security Reliance: While a secure backend is essential, Flutter apps often rely on a backend that could introduce security risks beyond the developer’s control. The backend’s security posture is critical, and vulnerabilities there can still affect the app’s security.
  • Network Attack Surface: Mobile apps are inherently more exposed to network-based attacks due to their reliance on APIs and web services. Techniques like rate limiting help but don’t fully mitigate this exposure.

Conclusion

Developing secure Flutter applications requires careful planning and proactive measures to guard against a wide range of potential security threats. By implementing data encryption, secure authentication, API protection, and regular testing, you can significantly improve your app’s security. Remember that security is an ongoing commitment: keep learning, stay informed, and adapt your strategies as technology and threats evolve. By making security a top priority, you’ll not only protect your users’ data but also build trust and reliability into your brand.


❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


References:

Secure Your Flutter App: Top Strategies for Security Concerns
Learn the most effective strategies to enhance the security of your Flutter app. Discover key measures and best…www.valuecoders.com

Security
An overview of the Flutter’s team philosophy and processes for security.docs.flutter.dev

Data Security in Flutter: Best Practices for 2024
Discover essential strategies and best practices for ensuring robust data security in Flutter applications in 2023.www.itpathsolutions.com


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Flutter and Blockchain: A Developer’s Comprehensive Guide

0

In this article, we will explore the Flutter and Blockchain: A Developer’s Comprehensive Guide. We see how to execute a demo program. We will tell you the best way how to use your Flutter applications.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table of Contents

Introduction

Understanding Blockchain Technology

Types Of Blockchain

Why Integrate Blockchain with Flutter?

Blockchain Fundamentals for Beginners:

Popular Blockchain Platforms for Flutter Integration

Smart Contract Interaction Tools

Steps for Integrating Blockchain in Flutter

Limitations and Challenges

Future Scope of Blockchain in Flutter

Conclusion

References


Introduction

The rapid advancements in technology have introduced new possibilities, one of the most significant being blockchain. This revolutionary technology ensures data integrity, security, and decentralization. But what does that mean for mobile app development? As a developer looking to expand your expertise in modern technologies, the combination of Flutter and blockchain provides an exciting opportunity to create secure, transparent, and decentralized applications (dApps). This guide explores blockchain’s foundational concepts, its popular platforms like Ethereum, Solana, and Polygon, their specific strengths, and detailed steps to integrate blockchain with Flutter, including tools and best practices Even if you’re new to blockchain or Flutter, this guide will provide you with a strong foundational understanding.


Understanding Blockchain Technology

Blockchain is a decentralized and distributed ledger technology that records transactions across multiple computers to ensure data integrity and security. Unlike traditional centralized databases, blockchain is managed by a network of nodes, making it more secure and less prone to tampering.

Core Principles for Developers:

  • Consensus Mechanisms: Determines how blocks are validated (e.g., Proof of Work (PoW), Proof of Stake (PoS), and newer mechanisms like Proof of History (PoH) in Solana).
  • Smart Contracts: Self-executing contracts where the terms are embedded in code. These are central to blockchain-based apps, automating workflows without intermediaries.
  • Nodes and Decentralization: The network’s participants (nodes) that validate and store the blockchain data. Full nodes maintain an entire copy of the blockchain, which supports the decentralized nature of the network.

The major benefits of blockchain include: 

  • Decentralization: Data is distributed across all nodes in the network, eliminating the need for a central authority.
  • Immutability: Once data is added to the blockchain, it is virtually impossible to modify or delete.
  • Transparency: All transactions are publicly visible and can be verified by participants. Ensuring no hidden changes can be made
  • Security: Cryptographic algorithms ensure that data on the blockchain is secure and reliable.

 dApps (decentralized applications) use blockchain as their backbone to ensure data isn’t stored on a centralized server but distributed across multiple nodes. This enhances security and trust among users.


 Types of Blockchains:

Understanding the different types of blockchains is essential for choosing the right platform for your Flutter app. Below are the main types of blockchains:

Public Blockchains

  • Definition: Open networks where anyone can participate, validate transactions, and access the data.(e.g., Bitcoin, Ethereum).
  • Pros: High transparency and decentralization.
  • Cons: Slower transaction speeds and higher energy consumption.

Private Blockchains

  • Definition: Restricted networks controlled by a single organization.
  • Pros: Higher transaction speeds and better control over data.
  • Cons: Reduced transparency and decentralization.

Consortium Blockchains

  • Definition: Semi-decentralized networks managed by a group of organizations.
  • Pros: Faster and more scalable than public blockchains.
  • Cons: Limited decentralization.

Hybrid Blockchains

  • Definition: A combination of public and private blockchains, leveraging the best of both worlds.
  • Pros: Flexible, efficient, and partially transparent.
  • Cons: Complex architecture and maintenance.

Why Integrate Blockchain with Flutter?

Flutter, Google’s open-source framework, allows developers to create high-performance cross-platform apps using a single codebase. Integrating blockchain with Flutter can bring about several benefits, making apps more secure, transparent, and capable of handling decentralized functionalities.

Benefits of Using Blockchain with Flutter

  • Enhanced Security: Blockchain’s immutable and decentralized nature ensures that user data and transactions are secure.
  • Decentralized Applications (dApps): Developers can create dApps with no central authority, which aligns with modern user preferences for privacy and control.
  • Transparency and Trust: Blockchain’s public ledger offers full transparency, building user trust.
  • Smart Contracts: Using platforms like Ethereum, developers can automate processes with self-executing contracts, reducing the need for intermediaries.

Combining Flutter’s capabilities with blockchain technology enables developers to build applications that are visually rich and backed by the power of decentralized networks.


Blockchain Fundamentals for Beginners:

Before diving into the implementation, let’s break down a few key blockchain concepts:

Smart Contracts: Self-executing contracts with terms directly embedded in code. They run on blockchain networks like Ethereum.

Ether (ETH): The native cryptocurrency of Ethereum, often used as a medium for transactions and smart contract operations.

Web3: A library or standard to interact with the blockchain. It’s essential for communicating between your Flutter app and the blockchain.


Popular Blockchain Platforms for Flutter Integration

1. Ethereum

Overview: Ethereum is a leading blockchain platform known for its smart contract capabilities. It was introduced in 2015 by Vitalik Buterin to expand blockchain applications beyond cryptocurrency.

Key Features:

  • Smart Contracts: Ethereum was the first blockchain to support programmable smart contracts, enabling developers to build decentralized applications.
  • EVM (Ethereum Virtual Machine): A runtime environment that executes smart contracts.
  • Active Developer Community: Ethereum has one of the largest and most active communities, ensuring continuous development and support.

Use Cases:

  • dApps: Decentralized finance (DeFi) apps, NFT marketplaces, gaming dApps.
  • Smart Contracts: Automating agreements without intermediaries.

Integration Steps:

  1. Install Dependencies:
dependencies:
web3dart: ^2.3.4
http: ^0.14.0

2. Connect to an Ethereum Node: Use Infura or Alchemy to access the Ethereum blockchain via their RPC endpoints.

import 'package:web3dart/web3dart.dart';
import 'package:http/http.dart';

final String rpcUrl = "https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID";
final Web3Client client = Web3Client(rpcUrl, Client());

3. Interact with Smart Contracts: Load the ABI (Application Binary Interface) and call contract functions.

Future<void> callContract(String contractAddress, String abiJson) async {
final contract = DeployedContract(
ContractAbi.fromJson(abiJson, 'MyContract'),
EthereumAddress.fromHex(contractAddress),
);
final function = contract.function('myFunction');
final result = await client.call(
contract: contract,
function: function,
params: [],
);
print('Result: $result');
}

Limitations:

  • Scalability Issues: Ethereum can handle only about 15 transactions per second (TPS), leading to slower transaction times during high traffic.
  • High Gas Fees: Transactions on Ethereum can be expensive, especially during peak times.

Future Enhancements:

  • Ethereum 2.0: A major upgrade that aims to improve scalability, security, and sustainability by transitioning from Proof of Work (PoW) to Proof of Stake (PoS).

2. Solana

Overview: Solana is a high-performance blockchain known for its fast and low-cost transactions. It was created in 2017 by Anatoly Yakovenko to address the scalability issues of Ethereum.

Key Features:

  • High Throughput: Solana can handle up to 65,000 TPS, making it one of the fastest blockchain platforms.
  • Low Transaction Fees: Transactions on Solana cost only a fraction of a cent.
  • Proof of History (PoH): A unique consensus mechanism that timestamps transactions, improving efficiency.

Use Cases:

  • DeFi Platforms: Solana is popular for building decentralized exchanges and other financial dApps.
  • NFTs: Many NFT projects are built on Solana due to its low fees and high speed.

Integration Steps:

  1. Use Solana RPC:
final Uri solanaRpcUri = Uri.parse("https://api.mainnet-beta.solana.com");
final response = await http.post(solanaRpcUri, body: jsonEncode({
"jsonrpc": "2.0",
"id": 1,
"method": "getBalance",
"params": ["YourWalletAddress"]
}));

2. Developing Smart Contracts: Write Solana programs in Rust and deploy them via tools like solana-cli. Developers can use libraries like Anchor for streamlined program development.

Limitations:

  • Centralization Concerns: Solana’s network is less decentralized compared to Ethereum.
  • Occasional Outages: The network has experienced downtime, affecting its reliability.

Future Enhancements:

  • Improved Decentralization: Solana is working towards decentralizing its network further.
  • Ecosystem Growth: As the ecosystem grows, more dApps and projects will be attracted to Solana due to its performance benefits.

3. Polygon (Matic)

Overview: Polygon is a Layer 2 scaling solution for Ethereum, providing faster and cheaper transactions while benefiting from Ethereum’s security and ecosystem.

Key Features:

  • Layer 2 Solution: Built on top of Ethereum to solve its scalability issues.
  • Interoperability: Polygon supports seamless interaction with Ethereum-based dApps.
  • Lower Gas Fees: Significantly reduces transaction costs compared to Ethereum.

Use Cases:

  • DeFi: Many DeFi platforms choose Polygon for its low fees and Ethereum compatibility.
  • Gaming: Blockchain-based games often use Polygon to enhance user experience with quick transactions.

Integration Steps:

  1. Configure Web3dart for Polygon: Use the same Ethereum configuration, but point to Polygon RPC endpoints.
final String rpcUrl = "https://polygon-rpc.com";
final Web3Client client = Web3Client(rpcUrl, Client());

2. Deploy and Use Smart Contracts: Contracts deployed on Ethereum can often be deployed with minimal changes on Polygon due to EVM compatibility.

Limitations:

  • Dependency on Ethereum: While Polygon is more efficient, it still relies on the Ethereum network for its security.
  • Competition: As more Layer 2 solutions emerge, Polygon must continuously innovate to remain competitive.

Future Enhancements:

  • Expansion of dApp Ecosystem: With increased adoption, Polygon aims to support more complex dApps.
  • Improved Protocols: Continued enhancements to maintain a balance between speed, security, and decentralization.

Smart Contract Interaction Tools

Smart contracts are self-executing pieces of code stored on the blockchain that automatically enforce the terms of an agreement. To streamline the process of writing, testing, deploying, and managing these contracts, developers utilize specialized tools. Below is a deeper dive into some of the most widely used smart contract interaction tools:

1. Remix IDE

Overview: Remix IDE is an online Integrated Development Environment used primarily for writing, testing, and deploying smart contracts, typically on the Ethereum blockchain. It is beginner-friendly and requires no installation.

Features:

  • Online Accessibility: Works in the browser, allowing developers to write and deploy contracts quickly.
  • Solidity Support: Built specifically for Solidity, the language used for writing Ethereum smart contracts.
  • Built-in Debugging: Provides tools to debug and test smart contracts directly in the browser.
  • Plugins: Offers various plugins that can extend functionality, such as static analysis and code optimization tools.

How it Relates to Flutter:

  • Smart Contract Development: Use Remix IDE to develop and deploy smart contracts before interacting with them in a Flutter app.
  • Testing Contracts: Remix provides a testing environment where you can simulate transactions and interactions with your smart contracts.

Example Workflow:

  1. Write and deploy a smart contract using Remix IDE.
  2. Copy the deployed contract’s ABI (Application Binary Interface) and contract address.
  3. Integrate these details into a Flutter app using the web3dart library for interaction.

2. Truffle

Overview: Truffle is a development framework that helps manage smart contract development, testing, and deployment. It is widely used for Ethereum-based dApp projects and provides a robust environment for building smart contracts.

Features:

  • Project Management: Simplifies the management of multiple smart contract projects.
  • Automated Testing: Includes a testing framework that supports JavaScript and Solidity-based tests.
  • Migrations: Helps with deploying contracts to blockchain networks through a migration script.
  • Ganache: A tool included with Truffle for setting up a local blockchain for development and testing.

How it Relates to Flutter:

  • Backend Contract Management: Truffle is used to write, test, and deploy smart contracts to networks like Ethereum. After deployment, Flutter apps can communicate with these contracts via libraries like web3dart.
  • Local Blockchain Development: Developers can use Ganache (part of Truffle) to set up a local blockchain for testing smart contract interactions before integrating them into a Flutter app.

Example Workflow:

  1. Use Truffle to write and compile a smart contract in Solidity.
  2. Test the contract using Truffle’s built-in testing capabilities.
  3. Deploy the contract to an Ethereum network.
  4. Use the contract’s ABI and address to set up interaction from a Flutter app.

3. Hardhat

Overview: Hardhat is a modern development environment designed for Ethereum that emphasizes flexibility and advanced tooling. It’s known for its strong plugin ecosystem and enhanced debugging features.

Features:

  • Advanced Debugging: Offers a powerful console for tracking down errors in smart contracts.
  • Task Runner: Allows developers to automate recurring tasks like compiling, deploying, and testing.
  • Plugin Ecosystem: Integrates well with various plugins for added functionality, such as testing with Waffle and reporting with Etherscan.
  • Local Ethereum Network: Comes with Hardhat Network, which is useful for testing and development.

How it Relates to Flutter:

  • Contract Development: Hardhat is used to develop and deploy smart contracts, providing a backend that a Flutter app can interact with.
  • Comprehensive Testing: Hardhat’s strong testing capabilities ensure that contracts work as expected before being connected to a Flutter app.
  • Flexibility and Modern Tooling: Its robust environment makes it ideal for developers looking for advanced tooling in smart contract development.

Example Workflow:

  1. Use Hardhat to create and compile smart contracts.
  2. Deploy the contracts to a testnet or mainnet.
  3. Retrieve the ABI and contract address and integrate them into a Flutter app using web3dart or REST API calls.

Steps for Integrating Blockchain in Flutter

To build a secure and transparent dApp using Flutter, you’ll need to integrate blockchain services. This guide outlines the complete process, from setting up the Flutter project to connecting with a blockchain network and interacting with smart contracts.

1. Install Required Tools

  • Flutter SDK: Download and install Flutter.
  • Node.js: Required for blockchain development tools like Truffle or Hardhat.
  • MetaMask: A browser extension for managing and accessing Ethereum wallets.
  • Truffle or Hardhat: Development frameworks for deploying and testing smart contracts.

1. Set Up Your Flutter Project

First, create a new Flutter project. This will serve as the foundation for your blockchain-powered dApp.

Commands:

flutter create flutter_blockchain_app
cd flutter_blockchain_app

This sets up a basic Flutter project structure with all the necessary directories and files.

2. Add Required Dependencies

Integrate essential packages to enable blockchain functionality within your Flutter app. The web3dart package is a Dart library for interacting with Ethereum-based blockchains, and the http package is used for HTTP requests.

Update pubspec.yaml:

dependencies:
flutter:
sdk: flutter
web3dart: ^2.3.4
http: ^0.14.0

Install the Packages:

flutter pub get

Explanation:

  • web3dart: Used for blockchain interaction, such as sending transactions and reading data from smart contracts.
  • http: Facilitates communication with Ethereum nodes over HTTP.

3. Connect to a Blockchain Network

To interact with a blockchain, set up a connection using a blockchain client. For Ethereum, you can use a service like Infura or Alchemy to connect to the network.

Create blockchain_service.dart:

import 'package:web3dart/web3dart.dart';
import 'package:http/http.dart';

class BlockchainService {
final String rpcUrl = "https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID"; // Replace with your endpoint
late Web3Client _client;
BlockchainService() {
_client = Web3Client(rpcUrl, Client());
}
Future<EtherAmount> getBalance(String address) async {
final ethAddress = EthereumAddress.fromHex(address);
return await _client.getBalance(ethAddress);
}
Future<String> sendTransaction(/* Transaction details */) async {
// Implement transaction logic
// This can include building and signing the transaction
}
}

Explanation:

  • Web3Client: Connects to an Ethereum network node via HTTP or WebSocket.
  • rpcUrl: The RPC endpoint provided by Infura or Alchemy, allowing you to communicate with the Ethereum mainnet or testnet.
  • getBalance: Retrieves the Ether balance of a specified Ethereum address.

4. Deploy and Interact with Smart Contracts

To interact with smart contracts, write and deploy them using Solidity and integrate their ABI into your Flutter app.

Step-by-step process:

  1. Develop and Deploy a Smart Contract:
  • Write the contract in Solidity and deploy it using tools like Remix IDE, Truffle, or Hardhat.

2. Integrate the Contract’s ABI in Flutter:

  • Copy the ABI (Application Binary Interface) after deploying the contract and use it for interaction.

Example for calling a smart contract function:

Future<void> callFunctionFromContract(String contractAddress) async {
final abi = '[ABI_JSON]'; // Replace with your contract's ABI
final EthereumAddress address = EthereumAddress.fromHex(contractAddress);
final contract = DeployedContract(ContractAbi.fromJson(abi, 'MyContract'), address);
final function = contract.function('myFunction');

var result = await _client.call(
contract: contract,
function: function,
params: [],
);
print(result);
}

Explanation:

  • ContractAbi: Defines the interface of your contract.
  • DeployedContract: Represents a deployed contract instance.
  • call: Reads data from the contract using the specified function.

5. Handle Blockchain Transactions

Sending transactions involves signing them with a private key. For security, handle private keys with care, using secure storage or a wallet integration.

Example of Sending a Transaction:

Future<String> sendTransaction(String privateKey, String receiverAddress, BigInt amount) async {
EthPrivateKey credentials = EthPrivateKey.fromHex(privateKey);
EthereumAddress to = EthereumAddress.fromHex(receiverAddress);
String transactionHash = await _client.sendTransaction(
credentials,
Transaction(
to: to,
value: EtherAmount.fromUnitAndValue(EtherUnit.ether, amount),
),
chainId: 1, // Mainnet or change for testnets
);
return transactionHash;
}

Explanation:

  • EthPrivateKey: Signs the transaction.
  • Transaction: Specifies transaction details such as the recipient and value.
  • sendTransaction: Broadcasts the signed transaction to the network.

Limitations and Challenges

  • Complexity: Integrating blockchain requires understanding smart contracts, cryptographic principles, and blockchain mechanics.
  • Performance: While Flutter is optimized for high performance, blockchain calls can introduce latency.
  • Security Risks: Smart contracts are prone to vulnerabilities that can compromise app security.
  • Limited Mobile Libraries: Compared to web development, mobile libraries for blockchain can be less mature.

 Future Scope of Blockchain in Flutter

The integration of blockchain with mobile frameworks like Flutter is expected to evolve rapidly. Innovations like Ethereum 2.0, improved Layer 2 solutions, and new platforms like Polkadot and Avalanche are expanding the possibilities for developers. Future trends may include:

  • Mainstream Adoption of dApps: Enhanced user experience and lower transaction fees will drive more users to decentralized applications.
  • Interoperability Solutions: As blockchain ecosystems grow, the need for interoperability will spur the development of cross-chain solutions.
  • Enhanced Security Protocols: Improved cryptographic techniques will make blockchain interactions safer.
  • Developer Tools: More sophisticated SDKs and plugins will emerge, making blockchain integration easier for Flutter developers.

Conclusion

Integrating blockchain technology with Flutter opens up a world of opportunities for creating secure, transparent, and decentralized applications. Whether you choose Ethereum for its smart contracts, Solana for its high throughput, or Polygon for its scalability, understanding the benefits, limitations, and future trends is crucial for successful development. With the continuous evolution of blockchain technology and the Flutter framework, the future of dApp development looks promising and full of potential.


❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


Reference:

https://en.wikipedia.org/wiki/Blockchain

https://archive.trufflesuite.com/docs


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


DragTarget In Flutter

0

Flutter gives different Widgets through which we can construct any sort of UI. Yet, over a design, your application ought to be interactive with the goal that it tends to be handily gotten to by clients and users.

This blog will explore DragTarget In Flutter. We perceive how to execute a demo program. We will learn how to use the drag target in your flutter applications.

Table Of Contents::

Introduction

Constructor

Properties

Code Implement

Code File

Conclusion



Introduction:

DragTarget is a widget that gets information when a Draggable widget is dropped. When a draggable is delayed on top of a drag target, the drag target is found out if it will acknowledge the information the draggable is conveying.

Assuming that the user drops the draggable on top of the drag target, then, at that point, the drag target is approached to acknowledge the draggable’s information.

Demo Module ::

This demo video shows how to use the drag target in a flutter and shows how a drag target will work in your flutter applications. We will show a user drag a box to the drag target then, the target box color was changed. It will be shown on your devices.

Constructor:

To utilize DragTarget, you need to call the constructor underneath:

const DragTarget({
Key? key,
required this.builder,
this.onWillAccept,
this.onAccept,
this.onAcceptWithDetails,
this.onLeave,
this.onMove,
this.hitTestBehavior = HitTestBehavior.translucent,
})

Properties:

There are some properties of DragTarget are:

  • > builder: This property is called to build the items in this DragTarget. The builder can assemble various widgets relying upon what is being hauled into this drag target.
  • > BuildContext: This property is used for the Context of a Widget.
  • > candidateData: This property is used to contain the list of draggable data that will be accepted by DragTarget.
  • > rejectedData: This property is used to contain the list of Draggable data that will not be accepted by DragTarget.
  • > onWillAccept: This property is used to determine whether this widget is interested in receiving a given piece of data being dragged over this drag target. or we can say that Takes a function that provides the data of Draggable to use as a parameter and returns a bool based on whether Draggable will be accepted or not if onWillAccept returns true then onAccept is called.
  • > onAccept: This property is used to take a function that provides the data of Draggable which was accepted by DragTarget.
  • > onLeave: This property is used to onLeave is called when Draggable leaves the DragTarget and is not dropped into DragTarget.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called drag_box.dart inside the lib folder.

We will add the final Offset initPos, String label, and Color itemColor. The offset position is equal to the Offset. Also, we will add an initState method. In this method, we will add a position that is equal to the widget. initPos

import 'package:flutter/material.dart';

class DragBox extends StatefulWidget {
final Offset initPos;
final String label;
final Color itemColor;

const DragBox(
this.initPos,
this.label,
this.itemColor, {Key? key}
) : super(key: key);

@override
DragBoxState createState() => DragBoxState();
}

class DragBoxState extends State<DragBox> {
Offset position = const Offset(0.0, 0.0);

@override
void initState() {
super.initState();
position = widget.initPos;
}

@override
Widget build(BuildContext context) {
return Positioned(
left: position.dx,
top: position.dy,
child: Draggable(
data: widget.itemColor,
onDraggableCanceled: (velocity, offset) {
setState(() {
position = offset;
});
},
feedback: Container(
width: 120.0,
height: 120.0,
color: widget.itemColor.withOpacity(0.5),
child: Center(
child: Text(
widget.label,
style: const TextStyle(
color: Colors.white,
decoration: TextDecoration.none,
fontSize: 18.0,
),
),
),
),
child: Container(
width: 120.0,
height: 120.0,
color: widget.itemColor,
child: Center(
child: Text(
widget.label,
style: const TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
),
),
),
);
}
}

Then, we will return a Positioned widget. In this widget, we will add the Draggable method. In this method, we will add data, onDraggableCanceled, and feedback.

Create a new dart file called main.dart inside the lib folder.

In the main. dart file, we will create a new class DragTargetDemo(). In this class, we will first create a Color caughtColor was equal to the yellow color.

Color caughtColor = Colors.yellow;

In the Stack widget, we will add two DragBox with Offset, label, and color. We will add a DragTarget widget. Inside the widget, we will add onAccept, and builder. In the builder, we will add a Container with width and height.

Stack(
children: <Widget>[
const DragBox(
Offset(30.0, 0.0),
'Drag This',
Colors.orange,
),
const DragBox(
Offset(250.0, 0.0),
'Drag This',
Colors.cyan,
),
Positioned(
left: 100.0,
bottom: 100.0,
child: DragTarget(
onAccept: (Color color) {
caughtColor = color;
},
builder: (
BuildContext context,
List<dynamic> accepted,
List<dynamic> rejected,
) {
return Container(
width: 150.0,
height: 150.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(28.0),
color: accepted.isEmpty
? caughtColor
: Colors.grey.shade200,
),
child: const Center(
child: Text("You can drag here!"),
),
);
},
),
)
],
),

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Output

Code File

import 'package:flutter/material.dart';
import 'package:flutter_drag_target_demo/drag_box.dart';
import 'package:flutter_drag_target_demo/splash_screen.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const Splash(),
debugShowCheckedModeBanner: false,
);
}
}

class DragTargetDemo extends StatefulWidget {
const DragTargetDemo({Key? key}) : super(key: key);

@override
_DragTargetDemoState createState() => _DragTargetDemoState();
}

class _DragTargetDemoState extends State<DragTargetDemo> {
Color caughtColor = Colors.yellow;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter DragTarget Demo'),
centerTitle: true,
backgroundColor: Colors.teal,
automaticallyImplyLeading: false,
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Stack(
children: <Widget>[
const DragBox(
Offset(30.0, 0.0),
'Drag This',
Colors.orange,
),
const DragBox(
Offset(250.0, 0.0),
'Drag This',
Colors.cyan,
),
Positioned(
left: 100.0,
bottom: 100.0,
child: DragTarget(
onAccept: (Color color) {
caughtColor = color;
},
builder: (
BuildContext context,
List<dynamic> accepted,
List<dynamic> rejected,
) {
return Container(
width: 150.0,
height: 150.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(28.0),
color: accepted.isEmpty
? caughtColor
: Colors.grey.shade200,
),
child: const Center(
child: Text("You can drag here!"),
),
);
},
),
)
],
),
),
);
}
}

Conclusion:

In the article, I have explained the Drag Target basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Drag Target User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying the Drag Target in your flutter projectsWe will show you what the Introduction is and what are the construction and properties of the Input Chip, and make a demo program for working with Drag Target in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


Read my other blogs :

Action Chip In Flutter
Action chip is one of the chips. Typically, it’s utilized to set off an action when the user presses the chipmedium.flutterdevs.com

Explore Types Of Constructors In Dart
Learn the types of Constructors in Dart for your appsmedium.flutterdevs.com

Filter Chip In Flutter
FilterChip is a material design widget in a flutter. Filter chips are utilized when we believe that the client should…medium.flutterdevs.com

Cupertino Timer Picker In Flutter
Cupertino timer picker in flutter is an ios style countdown timer picker. Utilizing the CupertinoTimerPicker widget we…medium.flutterdevs.com

Decorator Design Patterns For Dart & Flutter
The Decorator design is a method for expanding objects involving creation rather than inheritance, which is the…medium.flutterdevs.com


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Related: SMS Using Twilio In Flutter

Related: Using SharedPreferences in Flutter


Octo Image In Flutter

OctoImage is a multifunctional flutter picture widget that is a picture library for showing placeholders, error widgets, and changing your picture.

In this blog, we will explore Octo Image In Flutter. We will also implement a demo program, and learn how to use octo images using the octo_image package in your flutter applications.

octo_image | Flutter Package
An image library for showing placeholders, error widgets, and transforming your image. Recommended using with…pub.dev

If you’re looking for the best flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

Introduction

How to use

Implementation

Code Implement

Code File

Conclusion



Introduction:

The OctoImage widget in flutter requires an ImageProvider to show pictures in an application. The pictures in the OctoImage widget can be provided with a progress indicator and a placeholder for loading the Picture in it.

An OctoImage widget utilizes the Octosets which are only a mix of predefined placeholders, imagebuilders, and error widgets.

Demo Module ::

This demo video shows how to use octo images in a flutter and shows how an Octo Image will work using the octo_image package in your flutter applications. We will show a user different types of images with blur, placeholder, and progress indicators will be shown on your devices.

OctoImage Uses:

There are two ways to use the OctoImage widget as shown below:

  • > Using OctoImage:
OctoImage(
image: NetworkImage(
'YOUR IMAGE URL'),
placeholderBuilder: OctoPlaceholder.blurHash(
'PLACEHOLDER',
),
errorBuilder: OctoError.icon(color: Colors.red),
fit: BoxFit.cover,
);
  • > Using Octosets:
OctoImage.fromSet(
fit: BoxFit.cover,
image: NetworkImage(
'YOUR IMAGE URL',
),
octoSet: OctoSet.circleAvatar(
backgroundColor: Colors.red,
text: Text("Your Text"),
),
);

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
octo_image: ^1.0.2

Step 2: Import

import 'package:octo_image/octo_image.dart';

Step 3: Run flutter packages get in the root directory of your app.

How to implement code in dart file :

You need to implement it in your code respectively:

We will create a class OctoImageDemo extend with StatelessWidget. We will add an appbar and body. In the body, we will add three widgets _image()_blurImage(), and _circleAvatarImage().

class OctoImageDemo extends StatelessWidget {
const OctoImageDemo({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Octo Image Demo'),
backgroundColor: Colors.cyan,
automaticallyImplyLeading: false,
centerTitle: true,
),
body: ListView(
children: [
_image(),
const SizedBox(height: 10),
_blurImage(),
const SizedBox(height: 10),
_circleAvatarImage(),
],
),
);
}
}

First, we will define _image() widget are:

In this widget, we will return SizedBox with a height was 220 and its child OctoImage(). In this OctoImage, we will add an image, progressIndicatorBuilder, and errorBuilder. When the user runs the code first CircularProgressIndicator will run until the image shows.

Widget _image() {
return SizedBox(
height: 220,
child: OctoImage(
image: const NetworkImage(
'https://images.unsplash.com/photo-1516321318423-f06f85e504b3?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTZ8fHRlY2huaWNhbHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=400&q=60'),
progressIndicatorBuilder: (context, progress) {
double? value;
if (progress != null && progress.expectedTotalBytes != null) {
value =
progress.cumulativeBytesLoaded / progress.expectedTotalBytes!;
}
return CircularProgressIndicator(value: value);
},
errorBuilder: (context, error, stacktrace) => const Icon(Icons.error),
),
);
}

Now, we will define _blurImage() widget are:

In this widget, we will blur the image while it’s loading. We will return an AspectRatio was 268 / 173.

Widget _blurImage() {
return AspectRatio(
aspectRatio: 268 / 173,
child: OctoImage(
image: const NetworkImage(
'https://images.unsplash.com/photo-1619551964399-dad708b59b8b?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTR8fHRlY2huaWNhbHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=400&q=60'),
placeholderBuilder: OctoPlaceholder.blurHash(
'LEHV6nWB2yam9wo0adR*.7kCMdnj',
),
errorBuilder: OctoError.icon(color: Colors.red),
fit: BoxFit.cover,
),
);
}

Last, we will define _circleAvatarImage() widget are:

In this widget, we will create a circular avatar to which custom text can be added while it’s loading and can be used as follows.

Widget _circleAvatarImage() {
return SizedBox(
height: 220,
child: OctoImage.fromSet(
fit: BoxFit.cover,
image: const NetworkImage(
'https://images.unsplash.com/photo-1579445710183-f9a816f5da05?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8YXZlbmdlcnN8ZW58MHx8MHx8&auto=format&fit=crop&w=400&q=60',
),
octoSet: OctoSet.circleAvatar(
backgroundColor: Colors.red,
text: const Text("Flutter"),
),
),
);
}

Handling Errors:

A basic method for dealing with mistakes in the OctoImage Widget is to utilize the error widget. These are shown when the ImageProvider throws an error because the picture neglected to stack.

We can construct our custom widget, or we can likewise utilize the prebuild widgets:

OctoImage(
image: image,
errorBuilder: (context, error, stacktrace) =>
const Icon(Icons.error),
);


OctoImage(
image: image,
errorBuilder: OctoError.icon(),
),

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Final Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_octo_image_demo/splash_screen.dart';
import 'package:octo_image/octo_image.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(),
home: const Splash(),
debugShowCheckedModeBanner: false,
);
}
}

class OctoImageDemo extends StatelessWidget {
const OctoImageDemo({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Octo Image Demo'),
backgroundColor: Colors.cyan,
automaticallyImplyLeading: false,
centerTitle: true,
),
body: ListView(
children: [
_image(),
const SizedBox(height: 10),
_blurImage(),
const SizedBox(height: 10),
_circleAvatarImage(),
],
),
);
}

Widget _image() {
return SizedBox(
height: 220,
child: OctoImage(
image: const NetworkImage(
'https://images.unsplash.com/photo-1516321318423-f06f85e504b3?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTZ8fHRlY2huaWNhbHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=400&q=60'),
progressIndicatorBuilder: (context, progress) {
double? value;
if (progress != null && progress.expectedTotalBytes != null) {
value =
progress.cumulativeBytesLoaded / progress.expectedTotalBytes!;
}
return CircularProgressIndicator(value: value);
},
errorBuilder: (context, error, stacktrace) => const Icon(Icons.error),
),
);
}

Widget _blurImage() {
return AspectRatio(
aspectRatio: 268 / 173,
child: OctoImage(
image: const NetworkImage(
'https://images.unsplash.com/photo-1619551964399-dad708b59b8b?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTR8fHRlY2huaWNhbHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=400&q=60'),
placeholderBuilder: OctoPlaceholder.blurHash(
'LEHV6nWB2yam9wo0adR*.7kCMdnj',
),
errorBuilder: OctoError.icon(color: Colors.red),
fit: BoxFit.cover,
),
);
}

Widget _circleAvatarImage() {
return SizedBox(
height: 220,
child: OctoImage.fromSet(
fit: BoxFit.cover,
image: const NetworkImage(
'https://images.unsplash.com/photo-1579445710183-f9a816f5da05?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8YXZlbmdlcnN8ZW58MHx8MHx8&auto=format&fit=crop&w=400&q=60',
),
octoSet: OctoSet.circleAvatar(
backgroundColor: Colors.red,
text: const Text("Flutter"),
),
),
);
}
}

Conclusion:

In the article, I have explained Octo Image’s basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Octo Image On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying up the Octo Image in your flutter projectsWe will show you what the Introduction is. Make a demo program for working with Octo Image and you’ve learned how to use Octo Image using the octo_image package in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Related: Image Compress & Crop In Flutter


Custom Toast Message In Flutter

0

In flutter, no particular widget or function is accessible to show a toast message. We can utilize the snackbar widget rather than toast at the same time, we can’t change the place of the snackbar like toast. To add usefulness for showing toast messages to our flutter application we need to utilize FlutterToast dependency.

This blog will explore the Custom Toast Message In Flutter. We perceive how to execute a demo program. We will learn how to create custom toast messages using fluttertoast dependency with different properties in your flutter applications.

fluttertoast | Flutter Package
Toast Library for Flutter Now this toast library supports two kinds of toast messages one which requires BuildContext…pub.dev

Table Of Contents :

Introduction

Properties

Implementation

Code Implement

Code File

Conclusion



Introduction:

Toast is only a flash message in a flutter, which is utilized to show data to the client temporarily. It shows up at the lower part of the screen as default and disappears after a particular time.

For the most part, we will utilize a toast message to inform the user about the situation with the activity performed. For example, after presenting a registration form we can tell the user about the situation with the enlistment utilizing a toast message.

Demo Module :

The above demo video shows how to create a custom toast message in a flutter. It shows how the custom toast message will work using the fluttertoast package in your flutter applications. It shows when the user presses the button and then toast will display on your screen.

Properties:

Let’s customize the toast message utilizing various properties of FToast.ShowToast() method. These properties will assist in styling and situating the toast message.

  • > child — This property is used to take a widget as value. We will use this property to add a child widget which is a custom toast message.
  • > toastDuration — This property is used to take Duration as value. We will define how long we want the toast message to appear on the screen.
  • > gravity — This property is used to it takes constants of ToastGravity like BOTTOM_LEFT, BOTTOM_RIGHT, BOTTOM, etc.
  • > fadeDuration — This property is used to take an int as value. We will define how long the toast message should fade before appearing on the screen.
  • > positionedToastBuilder — This property is used to take a builder function as a value. If we want to position the toast message at the custom position on the screen other than the constant values of ToastGravity discussed above.

Implementation:

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
fluttertoast: ^8.1.1

Step 2: Import

import 'package:fluttertoast/fluttertoast.dart';

Step 3: Run flutter packages get in the root directory of your app.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called main.dart inside the lib folder.

We have to declare an object of class FToast which is provided in the dependency.

FToast? fToast;

Now, we have to initialize the object with the current context in the initState() method.

@override
void initState() {
super.initState();
fToast = FToast();
fToast?.init(context);
}

In the body part, we will add a Column widget. In this widget, we will add CrossAxisAlignment as the center. Also, add an image and ElevatedButton with text and the onPressed method. In this method, we will add the showCustomToast() method.

Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(height: 50,),
Image.asset(
"assets/logo.png",
height: 300,
width: 350,
),
ElevatedButton(
child: const Text("Show Custom Toast Message"),
onPressed: () {
showCustomToast();
},
),
],
),

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Output

Now we will deeply describe showCustomToast() method are:

We will create the showCustomToast() method. In this method, we will add a Widget toast and showToast.

showCustomToast() {
Widget toast = Container(
padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 12.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25.0),
color: Colors.blueGrey,
),
child: const Text(
"This is a Custom Toast Message",
style: TextStyle(color: Colors.white),
),
);

fToast?.showToast(
child: toast,
toastDuration: const Duration(seconds: 3),
);
}

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Final Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_custom_toast_message_demo/splash_screen.dart';
import 'package:fluttertoast/fluttertoast.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.teal,
),
home: const Splash(),
debugShowCheckedModeBanner: false,
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);

@override
_MyHomePageState createState() {
return _MyHomePageState();
}
}

class _MyHomePageState extends State<MyHomePage> {
FToast? fToast;

@override
void initState() {
super.initState();
fToast = FToast();
fToast?.init(context);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Flutter Custom Toast Message Demo"),
centerTitle: true,
automaticallyImplyLeading: false,
),
body: Container(
margin: const EdgeInsets.all(20),
alignment: Alignment.topCenter,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(height: 50,),
Image.asset(
"assets/logo.png",
height: 300,
width: 350,
),
ElevatedButton(
child: const Text("Show Custom Toast Message"),
onPressed: () {
showCustomToast();
},
),
],
),
));
}

showCustomToast() {
Widget toast = Container(
padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 12.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25.0),
color: Colors.blueGrey,
),
child: const Text(
"This is a Custom Toast Message",
style: TextStyle(color: Colors.white),
),
);

fToast?.showToast(
child: toast,
toastDuration: const Duration(seconds: 3),
);
}
}

Conclusion:

In the article, I have explained the Custom Toast Message basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Custom Toast Message On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying the Custom Toast Message in your flutter projectsWe will show you what the Introduction is. Make a demo program for a working Custom Toast Message using the fluttertoast package in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Related: Building Custom Widgets from Scratch

Related: Custom Music Player in Flutterflow

Related: Custom Chat Bubble In Flutter


Decorator Design Patterns For Dart & Flutter

0

Utilizing inheritance, we can statically broaden the usefulness of a Dart class. Yet, imagine a scenario in which we need more adaptability than that. We might need to add conduct to an object progressively, maybe as a user makes quality determinations.

The Decorator pattern can help! With this pattern, we can join a new way of behaving or properties to an object by enclosing it with an extraordinary decorator that shares the object’s interface.

This blog will explore Decorator Design Patterns for Dart & Flutter. We will perceive how to execute a demo program. Learn how to implement and use it in your flutter applications.

Table Of Contents::

Introduction

Decorator Pattern Example

Conclusion



Introduction:

The Decorator design is a method for expanding objects involving creation rather than inheritance, which is the methodology that works most normally in a Flutter application.

The patterns assist us with molding the connections between the objects and classes we make. These patterns are focused on how classes acquire from one another, how objects can be made out of different objects, and how objects and classes interrelate.

In this article, you’ll figure out how to assemble enormous, exhaustive frameworks from less complex, individual modules, and parts. The patterns help us in making adaptable, approximately coupled, interconnecting code modules to get done with complex responsibilities sensibly.

Decorator Pattern Example:

To exhibit the pattern, we’ll utilize color models, the exemplary workhorse of configuration design models. To begin with, we want to characterize a connection point for colors, and we’ll throw in a couple of sample color classes:

abstract class Color {
String paint();
}
class Red implements Color {
String paint() => "Red";
}
class Blue implements Color {
String paint() => "Blue";
}

Keep in mind, in Dart, there are no unequivocal connection points, however, every class exports its interaction for execution. We characterize the Color interface utilizing an abstract class with the goal that it can’t be straightforwardly launched. In this improved, model, the paint() technique will return a string properly to the color’s sort.

Since Red and Blue implement Color, they are expected to give execution the paint() technique. This implies client code can make factors of type Color that can be allotted to any color class.

With the color models set up, we can characterize a decorator interface and several example decorators:

abstract class ColorDecorator implements Color {
final Color color;
  ColorDecorator(this.color);
  String paint();
}
class GreenColorDecorator extends ColorDecorator {
GreenColorDecorator(Color color) : super(color);
@override
String paint() => "Green ${color.paint()}";
}
class BrownColorDecorator extends ColorDecorator {
BrownColorDecorator(Color color) : super(color);
@override
String paint() => "Brown ${color.paint()}";
}

Yet again we utilize an abstract class to characterize the point of interaction all color decorators ought to stick to. Moreover, ColorDecorator executes Color, so all classes that broaden ColorDecorator are connection points viable with color classes.

This is key because it implies we can start up a decorator, pass it a color, and afterward utilize the decorator like it were the color. That is the pith of the Decorator’s design.

Every decorator class inherits everything from ColorDecorator and overrides the unimplemented paint() strategy. It’s discretionary yet prescribed to incorporate the @override metatag while overriding acquired techniques.

Note that the color classes don’t override paint(); they should carry out paint(), yet they are not superseding an acquired technique when they do since they acquire nothing. Decorator constructors take a reference to the color they’ll design, and they give it to the abstract superclass’ constructor to be put away in the color property. The overridden draw() techniques in the decorator classes prepend their particular adornment onto the designed color’s string portrayal.

Here is an instance of utilizing the color decoration framework:

final red = Red();
print(red.paint());
final greenRed = GreenColorDecorator(red);
print(greenRed.paint());
final brownGreenColor= BrownColorDecorator(greenRed);
print(brownGreenColor.paint());

In the first place, we make a red and print the result from its paint() strategy, which will be the color’s name alone. To make a green red, we develop an example of GreenColorDecorator and passed it to the red. At the point when we draw the green red, we see that the red has been designed.

One of the qualities of the Decorator design is the capacity to apply however many decorators we wish to any object, so we can add a brown to the green red, bringing about a red with both variety enhancements.

Conclusion:

This blog will provide you with sufficient information on Trying up the Decorator Design Patterns for Dart & Flutter in your projectsYou can see that this pattern gives an adaptable method for adding qualities or conduct to an item at runtime, piecemeal, as an option in contrast to making new classes to cover each mix of characteristics an object might require.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Select Item Of List In Flutter

0

In some cases, we need to choose more than one thing from the list and play out some action i.e delete the selected item and so forth.

This blog will explore the Select Item Of List In Flutter. We perceive how to execute a demo program. We will learn how to select an item from the list in your flutter applications.

Table Of Contents::

Introduction

Code Implement

Code File

Conclusion



Introduction:

The below demo video shows how to select the items of the list in a flutter and shows how a select item will work in your flutter applications. We will show the user long press the items, then the items will be selected or deselected. Also, the user selected/ de-selected all items with a single click. It will be shown on your devices.

Demo Module ::


Code Implement:

You need to implement it in your code respectively:

Create a new dart file called data.dart inside the lib folder.

First of all, we need some data to make the app look like a real app and take some real scenarios. Create a data.dart file.

class MyData {
static List<Map> data = [
{
"id": 1,
"name": "Rahul",
"email": "rahul240@gamil.com",
"address": "120 kanpur India"
},
{
"id": 2,
"name": "Yogesh",
"email": "yogi@gamil.com",
"address": "1A/24 Delhi India"
},
{
"id": 3,
"name": "Rakhi",
"email": "rakhi@inc.com",
"address": "221 Bihar India"
},
{
"id": 4,
"name": "Thomas",
"email": "roy@yahoo.com",
"address": "406 Mumbai India"
},
{
"id": 5,
"name": "Manoj",
"email": "mnaoj24@aeo.com",
"address": "54 Noida Dadri"
},
{
"id": 6,
"name": "Mohit",
"email": "mohit5@gamil.com",
"address": "35 Greater Noida"
},
{
"id": 7,
"name": "Sadman",
"email": "khan6@gamil.com",
"address": "132 Pune India"
},
{
"id": 8,
"name": "Nadeem",
"email": "nawab7@gamil.com",
"address": "121 Lucknow India"
},
{
"id": 9,
"name": "Yashwant",
"email": "yash@gmail.com",
"address": "32 Delhi India"
},
{
"id": 10,
"name": "Prasad",
"email": "prasad@yahoo.com",
"address": "217 Mumbai India"
},
{
"id": 11,
"name": "Pragati",
"email": "pragati@tumblr.com",
"address": "3 Dehradun India"
},
{
"id": 12,
"name": "Imojean",
"email": "iwalbrookb@zdnet.com",
"address": "91904 Fieldstone Lane"
},
{
"id": 13,
"name": "Rochell",
"email": "rsharplesc@drupal.org",
"address": "46 Schmedeman Place"
},
{
"id": 14,
"name": "Fayina",
"email": "fwellwoodd@mapquest.com",
"address": "1 Anderson Street"
},
{
"id": 15,
"name": "Dilan",
"email": "dgethinge@wsj.com",
"address": "87297 High Crossing Alley"
},
{
"id": 16,
"name": "Berkie",
"email": "bmousbyf@si.edu",
"address": "5611 Colorado Drive"
},
{
"id": 17,
"name": "Aliza",
"email": "aabelsg@de.vu",
"address": "56 Dunning Way"
},
{
"id": 18,
"name": "Gene",
"email": "gernih@slashdot.org",
"address": "0479 Jay Court"
},
{
"id": 19,
"name": "Devland",
"email": "dlindbladi@geocities.jp",
"address": "0971 Johnson Terrace"
},
{
"id": 20,
"name": "Leigh",
"email": "larlidgej@xinhuanet.com",
"address": "430 Hanover Park"
},
{
"id": 21,
"name": "Annamaria",
"email": "agerreyk@jiathis.com",
"address": "03345 Larry Junction"
},
{
"id": 22,
"name": "Agace",
"email": "arubenczykl@meetup.com",
"address": "119 Stuart Alley"
},
{
"id": 23,
"name": "Ninette",
"email": "nhuglim@npr.org",
"address": "746 Calypso Plaza"
},
{
"id": 24,
"name": "Sosanna",
"email": "scopestaken@cloudflare.com",
"address": "81924 North Parkway"
},
{
"id": 25,
"name": "Millard",
"email": "mcullumo@jigsy.com",
"address": "6215 Hoepker Park"
},
];
}

The code will seem to be like the given snippet. Presently you go the data and now is the ideal time to render the data in the application and move towards the choice feature.

Create a new dart file called HomePage.dart inside the lib folder.

Now we will make the UI using the ListView.builder. The data will be loaded from the data. dart.

import 'package:flutter/material.dart';
import 'package:flutter_select_list_item_demo/data.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<Map> staticData = MyData.data;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Select Item Of List Demo'),
automaticallyImplyLeading: false,
centerTitle: true,
backgroundColor: Colors.cyan,
),
body: ListView.builder(
itemBuilder: (builder, index) {
Map data = staticData[index];
selectedFlag[index] = selectedFlag[index] ?? false;
bool? isSelected = selectedFlag[index];

return ListTile(
onLongPress: () => onLongPress(isSelected!, index),
onTap: () => onTap(isSelected!, index),
title: Text("${data['name']}"),
subtitle: Text("${data['email']}"),
leading: _buildSelectIcon(isSelected!, data),
);
},
itemCount: staticData.length,
),
);
}
}

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Output

Now will be added Selection Mode:

If I discuss myself, I will most likely utilize a long press. i.e When you long-press on the list item then it chooses the long-pressed thing and enables the determination mode.

On the off chance that anything is chosen from the list, the selection model is empowered.

We want a variable to flag the choice status of the item. To monitor the list of item determinations, we will utilize Map. The Map will store the unique id as the key and the boolean as the choice flag.

Adding Flag Variable for tracing selection Status:

Presently we want to follow which thing is chosen and which isn’t. To store this we want a variable of some sort. As we have a list of data so we likewise need a variable that can store the list of data.

import 'package:flutter/material.dart';
import 'package:flutter_select_list_item_demo/data.dart';

class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);

@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
bool isSelectionMode = false;
List<Map> staticData = MyData.data;
Map<int, bool> selectedFlag = {};

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Select Item Of List Demo'),
automaticallyImplyLeading: false,
centerTitle: true,
backgroundColor: Colors.cyan,
),
body: ListView.builder(
itemBuilder: (builder, index) {
Map data = staticData[index];
selectedFlag[index] = selectedFlag[index] ?? false;
bool? isSelected = selectedFlag[index];

return ListTile(
onLongPress: () => onLongPress(isSelected!, index),
onTap: () => onTap(isSelected!, index),
title: Text("${data['name']}"),
subtitle: Text("${data['email']}"),
leading: _buildSelectIcon(isSelected!, data),
);
},
itemCount: staticData.length,
),
);
}

void onTap(bool isSelected, int index) {
if (isSelectionMode) {
setState(() {
selectedFlag[index] = !isSelected;
isSelectionMode = selectedFlag.containsValue(true);
});
} else {
// Open Detail Page
}
}

void onLongPress(bool isSelected, int index) {
setState(() {
selectedFlag[index] = !isSelected;
isSelectionMode = selectedFlag.containsValue(true);
});
}

Widget _buildSelectIcon(bool isSelected, Map data) {
if (isSelectionMode) {
return Icon(
isSelected ? Icons.check_box : Icons.check_box_outline_blank,
color: Theme.of(context).primaryColor,
);
} else {
return CircleAvatar(
child: Text('${data['id']}'),
);
}
}
}

We can utilize a list yet using a map will be better and more powerful here. We can have user_id as the key to map and value as a boolean. As the list thing has an id and it’s extraordinary so utilizing a map is the most ideal choice here.

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Selected Output

Now Adding Select All Button:

Presently we will add the select all button so we can choose every one of the things on the list utilizing one tap/click. This is vital in the creation application and this feature makes life simpler when there is an extremely extensive list.

Add this line of code to the Scaffold

floatingActionButton: _buildSelectAllButton(),

The button will be apparent when the selectionMode is empowered. The floating Button icon button changed based on the item chosen.

Widget? _buildSelectAllButton() {
bool isFalseAvailable = selectedFlag.containsValue(false);
if (isSelectionMode) {
return FloatingActionButton(
backgroundColor: Colors.cyan,
onPressed: _selectAll,
child: Icon(
isFalseAvailable ? Icons.done_all : Icons.remove_done,
),
);
} else {
return null;
}
}

void _selectAll() {
bool isFalseAvailable = selectedFlag.containsValue(false);
selectedFlag.updateAll((key, value) => isFalseAvailable);
setState(() {
isSelectionMode = selectedFlag.containsValue(true);
});
}

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_select_list_item_demo/data.dart';

class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);

@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
bool isSelectionMode = false;
List<Map> staticData = MyData.data;
Map<int, bool> selectedFlag = {};

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Select Item Of List Demo'),
automaticallyImplyLeading: false,
centerTitle: true,
backgroundColor: Colors.cyan,
),
body: ListView.builder(
itemBuilder: (builder, index) {
Map data = staticData[index];
selectedFlag[index] = selectedFlag[index] ?? false;
bool? isSelected = selectedFlag[index];

return ListTile(
onLongPress: () => onLongPress(isSelected!, index),
onTap: () => onTap(isSelected!, index),
title: Text("${data['name']}"),
subtitle: Text("${data['email']}"),
leading: _buildSelectIcon(isSelected!, data),
);
},
itemCount: staticData.length,
),
floatingActionButton: _buildSelectAllButton(),
);
}

void onTap(bool isSelected, int index) {
if (isSelectionMode) {
setState(() {
selectedFlag[index] = !isSelected;
isSelectionMode = selectedFlag.containsValue(true);
});
} else {
// Open Detail Page
}
}

void onLongPress(bool isSelected, int index) {
setState(() {
selectedFlag[index] = !isSelected;
isSelectionMode = selectedFlag.containsValue(true);
});
}

Widget _buildSelectIcon(bool isSelected, Map data) {
if (isSelectionMode) {
return Icon(
isSelected ? Icons.check_box : Icons.check_box_outline_blank,
color: Theme.of(context).primaryColor,
);
} else {
return CircleAvatar(
child: Text('${data['id']}'),
);
}
}

Widget? _buildSelectAllButton() {
bool isFalseAvailable = selectedFlag.containsValue(false);
if (isSelectionMode) {
return FloatingActionButton(
backgroundColor: Colors.cyan,
onPressed: _selectAll,
child: Icon(
isFalseAvailable ? Icons.done_all : Icons.remove_done,
),
);
} else {
return null;
}
}

void _selectAll() {
bool isFalseAvailable = selectedFlag.containsValue(false);
selectedFlag.updateAll((key, value) => isFalseAvailable);
setState(() {
isSelectionMode = selectedFlag.containsValue(true);
});
}
}

Conclusion:

In the article, I have explained the Select Item basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Select Item On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying Select Items From the List in your flutter projectsWe will show you make a demo program for working with selecting an item from the list in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I need to correct something? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Related: Sum Of a List Of Numbers In Dart

Related: Inbuild List Methods In Dart


Explore Futures & Completers In Dart & Flutter

0

Even though Dart, with its helpful async/await syntax, can take a ton of the intricacy out of overseeing asynchronous calls, some of the time you want to cooperate with a more conventional callback library or a constant association that doesn’t work with prospects.

That is where completers come into the image. You can work on the API surface of a stateless callback library, similar to the one used to get to REST web APIs, by wrapping it with a future-based API. You can do likewise with stateful, relentless association APIs.

This blog will be Explore Futures & Completers In Dart & Flutter. We will perceive how to execute a demo program. Learn how to implement and use it in your flutter applications.

Table Of Contents::

Wrapping Callback library To Use Futures

Wrapping Persistent Connection To Use Futures

Conclusion



Wrapping Callback library To Use Futures:

A completer permits you to make and deal with a future. Whenever you’ve started up a completer, you can utilize it to restore a future to your APIs, and when an extended asynchronous call returns data or an error, you can finish that future, conveying the outcome.

To use completers, you need to import the dart:async core library. In the example, we’ve created a function, asyncQuery()that interacts with a fictional network call represented by getHttpData(). Our function will return a future initially, but it will resolve into string data at a later time.

To utilize completers, you want to import the dart: async core library. In the model, we’ve made a capability, asyncQuery() that cooperates with an imaginary network call addressed by getHttpData().

import 'dart:async';
Future<String> asyncQuery() {
final completer = Completer<String>();
  getHttpData(
onComplete: (results) {
completer.complete(results);
},
onError: (error) {
completer.completeError(error);
}
);
  return completer.future;
}

How about we skip the call getHttpData() for the second and check out at the last line of asyncQuery()? There, we return the future occurrence related to the completer we’ve started up. At the point when our capability is executed, the completer (and future) are made, then the network call happens asynchronously as we register the callbacks it needs.

The getHttpData() function takes two boundaries, the first being a completion callback and the second an error callback. The finish callback finishes the future we’ve previously returned, sending results with it. With this example, you can keep clients of your code from being required to manage callbacks, permitting them to get data by getHttpData() utilizing the less complex future worldview.

Wrapping a persistent connection to use futures

If your application collaborates with a tireless association, utilizing attachments or something almost identical, expecting a reaction from the socket server in the wake of making a request is normal. Over a stateful, relentless association, your application can’t foresee when or in what request reactions or other spontaneous messages might show up.

To show this example, we should take a gander at an extract from an socket service class you could use in your application:

class SocketService {
final _socketConnection = SomeSocketConnection();
final Map<String, Completer<String>> _requests = {};
  Future<String> sendSocketMessage(String data) {
final completer = Completer<String>();
final requestId = getUniqueId();
    final request = {
'id': requestId,
'data': data,
};
    _requests[requestId] = completer;
    _socketConnection.send(jsonEncode(request));
    return completer.future;
}
  void _onSocketMessage(String json) {
final decodedJson = jsonDecode(json);
final requestId = decodedJson['id'];
final data = decodedJson['data'];
    if (_requests.containsKey(requestId)) {
_requests[requestId].complete(data);
_requests.remove(requestId);
}
}
}

As referenced, this is only a passage, yet what’s incorporated will exhibit the future administration pattern. The class gets going by introducing an imaginary socket association object and a vacant map that is utilized to monitor dynamic attachment demands. The map will involve string demand IDs as keys and completers as values, making a table of completers.

To monitor which solicitations are related to which response, we want to create an exceptional ID and connect it to each ask. The socket server should incorporate that equivalent ID with every response. Along these lines, when socket messages show up, we can analyze the ID and find it in our solicitation table to decide whether the message is a reaction to a prior demand

The public sendSocketRequest() method accepts a few string information as a contention and returns a future. The strategy initially makes a couple of comfort factors as it produces a completer and a request ID for the request.

Note that there is no real getUniqueId() function. You can create unique IDs by anything implies you favor. Then, we put the ID and the data into a Map<String, dynamic> so we can encode it as JSON to be sent over the attachment.

final response = await mySocketService.sendSocketMessage("Hi!");

The response variable will be filled when a response to this particular request is gotten by the client application, and this calling code never needs to realize pretty much all the accounting occurring in the background to keep requests and responses accurately matched.

Conclusion

I hope this blog will provide you with sufficient information on Trying up the Explore Futures & Completers In Dart & Flutter in your projectsNow you know how to make interacting with callback libraries easier using Dart futures and completers.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Action Chip In Flutter

0

Material Design has conservative components called chips. Action chip is one of the chips. Typically, it’s utilized to set off an action when the user presses the chip. Flutter makes it more straightforward for us to make an action chip by giving us a widget called ActionChip.

This blog will explore the Action Chip In Flutter. We perceive how to execute a demo program. We will learn how to use the Action Chip and how to customize your flutter applications.

ActionChip class – material library – Dart API
A Material Design action chip. Action chips are a set of options that trigger an action related to primary content…api. flutter.dev

Table Of Contents::

Introduction

Constructor

Properties

Code Implement

Code File

Conclusion



Introduction:

ActionChip is a material widget in a flutter. The actual name proposes that they are utilized to set off some action. Action chips ought to be made progressively founded on the context of the essential substance.

We can’t incapacitate an action chip so showing it to the user without its purpose is better not. Flutter gives a widget called ActionChip which permits us to add an action chip to our application.

Demo Module::

This demo video shows how to use the action chip in a flutter and shows how an action chip will work in your flutter applications. We will show a user press the chip then, the chip will trigger an action. It will be shown on your devices.

Constructor:

To utilize ActionChip, you need to call the constructor underneath:

To make an action chip in flutter we need to call the constructor of the ActionChip class given by flutter. ActionChip has two required properties label and onPressed callback.

const ActionChip({
Key? key,
this.avatar,
required this.label,
this.labelStyle,
this.labelPadding,
required this.onPressed,
this.pressElevation,
this.tooltip,
this.side,
this.shape,
this.clipBehavior = Clip.none,
this.focusNode,
this.autofocus = false,
this.backgroundColor,
this.padding,
this.visualDensity,
this.materialTapTargetSize,
this.elevation,
this.shadowColor,
})

Without utilizing these properties we can’t make an action chip. We need to set the label with a widget, typically a text widget. The onPressed callback is utilized to play out any action when the chip is squeezed.

Properties:

There are some properties of ActionChip are:

  • > avatar — This property is used to add an avatar to the action chip.
  • > shape — This property is used to change the shape of the action chip.
  • > shadowColor — This property is used to apply color to the shadow which appears when the chip has elevation.
  • > pressElevation — This property is used to provide elevation when the chip is pressed.
  • > onPressed — This property is used to perform some action when we press the chip.
  • > labelStyle — This property is used to apply a style to the label like changing font size, font family, text color, etc.
  • > backgroundColor — This property is used to change the background color of the action chip.
  • > side — This property is used to apply a border to the action chip.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called main.dart inside the lib folder.

In the main. dart file, we will create a new class MyHomePage(). In this class, we will create a bool selected that is equal to the false.

bool selected = false;

In the body, we will add a Center widget. In this widget, we will add a Column widget and add an image with height and width. Also, we will add a Container widget.

Center(
child: Column(
children: [
Image.asset(
"assets/logo.png",
height: 300,
width: 350,
),
Container(
alignment: Alignment.topCenter,
margin: const EdgeInsets.only(top: 20),
child: ActionChip(
backgroundColor: Colors.brown.shade200,
padding: const EdgeInsets.only(top: 20,left: 20, right: 20,bottom: 20),
avatar: selected ? const CircularProgressIndicator() : null,
label: Text(selected ? "Cancel" : "Download",style: const TextStyle(fontSize: 16),),
onPressed: () {
selected = !selected;
setState(() {});
},
elevation: 8),
),
],
),
)

On this widget, we will add an alignment was the topCenter and add an ActionChip widget. Inside the widget, we will add backgroundColor, padding, avatar, label, elevation, and onPressed function. In this function, we will add selected equal not selected.

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_action_chip_demo/splash_screen.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.brown,
),
home: const Splash(),
debugShowCheckedModeBanner: false,
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);

@override
_MyHomePageState createState() {
return _MyHomePageState();
}
}

class _MyHomePageState extends State<MyHomePage> {
bool selected = false;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Flutter Action Chip Demo",
style: TextStyle(color: Colors.black),
),
centerTitle: true,
automaticallyImplyLeading: false,
backgroundColor: Colors.brown.shade200,
),
body: Center(
child: Column(
children: [
Image.asset(
"assets/logo.png",
height: 300,
width: 350,
),
Container(
alignment: Alignment.topCenter,
margin: const EdgeInsets.only(top: 20),
child: ActionChip(
backgroundColor: Colors.brown.shade200,
padding: const EdgeInsets.only(
top: 20, left: 20, right: 20, bottom: 20),
avatar: selected ? const CircularProgressIndicator() : null,
label: Text(
selected ? "Cancel" : "Download",
style: const TextStyle(fontSize: 16),
),
onPressed: () {
selected = !selected;
setState(() {});
},
elevation: 8),
),
],
),
));
}
}

Conclusion:

In the article, I have explained the Action Chip basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Action Chip User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying the Action Chip in your flutter projectsWe will show you what the Introduction is and what are the construction and properties of the Action Chip, and make a demo program for working with Action Chip in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on FacebookGitHubTwitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Related: Filter Chip In Flutter

Related: Input Chip In Flutter