Google search engine
Home Blog Page 12

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.


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.


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.


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.


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.


Filter Chip In Flutter

0

An assortment of filter chips is typically utilized where the user can choose different choices. Making a filter chip in Flutter should be possible by utilizing the FilterChip widget which is exceptionally simple to utilize.

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

FilterChip class – material library – Dart API
A Material Design filter chip. Filter chips use tags or descriptive words as a way to filter content. Filter chips are…api. flutter.dev

Table Of Contents::

Introduction

Constructor

Properties

Code Implement

Code File

Conclusion



Introduction:

FilterChip is a material design widget in a flutter. Filter chips are utilized when we believe that the client should choose different choices from a gathering of chips.

Flutter gives a widget called FilterChip which permits us to add a filter chip to our application. They can be utilized in the spot of Checkbox or Switch widgets. It requires one of its precursors to be a Material widget.

Demo Module ::

This demo video shows how to use the filter chip in a flutter and shows how a filter chip will work in your flutter applications. We will show a user choose the many choices from a group of chips. It will be shown on your devices.

Construction:

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

To create a filter chip in flutter we have to call the constructor of the FilterChip class provided by flutter. There are two required properties for the FilterChip widget which are label and onSelected callback.

To make a filter chip in flutter we need to call the constructor of the FilterChip class given by flutter. There are two required properties for the FilterChip widget which are label and onSelected callback.

const FilterChip({
Key? key,
this.avatar,
required this.label,
this.labelStyle,
this.labelPadding,
this.selected = false,
required this.onSelected,
this.pressElevation,
this.disabledColor,
this.selectedColor,
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,
this.selectedShadowColor,
this.showCheckmark,
this.checkmarkColor,
this.avatarBorder = const CircleBorder(),
})

Without utilizing these properties we can’t make a filter chip. We need to set the name with a widget, normally a text widget. The onSelected callback is utilized to address whether the chip is chosen or unselected.

Properties:

There are some properties of FilterChip are:

  • > selected — This property is utilized to show whether the chip is chosen or unselected. It takes a boolean value setting true will make the chip chosen and false will make the chip unselected.
  • > onSelected — This property is utilized to update the chosen or unselected condition of the decision chip and to play out certain activities when the chip is chosen or unselected.
  • > showCheckmark — This property is used to show/hide the checkmark that appears when the chip is selected. It is a boolean value. Setting true will make the checkmark visible and false will make it invisible. By default the value is true.
  • > pressElevation — This property is used to change the amount of elevation we want to apply when we press the chip.
  • > backgroundColor — This property is used to add/change the background color of the filter chip.
  • > elevation — This property is used to apply elevation to the filter chip.

How to implement code in dart file :

You need to implement it in your code respectively:

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

First, we want an ItemModel class for holding the information of Filterchip. The List will hold the objects of type ItemModel which is a pojo class. The pojo class will have three parameters label, color, and isSelected.

import 'dart:ui';

class ItemModel {
String label;
Color color;
bool isSelected;

ItemModel(this.label, this.color, this.isSelected);
}

The label will hold the label of the chip, the color will hold the backgroundColor and isSelected will hold the chosen or unselected condition of the filter chip.

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 first create a List of types ItemModel and provide the data for chips.

final List<ItemModel> _chipsList = [
ItemModel("Android", Colors.green, false),
ItemModel("Flutter", Colors.blueGrey, false),
ItemModel("Ios", Colors.deepOrange, false),
ItemModel("Python", Colors.cyan, false),
ItemModel("React JS", Colors.teal, false),
];

We will create a bool selected is equal to the false

bool selected = false;

In the body, we will be a Column widget. In this widget, we will add an image with height and width. We will add a Wrap widget. in this widget, we will add a spacing was 8, the direction was the horizontal axis, and the filterChipsList() method. We will below define the method with the code.

Column(
children: [
Image.asset(
"assets/logo.png",
height: 300,
width: 350,
),
Wrap(
spacing: 8,
direction: Axis.horizontal,
children: filterChipsList(),
),
],
),

Now we will deeply define filterChipsList() method are:

This method was on the list of widgets. We will add the FilterChip widget. In this widget, we will add a label, backgroundColor, selected, labelStyle selected, onSelected, and then return chips.

List<Widget> filterChipsList() {
List<Widget> chips = [];
for (int i = 0; i < _chipsList.length; i++) {
Widget item = Padding(
padding: const EdgeInsets.only(left: 10, right: 5),
child: FilterChip(
label: Text(_chipsList[i].label),
labelStyle: const TextStyle(color: Colors.white,fontSize: 16),
backgroundColor: _chipsList[i].color,
selected: _chipsList[i].isSelected,
onSelected: (bool value) {
setState(() {
_chipsList[i].isSelected = value;
});
},
),
);
chips.add(item);
}
return chips;
}

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_filter_chips_demo/item_model.dart';
import 'package:flutter_filter_chips_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.blueGrey,
),
debugShowCheckedModeBanner: false,
home: const Splash(),
);
}
}

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

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

class _MyHomePageState extends State<MyHomePage> {
bool selected = false;
final List<ItemModel> _chipsList = [
ItemModel("Android", Colors.green, false),
ItemModel("Flutter", Colors.blueGrey, false),
ItemModel("Ios", Colors.deepOrange, false),
ItemModel("Python", Colors.cyan, false),
ItemModel("React JS", Colors.teal, false),
];

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Flutter Filter Chip Demo"),
automaticallyImplyLeading: false,
centerTitle: true,
),
body: Center(
child: Column(
children: [
Image.asset(
"assets/logo.png",
height: 300,
width: 350,
),
Wrap(
spacing: 8,
direction: Axis.horizontal,
children: filterChipsList(),
),
],
),
));
}

List<Widget> filterChipsList() {
List<Widget> chips = [];
for (int i = 0; i < _chipsList.length; i++) {
Widget item = Padding(
padding: const EdgeInsets.only(left: 10, right: 5),
child: FilterChip(
label: Text(_chipsList[i].label),
labelStyle: const TextStyle(color: Colors.white,fontSize: 16),
backgroundColor: _chipsList[i].color,
selected: _chipsList[i].isSelected,
onSelected: (bool value) {
setState(() {
_chipsList[i].isSelected = value;
});
},
),
);
chips.add(item);
}
return chips;
}
}

Conclusion:

In the article, I have explained the Filter Chip basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Filter 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 Filter Chip in your flutter projectsWe will show you what the Introduction is and what are the construction and properties of the Filter Chip, and make a demo program for working with Filter 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.


Cupertino Timer Picker In Flutter

0

The most excellent portable applications up to this point we have seen had clicks and contacts and motions taps and adding these connections in a mobile application was so difficult, However, Flutter acts to the rescue and assists you with building the most Lovely application encounters across various stages with the equivalent codebase.
We can establish the point in time for a countdown timer utilizing a timer picker. Rather than using it as a picker for a countdown timer, we can on the other hand involve it as a time picker.

This article will explore the Cupertino Timer Picker In Flutter. We will see how to implement a demo program. Learn how to create an ios style CupertinoTimerPicker and also learn how to customize the style of the CupertinoTimerPicker widget using different properties.in your flutter applications.

Table Of Contents::

Introduction

Constructor

Parameters

Code Implement

Code File

Conclusion



Introduction:

Cupertino timer picker in flutter is an ios style countdown timer picker. Utilizing the CupertinoTimerPicker widget we can add an ios style countdown timer picker to our application. A timer picker allows us to establish the point in time for a countdown timer. We can likewise involve it as a time picker for picking time as opposed to involving it as a selector for a countdown timer.

By and large, we will utilize a countdown timer to show the time left in a web-based assessment or before sending off an occasion, and so on. It will show the countdown duration in hours, minutes, and seconds. The greatest span we can set is 23 hours 59 minutes and 59 seconds.

Demo Module ::

This demo video shows how to create a Cupertino timer picker in a flutter and shows how a Cupertino timer picker will work in your flutter applications. We will show a button, when a user press a button, then show a model popup for the chosen timer. It will be shown on your device.

Constructor:

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

To make a Cupertino timer picker in flutter we need to utilize CupertinoTimerPicker class. Calling the constructor and giving the necessary properties will accomplish the work. It has one required property onTimerDurationChanged. It takes a callback capability as a value.

CupertinoTimerPicker({
Key? key,
this.mode = CupertinoTimerPickerMode.hms,
this.initialTimerDuration = Duration.zero,
this.minuteInterval = 1,
this.secondInterval = 1,
this.alignment = Alignment.center,
this.backgroundColor,
required this.onTimerDurationChanged,
})

We don’t need to show a timer picker consistently like different widgets. We need to show it when an occasion triggers. For instance, on the snap of a button, or some other widget. For the most part, we will show a timer picker utilizing showCupertinoModalPopup or showModalBottomSheet.

Properties:

There are some properties of CupertinoTimerPicker are:

  • > mode — This Property is utilized to change the mode of the timer picker. It accepts the CupertinotimerPickerMode consistent as a value. It has three constants hm, ms, and hms. Naturally, it is hms (hours minutes seconds).
  • > initialTimeDuration — This Property is used to the InitialTimerDuration has a default value of 0 and a maximum value of 23 hours 59 minutes 59 seconds.
  • > minuteInterval — This Property is used to change the interval between the minutes of the timer picker we will use this property. It takes double as value. By default, it is 1.
  • > secondInterval — This Property is used to change the seconds of the timer picker we will use this property. It also takes double as a value which is 1 by default.
  • > alignment — This Property is used for the Classes generated with Alignment and its variations are acceptable in a property or argument of this kind.
  • > backgroundColor — This Property is utilized in this parameter to alter the picker’s background color. CupertinoColors or the colors class steady are acknowledged as values.
  • > onTimerDurationChanged — This Property is used for the callback function is the value it accepts. Every time the user modifies the time in the picker, this function is called. The most recent time will be obtained through this method. We will use the setState() function to update the UI with this value.

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 MyHomePage class. We will create a Duration initialTimer is equal to the Duration() and also create var time.

Duration initialTimer = const Duration();
var time;

Now, we will create a widget was timerPicker(). In this widget, we will return the CupertinoTimerPicker method. In this method, we will add a mode was CupertinoTimerPickerMode.hms, minuteInterval was 1, secondInterval was also 1, and initialTimerDuration was initialTimer.

Widget timerPicker() {
return CupertinoTimerPicker(
mode: CupertinoTimerPickerMode.hms,
minuteInterval: 1,
secondInterval: 1,
initialTimerDuration: initialTimer,
onTimerDurationChanged: (Duration changeTimer) {
setState(() {
initialTimer = changeTimer;
time =
'${changeTimer.inHours} hrs ${changeTimer.inMinutes % 60} mins ${changeTimer.inSeconds % 60} secs';
});
},
);
}

Also, we will add the onTimerDurationChanged property. In this property, we will add inside a setState() function. In this function, we will add initialTimer is equal to the changeTimer and time is equal to the hrs, mins, and sec.

Now, we will create a widget was _buildContainer(Widget picker).

In this widget, we will return a Container with height, padding, and color, and the child was DefaultTextStyle() method. In this method, we will add GestureDetector().

Widget _buildContainer(Widget picker) {
return Container(
height: 200,
padding: const EdgeInsets.only(top: 6.0),
color: CupertinoColors.white,
child: DefaultTextStyle(
style: const TextStyle(
color: CupertinoColors.black,
fontSize: 22.0,
),
child: GestureDetector(
onTap: () {},
child: SafeArea(
top: false,
child: picker,
),
),
),
);
}

Now, in the body, we will add the Inkwell widget. In this widget, we will add the onTap() function. In this function, we will add showCupertinoModalPopup. Also, we will add a Container with height and add the text “Cupertino Timer Picker”. Also, adding other text was times ie equal to null then show ‘No Select Time’ else show ‘time’ when the user was selected

InkWell(
onTap: () {
showCupertinoModalPopup<void>(
context: context,
builder: (BuildContext context) {
return _buildContainer(timerPicker());
});
},
child: Column(
children: [
Container(
height: 50,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Colors.cyan),
child: const Center(
child: Text(
"Cupertino Timer Picker",
style: TextStyle(color: Colors.white, fontSize: 17),
),
),
),
Container(
padding: const EdgeInsets.only(top: 8, bottom: 8),
child: Text(
time == null ? 'No Select Time' : ' $time',
style: const TextStyle(
color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.bold),
),
),
],
),
),

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/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_timerpicker_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 const MaterialApp(
debugShowCheckedModeBanner: false,
home: Splash(),
);
}
}

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

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

class _MyHomePageState extends State {
Duration initialTimer = const Duration();
var time;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Flutter Cupertino Timer Picker Demo"),
automaticallyImplyLeading: false,
centerTitle: true,
backgroundColor: Colors.green,
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
"assets/logo.png",
height: 200,
),
const SizedBox(
height: 50,
),
InkWell(
onTap: () {
showCupertinoModalPopup<void>(
context: context,
builder: (BuildContext context) {
return _buildContainer(timerPicker());
});
},
child: Column(
children: [
Container(
height: 50,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Colors.cyan),
child: const Center(
child: Text(
"Cupertino Timer Picker",
style: TextStyle(color: Colors.white, fontSize: 17),
),
),
),
Container(
padding: const EdgeInsets.only(top: 8, bottom: 8),
child: Text(
time == null ? 'No Select Time' : ' $time',
style: const TextStyle(
color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.bold),
),
),
],
),
),
],
),
),
);
}

Widget timerPicker() {
return CupertinoTimerPicker(
mode: CupertinoTimerPickerMode.hms,
minuteInterval: 1,
secondInterval: 1,
initialTimerDuration: initialTimer,
onTimerDurationChanged: (Duration changeTimer) {
setState(() {
initialTimer = changeTimer;
time =
'${changeTimer.inHours} hrs ${changeTimer.inMinutes % 60} mins ${changeTimer.inSeconds % 60} secs';
});
},
);
}

Widget _buildContainer(Widget picker) {
return Container(
height: 200,
padding: const EdgeInsets.only(top: 6.0),
color: CupertinoColors.white,
child: DefaultTextStyle(
style: const TextStyle(
color: CupertinoColors.black,
fontSize: 22.0,
),
child: GestureDetector(
onTap: () {},
child: SafeArea(
top: false,
child: picker,
),
),
),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying the Cupertino Timer Picker in your flutter projectsWe will show you what the Introduction is and what are the construction and properties of the Choice Chip, and make a demo program for working with Cupertino Timer Picker 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.