Google search engine
Home Blog Page 31

Exploring Dart DevTools

0

Today’s article, We are going to Explore Dart DevTools. Dart Dev Tools, you were able to debug your Flutter application and inspector your flutter code. In any case, presently, with a new Preview of Dart Dev Tools, things get insane! They redeveloped Dart Dev Tools utilizing Flutter and made it an independent application. So yes, now we are going to utilize a stage to debug our applications created with Flutter. Now you can debug your applications and measure your performance and different metrics with Dart Dev Tools. These tools have flowed in IDEs, the flutter tool, the webdev tools, and the devtools package

DevTools with Flutter app

  • Inspect the UI design and state of a Flutter application.
  • Analyze UI jank execution issues in a Flutter application.
  • Source-level debugging of a Flutter or Dart command-line application.
  • Debug memory issues in a Flutter or Dart command-line application.
  • View general log and diagnostics data about a running Flutter or Dart command-line application.

How to install DevTools:

  1. Install the Flutter plugin -: Install the Flutter plugin in the event that you don’t as of now have it installed. This should be possible utilizing the ordinary Plugins page in the IntelliJ and Android Studio settings. When that page is open, you can search the marketplace for the Flutter plugin.
  2. Start an application to debug -: To open DevTools, you first need to run a Flutter application. This can be cultivated by opening a Flutter project, ensuring that you have a device connected, and clicking the Run or Debug toolbar buttons.
  3. Launch DevTools from the toolbar/menu –: Once an application is running, you can begin DevTools utilizing one of the following.

-> Select the Open DevTools toolbar activity in the Run view.

-> Select the Open DevTools toolbar activity in the Debug view. (on the off chance that is debugging)

-> Select the Open DevTools activity from the More Actions menu in the Flutter Inspector view.

Flutter inspector

The Flutter appliance controller is an amazing asset for imagining and investigating Flutter appliance trees. The Flutter structure utilizes an appliance as the center structure block for anything from controls like content and flips, to design like focusing, lines, and sections. The inspector makes you picture and investigates Flutter appliance trees.

Timeline view

The events show information about Flutter outlines. It involves three fragments, all expanding in commonness.

  • Shape rendering outline:- The outline is populated with singular edges as they are rendered in your application. Each bar in the graph speaks to an edge. The bars are shading coded to include the different pieces of work that happen when rendering a Flutter outline.
  • Shape events outline:- The shape events outline shows the event follows for a solitary edge. The top-most event generates the event underneath it, etc. The UI and GPU events are independent event streams; however, they share a typical course of events (showed at the highest point of the confined graph). This timeline is carefully for the given shape. It doesn’t reflect the clock shared by all edges.
  • CPU profiler:- CPU profiling data for a particular event from the shape events outline (Build, Layout, Paint, and so forth).

Memory view

Allotted Dart objects made utilizing a class constructor live in a part of memory called the pile.

DevTools Memory sheet lets you look at how a disconnect is utilizing memory at a given second. This sheet, utilizing Snapshot and Reset, can show gatherer checks. The aggregators can be utilized to contemplate the pace of memory designations on the off chance that you presume your application is spilling memory or has different bugs identifying with memory portion.

Memory profiling consists of four parts, all expanding in commonness.:

  • Memory overview graph
  • Event timeline
  • Snapshot
  • Class instances

Performance view

The performance view allows you to file records and profile a consultation from your Dart utility.

  • Call Tree:- The call tree view shows the strategy follow for the CPU profile. This table is a top-down illustration of the profile, which means that a way may be expanded to expose its callees.
  • Bottom-Up:- This view indicates the strategy follows for the CPU profile; however because the call shows, it’s a bottom-up representation of the profile. This implies each top-level strategy in the table is really the last technique in the call stack for a given CPU test.
  • Flame chart:- This tab of the profiler shows CPU tests for the recorded span. This outline ought to be seen as a top-down stack follow, where the top-most stack outline calls the one beneath it. The width of each stack outline speaks to the measure of time it expended the CPU. Stack outlines that expend a ton of CPU time might be a decent spot to search for conceivable execution upgrades.

Debugger

DevTools includes a full source-level debugger, breakpoints, stepping, and variable inspection. When you open the debugger tab, you have to see all of the libraries to your utility listed in the bottom left display (beneath the Scripts region), and the supply for the main entry point in your app is loaded in the most important app source region.

So as to peruse around a greater amount of your application sources, you can look through the Scripts region and select other source record to show.

Logging view

Its view shows events from the Dart runtime, application frameworks (like Flutter), and application-level logging events.

4. Launch DevTools from an action -: Search for the Open DevTools activity. At the point when you select that activity, DevTools is introduced (on the off chance that it isn’t as of now), the DevTools server dispatches, and a program case opens highlighting the DevTools application.

At the point when opened with an IntelliJ activity, DevTools isn’t associated with a Flutter application. You’ll have to offer an assistance convention port for an at present running application. You can do this utilizing the inline Connect to a running app dialog.

DevTools with non-Flutter web app

To dispatch a web application so you can utilize Dart DevTools, utilize the webdev serve command with the --debug or --debug-extension flag:

$ webdev serve --debug

DevTools with command-line app

You can utilize DevTools to perform source-level investigating or to see general log and diagnostics data for a running command-line application.

1. Install

Use pub to install DevTools:

$ pub global activate devtools

2. Launch DevTools server

When you have DevTools, utilize the devTools an order to run the local web server for DevTools:

$ pub global run devtools
Serving DevTools at http://127.0.0.1.9100

3. Start the target app

Utilize the dart --observe a command to execute the main file for the Dart command-line application that you need to debug or watch:

$ cd path/to/dart/app
$ dart --observe main.dart
Observatory listening on http://127.0.0.1:8181/wYDP3x9mvbw=/

4. Open DevTools and connect to the target app

  • Open Chrome gateway window and explore to http://localhost:9100.
  • Paste the “listening” URL into the text field under Connect to a running application, and press the Connect button.

Conclusion:

This article would serve as an Exploratory article for Dart DevTools and its working using Flutter. Dart DevTools is an all-important tool in native applications that has now also been introduced in flutter’s latest version also.

I hope this blog has provided you with valuable information about what is all about Dart DevTools, and that you will give it Dart DevTools — a Try. Begin using your apps. Thanks for reading this article ❤

flutter-devs/Dart_DevTools_Demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com

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.


Exploring Threading In Flutter

0

In this article, We are going to learn about Threading In Flutter. Flutter applications start with a single execution process to manage to execute code. Inside this strategy, you will discover various ways that the method handles different bits of code performing simultaneously.

To get a visual understanding through the help of video , Please watch:


Isolates

At the point when Dart starts, there will be one main Isolate(Thread). It is the original main executing thread of the application, alluded to as the UI Thread. Isolates are:

  • Dart’s version of Threads.
  • Isolate memory isn’t shared with each other.
  • Utilizations Ports and Messages to convey between them.
  • May utilize another processor core if accessible.
  • Runs code in parallel.

It secures Flutter apps, you may only ever utilize one Isolate, and your app will run smoothly. Isolates are outstanding in the event you have a long-running assignment that you need to process even as permitting the remainder of your application to run as unrestricted as may want to be anticipated reasonably.

Event Loops & Microtasks

Flutter applications aren’t as necessary as a single step by step line of executing code. You have user clicks, timers, keyboard input, and that’s just the beginning, all wanting to method code. On the off chance that there is only simply one thread, at that factor, then how do these events and code get processed?

The appropriate response is with the Event and Microtask Queue.

The event queue is the pathway for outside assets to pass requests for processing. Every one is dequeued as received and finished. It is a First In First Out (FIFO) queue. A Microtask queue is for code that must be executed asynchronous manner but isn’t from an external source. It might occur after an event has brought about a code that should run before returning manage to the event loop.

The Microtask queue has finish precedence, and the event loop will no longer dequeue from the Event queue until the Microtask queue is empty. It will continuously check the Microtask queue first, before dequeuing off the Event queue.

Code Implementation:

If you run this code via the click of a button in Flutter:

import 'dart:io';

String _data = "";
int clickCount = 0;

Future<void> _buttonClick() async {
var data = _data + "Started $clickCount: ${DateTime.now().toString()}\n";
sleep(Duration(seconds: 2));
data += "End $clickCount: ${DateTime.now().toString()}\n";
clickCount += 1;
setState(() {
_data = data;
});
}

You get the following output after two back to back clicks. Considering my seriously reused state variable there, we can see that it held up until the code ran before the next click occasion has prepared.

Started 0: 2020-05-18 12:47:27.769285 
End 0: 2020-05-18 12:47:29.779730
Started 1: 2020-05-18 12:47:29.784756
End 1: 2020-05-18 12:47:31.785403

Note: You should be about async tasks. As quickly as you definitely use an await, as for instance await Future.delayed(new Duration(seconds: 2));

The event loop will presently become active again. Because an await allows lets in concurrency inside the equal thread, it ought to permit the event loop to proceed, for this reason, the end result of utilizing an await for rather thansleep will appear gradually like this.

Started 0: 2020-05-18 12:47:27.769285 
End 1: 2020-05-15 18:47:31.785403

Ports

In the event that you have to make another thread, that has its own event queue, you need to make a fresh out of the box new Isolate. You can do that utilizing the spawn technique, and This is the low-level approach to compose isolates, utilizing the SendPort and ReceivePort.

import 'dart:async';
import 'dart:isolate';

main() async {
var receivePort = new ReceivePort();
await Isolate.spawn(echo, receivePort.sendPort);

// The 'echo' isolate sends it's SendPort as the first message
var sendPort = await receivePort.first;

var msg = await sendReceive(sendPort, "bye");
print('received $msg');
msg = await sendReceive(sendPort, "hello");
print('received $msg');
}

// the entry point for the isolate
echo(SendPort sendPort) async {
// Open the ReceivePort for incoming messages.
var port = new ReceivePort();

// Notify any other isolates what port this isolate listens to.
sendPort.send(port.sendPort);

await for (var msg in port) {
var data = msg[0];
SendPort replyTo = msg[1];
replyTo.send(data);
if (data == "hello") port.close();
}
}

/// sends a message on a port, receives the response,
/// and returns the message
Future sendReceive(SendPort port, msg) {
ReceivePort response = new ReceivePort();
port.send([msg, response.sendPort]);
return response.first;
}

You will get the following output on running up the code :

$ isolates.dart 
received bye
received hello

You might not use Isolates generally, in many Flutter applications, you are much more likely to stay in one isolate; however, you want asynchronous execution. Asynchronous communication is workable through the async and await ahead to keywords as we will undergo subsequently.

Future with Async & Await

An async and await keywords you may use in Dart, towards a Future. When running async code:

  • It runs in the equivalent Isolate(Thread) that began it.
  • Runs simultaneously (not parallel) at the same time as other code, in the equivalent Isolate(Thread).

It is significant, in that it does not block other code from running in a similar thread. Particularly substantial when you are in the main UI Thread. It will generally help keep your UI smooth while dealing with many events occurring in your code.

Future

Future represents a task on the way to finish or fail sometime within the future, and you’ll notice when. In this easy example, we have a Future, that returns a value. It does so instantly (this is only an example). At the point When you call myFunction(), it provides it to the Event queue to finished. It will proceed with all the synchronous code in the main() function first someOtherFunction(), then start to process each asynchronous call from the Event queue.

If you use Future.delayed or Future.value it actually puts it in the Microtask queue.

import 'dart:async';

Future myFunction() => new Future.value('Hello');

void main() {
myFunction().then((value) => debugPrint(value)); // Added to Microtask queue
myFunction().then((value) => debugPrint(value)); // Added to Microtask queue
someOtherFunction(); // Runs this code now
// Now starts running tasks from Microtask queue.
}

If you want to wait for the function to finish you need to use await.

Async & Await

This simple code will now stop the synchronous execution, while it waits for a result from an asynchronous task.

void mainTest() async {
debugPrint(await myFunction()); // Waits for completion
debugPrint(await myFunction()); // Waits for completion
someOtherFunction(); // Runs this code
}

Embedder

Embedder can be considered as a layer embedding other platforms. The extent of obligation consists of native platform plug-ins, thread control, event loop.

There are Four Runner which is as follows. Each of them Flutter Engine thinks about the next. Yet, allEngineShare onePlatform Runner.

  • UI Runner.
  • GPU Runner.
  • IO Runner.
  • Platform Runner.

UI Runner

UI RunnerResponsible forFlutter EngineimplementRoot IsolateCode, in addition to processing fromNative PluginTasks.Root IsolateMany function methods are bound to handle their own events. When the program starts,Flutter EngineWould beRootbindingUI RunnerProcessing functions, such as the Root IsolateAbility to submit rendered frames.

WhenRoot IsolatetowardsEngineWhen submitting a rendering frame,EngineWaiting for the next vsync, when the next Vsync arrives, byRoot IsolateYesWidgetsLayout operation, and generate the description of the display information of the page, and communicate the data.EngineTo deal with.

Given the rightwidgetsConductlayoutAnd generatelayer treeyesUI RunnerIfUI RunnerA lot of tedious handling will affect the display of the page, so tedious operations should be handed over to others.isolateProcessing, such as fromNative PluginEvents.

GPU Runner

GPU RunnerIt is not directly responsible for rendering operations, but for GPU-related management and scheduling. Whenlayer treeWhen information arrives,GPU RunnerSubmit it to the predefined rendering stage. Skia arranges the rendering stage. Various platforms may have various executions.

GPU RunnerRelatively autonomous, exceptEmbedderNo different threads can submit rendering data to them.

IO Runner

someGPU RunnerFor more time-consuming operations, put them inIO RunnerProcessing, such as image reading, decompression, rendering, and other services. But onlyGPU RunnerToSubmit rendering information to GPU, in order to ensure thatIO RunnerIt also has this ability, soIO RunnerCan be citedGPU RunnerOfcontext It enables you to submit rendering information to the GPU.

Platform Runner

Platform RunnerAnd the iOS platformMain ThreadVery comparative, inFlutterIn addition to time-consuming operations, all tasks should be put inPlatformMedium,FlutterMany of these APIs are not thread-safe and may cause bugs in different threads.

In any case, too long tasks along with IO must be accomplished in various threads, in some other case, they will affect the general performance.PlatformNormal execution, even bywatchdogKill. Regardless, it must be noticed that because of the reality ofEmbedder RunnerMechanisms,PlatformBlocked pages do now, not reason page crashes.

Not justFlutter EngineThe code in thePlatformIn implementation,Native PluginTasks will also be appointed toPlatformIn execution. In fact, the code on the native side runs on thePlatform RunnerIn the middle, but not in the middle.FlutterThe code on the side runs on theRoot IsolateIfPlatformWhen time-consuming code is executed in the framework, the main thread of the native platform will be checked.

Conclusion:

I hope this blog will help you in comprehending out Threading in a flutter by adding a Perfect Competitive niche to your knowledge baseThanks 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.


Explore ARCore in Flutter

0

This article mainly focuses on ARCore and their handling in flutter apps. ARCore is Google’s platform for building augmented reality apps to be made that brings capabilities to millions of cellular devices utilizing extraordinary APIs. It permits your device to locate its surroundings, recognize the arena, and communicate with them. After the arrival of arcore 1.6 with further improvement to assist us with building a more realistic and more compelling augmented reality experience with a lot of updates. A part of the APIs is to be had throughout Android and iOS to permit shared AR reviews. We will integrate ARCore in a flutter with a demo example.

ARCore Uses:

There are three uses to combine digital substance with the present actual world as observed through your device’s camera:

  • Motion trace:- permits the phone to realize and observe with its role comparative with the sector.
  • Surroundings comprehension:- lets in the phone to distinguish the size and place of all forms of surfaces: horizontal, vertical, and calculated surfaces like the ground, a footstool, or walls.
  • Brightness approximation:- allows the device to appraise the surroundings present lights circumstances.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:

arcore_flutter_plugin: latest version

Step 2: Import

import 'package:arcore_flutter_plugin/arcore_flutter_plugin.dart';

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

Minimum Version Requirement:

minSdkVersion to 24 and compileSdkVersion to 28 change in your android/app/buld.gradle file.

Step 4: Enable ARCore

Enable ARCore in the main/Androidmanifest.xml file.

An app that helps AR capabilities may be configured in two methods are:

For AR Required apps

If you want to Playstore to download ARCore whilst the application has established:-

  • The Google Play Store makes AR Required apps available only on devices that assist ARCore.
  • At the point when clients introduce an AR Required application, the Google Play Store consequently introduces Google Play Services for AR. Be that as it may, your app needs to, anyhow, play out extra runtime checks on the off risk that Google Play Services for AR has to be refreshed or has physically uninstalled.
<uses-sdk android:minSdkVersion="24"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera.ar" />
<application …>
<meta-data android:name="com.google.ar.core" android:value="required" />
</application>

For AR Optional apps

If you don’t want Playstore to download ARCore whilst the application has established:-

  • AR Optional applications can be established and run on devices that do not support ARCore.
  • At the factor, when clients introduce an AR Optional application, the Google Play Store won’t consequently introduce Google Play Services for AR with the app.
<uses-permission android:name="android.permission.CAMERA" />
<!-- "AR Optional" apps must declare minSdkVersion ≥ 14. -->
<uses-sdk android:minSdkVersion="14" />
<application …>
<meta-data android:name="com.google.ar.core" android:value="optional" />
</application>

Step 5: Add the Sceneform library

Add this to your app’s build. Gradle file.

android {

compileSdkVersion 28
...
compileOptions {
sourceCompatibility 1.8
targetCompatibility 1.8
}
defaultConfig {
...
minSdkVersion 24
...
}
}
dependencies {
implementation 'com.google.ar.sceneform.ux:sceneform-ux:1.11.0'
// Alternatively, use ArSceneView without the UX dependency.
implementation 'com.google.ar.sceneform:core:1.11.0'
implementation 'com.google.ar:core:1.11.0'
}

Step 6:Enable AndriodX

Add this to your gradle.properties file:

org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true

Supported devices:

A record of the unique phone that is currently supported is indexed proper right there:

  • Android (Google Play)
  • Android (China)
  • iOS

Code Implementation:

In the body part, you will add ArCoreView().

body: ArCoreView(
onArCoreViewCreated: _onArCoreViewCreated,),

Create Controller and use in this_onArCoreViewCreated() method.

ArCoreController arCoreController;

Create _onArCoreViewCreated() method and add all shape in this methods.

_onArCoreViewCreated(ArCoreController _arCoreController){
arCoreController = _arCoreController;
_addSphere(arCoreController);
_addCube(arCoreController);
_addCylinder(arCoreController);
}

In all shape methods, you will add arcore shape and arcore node with position and materials, and you will view on arcore.dartfile.

import 'package:flutter/material.dart';
import 'package:arcore_flutter_plugin/arcore_flutter_plugin.dart';
import 'package:vector_math/vector_math_64.dart' as vector;

class ARCore extends StatefulWidget {
ARCore({Key key, this.title}) : super(key: key);

final String title;

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

class _ARCoreState extends State<ARCore> {
ArCoreController arCoreController;

_onArCoreViewCreated(ArCoreController _arCoreController){
arCoreController = _arCoreController;
_addSphere(arCoreController);
_addCube(arCoreController);
_addCylinder(arCoreController);
}

_addSphere(ArCoreController _arCoreController) {
final material = ArCoreMaterial(color: Colors.deepPurple, );
final sphere = ArCoreSphere(materials: [material], radius: 0.2,);
final node = ArCoreNode(
shape: sphere,
position: vector.Vector3(
0, -0.3, -1
),
);

_arCoreController.addArCoreNode(node);
}

_addCylinder(ArCoreController _arCoreController) {
final material = ArCoreMaterial(color: Colors.green, reflectance: 1);
final cylinder =
ArCoreCylinder(materials: [material], radius: 0.3,
height: 0.1,);
final node = ArCoreNode(
shape: cylinder,
position: vector.Vector3(
-0.3, -1, -1.0
),
);

_arCoreController.addArCoreNode(node);
}

_addCube(ArCoreController _arCoreController) {
final material = ArCoreMaterial(color: Colors.pink, metallic: 1);
final cube = ArCoreCube(materials: [material], size: vector.Vector3(0.5, 0.5, 0.5));
final node = ArCoreNode(
shape: cube,
position: vector.Vector3(
0.5, -3, -3
),
);

_arCoreController.addArCoreNode(node);
}

@override
void dispose() {
arCoreController.dispose();
super.dispose();
}

@override
Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(

title: Text(widget.title),
),
body: ArCoreView(
onArCoreViewCreated: _onArCoreViewCreated,

),
);
}
}

You will see a full code on a GitHub, and this is a small demo example to integrate with ARCore, and this below video shows how ARCore will work and 3d Object shown.

3D Object

Conclusion:

I hope this blog will provide you with sufficient information in Trying up ARCore in your flutter projects. Well, there are various options out there for ARCore, and its a fascinating topic for developers.


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.

Click the GitHub link below to find the source code of the Flutter ARCore Demo.

flutter-devs/flutter_arcore_demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


From Our Parent Company Aeologic

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

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

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

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

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


ember 4, 2023.

Custom Paint In Flutter

0

Flutter has been Quintessential choice among the Developers Fraternity as a reason of the Language’s Ability to Develop Wonderful User Interfaces designs at the Desired frame per second. In this Blog, we’ll try to give you a quick Overview of Flutter and Instruct you to build your flutter app with Custom Paint Design which basically enhance the User Interface of the Application.

Flutter is Google’s UI toolkit for building beautiful, natively compiled applications for mobileweb, and desktop from a single codebase.

For Getting Accustomed with the Flutter basics , You can always go through the video made by google about its Magnificent Framework:

What is the Dire Need to use Custom Paint in Flutter:

Custom Paint basically ensure the UI designing of those components that cannot be derived from the regular shapes provided by Flutter . This widget shows the customizability of flutter from its peers .Custom Painter is :

A widget that provides a canvas on which to draw during the paint phase.

:To paint in Flutter you can use the CustomPaint widget which basically takes size of its parent if not given the child .

  • The CustomPainter subclass overrides two methods: paint() and shouldRepaint().

How to Install Flutter :

Installing Flutter SDK into your device is easily done through with the help of going through the official flutter doc and following the steps provided for your respective windows , Linux, macOS at flutter.dev.

Create a new flutter app

1. Firstly, Create a new project and then clear all the code in the main.dart file. Type below command in your terminal:-

flutter create yourProjectName

Code Implementation:

First, create a class that will be landing page of the module a.k.a CustomPaintExample class.

So, let me walk you through the code to give better understanding of whats happening here. As you can see the UI we’re going to achieve so accordingly, I created a class CustomPaintExample which contains the code for the UI. There are two main elements, the shape and the button animation. The button when pressed increases the value of percentValue by 10 and accordingly the progress on the button border can be seen increasing. The widget is also broken down into two elements CustomPainterExample.buildShape() and CustomPainterExample.buildButtonAnimation() which I created in different class CustomPainterExampleWidgets.

In the Class CustomPainterExampleWidgets, The element CustomPainterExample.buildShape() returns a ClipPath which consists of clipper CustomShapeClass and the other element CustomPainterExample.buildButtonAnimation() consist of a Container with Custom Paint as its child displayed at the Centre of screen .The CustomPaint first asks its painter to paint on the current canvas, then it paints its child, and then, after painting its child, it asks its foregroundPainter to paint. The Percentage increase is shown by the onPressed method at the Raised Button.Let’s understand what foregroundPainter implies. This also illustrate that on choosing painter instead of the foregroundPainter will do the exact opposite.

import 'package:flutter/material.dart';
class CustomShapeClass extends CustomClipper<Path> {
@override
getClip(Size size) {
// TODO: implement getClip
var
path = new Path();
path.lineTo(0, size.height / 4.25);
var firstControlPoint = new Offset(size.width / 4, size.height / 3);
var firstEndPoint = new Offset(size.width / 2, size.height / 3 - 60);
var secondControlPoint =
new Offset(size.width - (size.width / 4), size.height / 4 - 65);
var secondEndPoint = new Offset(size.width, size.height / 3 - 40);
    path.quadraticBezierTo(firstControlPoint.dx, firstControlPoint.dy,
firstEndPoint.dx, firstEndPoint.dy);
path.quadraticBezierTo(secondControlPoint.dx, secondControlPoint.dy,
secondEndPoint.dx, secondEndPoint.dy);
    path.lineTo(size.width, size.height / 3);
path.lineTo(size.width, 0);
path.close();
return path;
}
  @override
bool shouldReclip(CustomClipper oldClipper)
{
return true;
}
}

The CustomShapeClass extending CustomClipper is illustrated above .In this control points and end points are defined in which the quadratic bezier curve is drawn .Now let’s declare the core of the App, ButtonPainter class.

import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class ButtonPainter extends CustomPainter
{
Color buttonBorderColor;
Color progressColor;
double percentage;
double width;
ButtonPainter({this.buttonBorderColor,this.progressColor,this.percentage,this.width});
@override
void paint(Canvas canvas, Size size) {
Paint line = Paint()
..color = buttonBorderColor
..strokeCap = StrokeCap.round
..style = PaintingStyle.stroke
..strokeWidth = width;
Paint complete = Paint()
..color = progressColor
..strokeCap = StrokeCap.round
..style = PaintingStyle.stroke
..strokeWidth = width;
Offset center = Offset(size.width/2, size.height/2);
double radius = min(size.width/2,size.height/2);
canvas.drawCircle(
center,
radius,
line
);
double arcAngle = 2*pi* (percentage/100);
canvas.drawArc(
Rect.fromCircle(center: center,radius: radius),
-pi/2,
arcAngle,
false,
complete
);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}

Here we get the different properties lineColor, which means the color for the track, on which the progress would be drawn, completeColor for the progress finished,completePercent for the level of the progress finished. From its parent widget, we send down this property, here we simply draw.

ButtonPainter extends the class CustomPainter and we need to override its paint method to draw the graphics. To draw, from the start, we need to announce something called Paint, it typifies all the properties that are expected to draw something on the screen. So we have two Paint objects; the first one is a line that speaks to the track line on which the progress would be drawn. We give it a color, that is provided as a property, the strokeCap is round, and we tell the style to be PaintingStyle.stroke as, we don’t need a filled circle we simply need a stroke, at that point set the width to the provided one. So additionally, we announce the complete Paint object for the progress finished.

Thus, from the start, we have to draw a full circle and afterward an arc on it, that is finished.

Offset center  = Offset(size.width/2, size.height/2);
double radius = min(size.width/2,size.height/2);

In these two lines, we calculate the directions for the center of the circle and the radius, its basic, the center is width, and the height of the container divided by 2. We need the center of the circles exactly in the middle. size Is what we get as a parameter in the paint function, which is the size of the container. radius It is the minimum of the half of the width and the height, and now we are taking a minimum of both as the container might not be a square always.

canvas.drawCircle(center,radius,line);

Now we just draw with the drawCircle function called on the provided canvas object, where we go in the center, the radius, and the Paint object.

canvas.drawArc(Rect.fromCircle(center: center,radius: radius),
-pi/2,arcAngle,false,complete);

Now, we figure the angle for the completed arc, which it appeared. I am not going into the geometric calculation. To call drawArc, we need to specify a Rect, which is the bounding box of the arc, we get the Rect encompassing the circle parameters we drew earlier. At that point, we give a beginning angle, which is -pi/2 radians, remember its not 0. The top is -pi/2, 0 is the right-most purpose of the circle. We supply the arcAngle at that point, which is how much the arc should extend as well. We pass in false after that to tell that we don’t want the finish of the arc to be connected back to the center and at last we send in the Paintobject, complete. That’s all we expected to draw using CustomPaint.

Now, let add the animations.

percentageAnimationController = new AnimationController(vsync: this,
duration: new Duration(milliseconds: 1000))
..addListener((){setState(() {
percentage=lerpDouble(percentage,newPercentage,
percentageAnimationController.value);});});

We add the animation on HomePagescreen in initState() method. Then, we have added a listener on the AnimationController which is called at each step of the animation, and we change the percentage. To change the percentage, we get an inserted value with the help of lerpDoublefunction, the value is within percentage and newPercentage which is ten more than the original value, we interpolate it based on the AnimationController’svalue.

We add this line in the onPressed of the button to kick off the animation.

percentageAnimationController.forward(from: 0.0);

You will see a full code on a GitHub, and this is a small circular progress example to integrate with custom paint, and this below video shows how Custom Paint will work.

Hope this blog will provide you with sufficient information in Trying up Custom Paint in your flutter projects .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.

Click the GitHub link below to find the source code of the Custom Paint Demo.

flutter-devs/Custum_Paint_Demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


From Our Parent Company Aeologic

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

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

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

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

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


Razorpay Payment In Flutter

Razor Pay is one of the best payment gateways which provided plugin in a flutter. It was the most straightforward to integrate in-product payment widget that kicked us off with Razorpay yet it was the quick and dependable help for both issue settlement and on-boarding new highlights that have kept us cooperating with them!.

Assemble a protected installment arrangement on your site or portable application with Razorpay and get installments from your clients utilizing different installment techniques on your Checkout structure. You can follow installments at each progression of its life cycle and effectively manage them.

How to Generate API Key

  1. Sign in to your Dashboard with suitable credentials.
  2. Select the mode (Test or Live) for which you need to create the API key
  3. Explore to Settings → API Keys → Generate Key to create a key for the chose mode.

Note:
You need to produce separate API Keys for the test and live modes. No cash is deducted from your record in test mode.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec.yaml file.

dependencies:

razorpay_flutter: latest version

Step 2: Import

import 'package:razorpay_flutter/razorpay_flutter.dart';

Minimum Version Requirement:

For Android, guarantee that the base minimum API level for your app is 19 or higher.

For iOS, guarantee that the base minimum deployment target for your app is iOS 10.0 or higher.Likewise, remember to enable bitcode for your project.

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

Now core concepts of the Razorpay Payment.

You need to implement it in your code respectively:

Create Razorpay instance:

Use this code to create a Razorpay instance.

_razorpay = Razorpay();

Event Listeners:

The plugin utilizes event-based communication and transmits events when payments fail or succeed.

The event names are uncovered using the constants EVENT_PAYMENT_SUCCESSEVENT_PAYMENT_ERROR and EVENT_EXTERNAL_WALLET from the Razorpay class.

Use the on(String event, Function handler) method on the Razorpay instance to append event listeners.

_razorpay.on(Razorpay.EVENT_PAYMENT_SUCCESS, _handlePaymentSuccess);
_razorpay.on(Razorpay.EVENT_PAYMENT_ERROR, _handlePaymentError);
_razorpay.on(Razorpay.EVENT_EXTERNAL_WALLET, _handleExternalWallet);

Handler:

The handlers would be defined in the class and handle the different responses.

In this handler, you can add one more dependencies

fluttertoast: ^latest version

then again run flutter packages get in the root directory of your app.

Setup Options:

Introduce the details in options and pass your Razorpay key Id here. if you don’t have one go here.

To clear event listeners, use the clear method on the Razorpay instance.

_razorpay.clear(); // Removes all listeners

Error Codes:

The error codes have been uncovered as integers by the Razorpay class.

The error code is accessible as the code field of the PaymentFailureResponse the instance passed to the callback.

  1. NETWORK_ERROR: There was a network error. For example, loss of internet connectivity.
  2. INVALID_OPTIONS: An issue with options passed in Razorpay.open.
  3. PAYMENT_CANCELLED: The user canceled the payment.
  4. TLS_ERROR: The device does not support TLS v1.1 or TLS v1.2.
  5. UNKNOWN_ERROR: An unknown error occurred.

Event Names:

The event names have been uncovered as strings by the Razorpay class.

> EVENT_PAYMENT_SUCCESS: The payment was successful.

> EVENT_PAYMENT_ERROR: The payment was not successful.

> EVENT_EXTERNAL_WALLET: An external wallet was selected.

Payment Success Response:

  • Payment IdstringThe ID for the payment.
  • Order IdstringThe order ID if the payment was for an order, otherwise null.
  • Signature:string The signature to be used for payment verification. Only valid for orders, otherwise null.

Payment Failure Response:

=> Codeinteger The error code.

=>Message: string The error message.

External Wallet Response:

Wallet Namestring The name of the external wallet selected.

https://gist.github.com/ShaiqAhmedkhan/ec34b4c903b313b927301761c44c1a6f#file-cart-dart

This is a small bakery flutter example will integrate Razorpay payment, in this code, you will see how to add Razorpay in our code and how to get an order with online payment. This below video shows how Razorpay Payment will work.

So this was the basic example of the Bakery app integrated with Razorpay Payment where we did a simple example and you can learn it and also you can do 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.

Click the GitHub link below to find the source code of the Bakery App integrated with Razorpay.

flutter-devs/Flutter_Bakery_App_Demo
This App has a decent UI as well as we have integrated Razor Payment Gateway — flutter-devs/Flutter_Bakery_App_Demogithub.com


From Our Parent Company Aeologic

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

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

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

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

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


Built-in Explicit Animations in Flutter

0

In our last post, we figured out how to do some marvellous animations movements utilizing Flutter’s staggered animations. AnimatedFoo and TweenAnimationBuilderenabled you to drop some fundamental animations into your application. These animations commonly go one way, “tweening” from a beginning to an end, where they stop. Off-camera, Flutter is taking control, accepting expectations and discarding any requirement for you to stress over the change starting with one thing then onto the next.

This works superbly for some animations objectives, yet in some cases that ever-forward bolt of time leaves us feeling transiently bolted. All in all, as we stop and think about the laws of thermodynamics and the unavoidable warmth demise of the universe, wouldn’t it be decent on the off chance that we could switch time, and do everything once more?

Transition widgets are a lot of Flutter widgets whose names all end in — you speculated it — Transition. ScaleTransitionSizeTransition DecoratedBoxTransition, and that’s just the beginning. They look and feel a great deal like our AnimateBlah widgets. PositionedTransition, for example, animates a widget’s progress between various positions. This is a lot of like, however, there is one significant contrast: these Transition widgets are augmentations of AnimatedWidget. This makes them explicit animations.

An image of Sun(GalaxyWay) just sitting on the galaxy, not rotating

RotationTransition

The RotationTransition widget is a helpful one that deals with the entirety of the trigonometry and changes math to make things turn. Its constructor just takes three things:

// [Most of] RotationTransition’s constructor
RotationTransition({
Widget child,
Alignment alignment,
Animation<double> turns,
})

child — the widget we need to turn. The galaxy way, so we’ll put it there: Next, we have to give RotationTransition the point our sun turns around. Our sun is generally in the centre of the picture where we’d ordinarily anticipate. Along these lines, we’ll give an arrangement of focus, making the entirety of our rotational math “adjusted” to that point.

RotationTransition(
turns: _repeatingAnimationLong,
child: GalaxyWay(),
alignment: Alignment.center,
),

Not to stress! This is a piece of what makes RotationTransition and the various Transition widgets, an explicit animation. We could achieve a similar rotation impact with an AnimatedContainer and a change, however then we’d turn once and afterwards stop. With our explicit animations movements, we have control of time and can make it so our sun spins constantly.

The turns property expects something that gives it a value and educates it when that value changes. An Animation<double> is just that. For RotationTransition, the value analyzes how regularly we’ve turned, or even the more explicitly, the level of one revolution finished.

Creating an AnimationController

Perhaps the most effortless approaches to get an Animation<double> is to make an AnimationController, which is a controller for animation. This controller handles tuning in for ticks¹ and gives us some helpful powers over what the movement is doing.

We’ll have to make this in a stateful widget since keeping an idea about the controller will be significant in our imminent future. Since AnimationController likewise has its own state to manage, we initialize it in initState, and dispose of it in dispose().

There are two parameters we should provide for Animation Controller’s constructor. The first is a length, which is to what extent our explicit animation movement keeps going. The entire explanation we’re here is that we need an article to disclose to us how far along we are in a solitary revolution. Of course, AnimationController “emits” values from 0.0 to 1.0. What number of and how granular those qualities are relied upon to what extent we need a single rotation to take. Luckily, Dart gives us a Duration class to utilize. For this demo, we should have the sun turning somewhere close to 5 seconds and 230 million years for every revolution. What about 15 seconds for each turn at that point?

_animationController = AnimationController(
duration: Duration(seconds: 15),
// TODO: finish constructing me.
);

On the off chance that we left things at that, not a lot occurs. That is on the grounds that we’ve been given a controller, yet haven’t pressed any of its buttons! We need our sun to turn forever, isn’t that so? For that, we’ll simply ask the controller to continually repeat the animation movement.

_animationController = AnimationController(
duration: Duration(seconds: 15),
vsync: this,
)..repeat();

Making use of an AnimationController

Allowing anybody to control the sun appears to be a piece excessively lenient, however, so I’m going to make it an easter egg. I’ll add a sibling to the sun that is a basic button, covered up off background in the animation, and I’ll pass it a reference to our controller so that inside its onTap listener, we can stop or restart the movement.

The controller maintains — among other things — the status of the animation, which we can check and stop in case we’re running or restart in case we’re definitely not. What’s more, there you go! By utilizing an animation controller, we’re ready to control the animation movement on request. In any case, that is not everything you can do with the controller.

With it, you can likewise animate to (or in reverse from) a particular value, flying the animation movement forward with a given speed, or control various animations with a similar controller.

This was only our first taste of explicit animations in Flutter. We saw how a Transition widget functionsAnimationControllerto give some directionality and command over how our animation functions. In future posts, we’ll be jumping further into explicit animations and how to get considerably more altered.

here in the video posted below, you will see how explicit animation was working and when you tap anywhere in that screen then it pause the animation and the whole animation will freeze and then you tap again anywhere in that screen then it resumes animation, you can control the speed of animation and also the movement of directions.

So this was the basic example of Explicit Animation where we did a simple example and you can learn it and also you can do 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.

Click the GitHub link below to find the source code of the Explicit Animation.

flutter-devs/ExplicitAnimations
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


From Our Parent Company Aeologic

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

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

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

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

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


Staggered Animation In Flutter

0

A staggered animation includes consecutive or covering animations.To make an staggered animation, to utilize a few/couple of Animation items.One Animation Controller controls all the Animations.Each Animation object shows the movement at some point or another of an Interval.For each preferred position being animated, make a Tween.

Staggered animations movements are a direct idea: visual changes occur as a progression of tasks, instead of at the same time. The activity may be simply consecutive, with one change occuring after the following, or it may somewhat or totally cover. It may likewise have holes, where no progressions happen.

Here is the demo video you can take a look staggered animationhttps://www.youtube.com/embed/0fFvnZemmh8?feature=oembed

In this video, you will see the accompanying animation movement of a single widget, which starts as a bordered blue square with marginally adjusted corners. The square runs they will blur and afterward change in square was broaden in measure and afterward square becomes taller while moving upwards and they will changes into an outskirt circle and the progressions shading blue to orange,after walking forward, the activity runs backward.

Structure of a staggered animation

The entire of the animations are pushed by methods for a similar Animation Controller.Regardless of the way extensive the animation movement keeps going in genuine time, the controller’s qualities should be among zero.0 and 1.0, comprehensive.

Every animation movement has an Interval among zero.Zero and 1.0, comprehensive.

For every having a place that animates in an interval, make a Tween. The Tween determines the beginning and give up values for that assets.The Tween produces a Animation thing that is made do with the guide of the controller.

To set up the animation:

  • Make a Animation Controller that deals with every one of the Animations.
  • Make a Tween for each having a place being animated.
  • The Tween characterizes different values.
  • The Tween’s animate technique requires the decide controller, and produces a Animation for that assets.
  • Determine the interval time frame at the Animation’s curve assets.

How to use Staggered animation in Flutter:

The following code makes a tween for the avatarSize property. It constructs a CurvedAnimation, determining an elasticOut curve. See Curves for other accessible pre-characterized animation Curves.

avatarSize = Tween<double>(
begin: 50.0,
end: 150.0,
).animate(
CurvedAnimation(
parent: controller,
curve: Interval(
0.125, 0.250,
curve: Curves.elasticOut,
),
),
),

Animation controller and Animation define an instance of the class AnimationController for the animation controller and five instances of the class Animation to handle animations (double to get a progressive value from 0 to 1).

final AnimationController controller;
final Animation<double> barHeight;
final Animation<double> avatarSize;
final Animation<double> titleOpacity;
final Animation<double> textOpacity;
final Animation<double> imageOpacity;

Animation initializing override the initState method and define the parameters for the animation. For this situation, the duration is set to three seconds.

_controller = AnimationController(
duration: const Duration(milliseconds: 3500),
vsync: this,);

How to implement in dart file:

You need to implement it in your code respectively:

This stateful widget, Staggered Trekking Animation add as a mixin the SingleTickerProviderStateMixin and makes the AnimationController was determining a 3500 ms duration. It will plays the animation movement and builds the non-animating portion of the widget. The animation start when a tap is distinguished in the screen. The animation movement runs forward and then reverse automatically.

https://gist.github.com/ShaiqAhmedkhan/99acdd5d7303e8711c3bd17cacd75d05#file-staggered_trekking_animation-dart

In Staggered Trekking Enter Animation, using the tween’s current values and next you will make a Stateless widget,Staggered Trekking make a build() function an AnimatedBuilder—this widget for building animations. We create a function named _buildAnimation() and it work UI updates and assigns it to its builder property.

https://gist.github.com/ShaiqAhmedkhan/cb4e10462a536eeaf01cc2def10b4578#file-staggered_trekking_enter_animation-dart

AnimatedBuilder will listen to the notifications from the animation controller will marking the widget for the values change. For each tick of the animation, the values were updated, resulting in a call to _buildAnimation().

here in the video posted below, you will see how staggered animation were working and when you tap anywhere in that screen it starts animation and run reverse automatically animation, you can control the speed of animation also.

So this was the basic example of Staggered Animation where we did a simple example and you can learn it.

Click the GitHub link below to find the source code of the Staggered Animation.

flutter-devs/Flutter-StaggeredAnimation
You can’t perform that action at this time. You signed in with another tab or window. You signed out in another tab or…github.com


From Our Parent Company Aeologic

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

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

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

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

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


Parsing JSON in Flutter

0

For those of you who do not know what is Flutter then

Flutter is an open-source mobile application development SDK created by Google. It is used to develop applications for Android and iOS.

or you can visit https://flutter.dev

let’s talk about JSON parsing in flutter.

I know it is really confusing for beginners to understand how to parse JSON data.

Let’s Start with a JSON example

Suppose I want to access the articles list but the articles have many attributes and we need to parse the article array into our app.

Let’s see what we have in the article

So How we are going to do that?

Step 1: Create a PODO

First of all, we have to create a PODO (Plain Old Dart Object) for a particular article.

To access source in the Article we also have to create a PODO for Source.

https://gist.github.com/ashishrawat2911/c5eeb2f47a7b24b437670f1aeacf81ef#file-article-dart

Step 2: Make the network request

I am using the NewsApi to retrieve the JSON data

I have the URL and I want the response when I request to the URL.

Step 3: Decode the response

Now I have the response I can get the list of articles.

If you are an android developer and you know the traditional way of parsing the JSON data then you must remember that first we retrieve the JSON data and get the JSON array then iterate the JSON array and map to the Java objects we have done the same here.

var rest = data["articles"] as List;

Now the rest will have the JSON array and we will iterate the JSON array and map to the Dart objects.

Step 3: Map the JSON objects to Dart Objects

Complete method of parsing the JSON array

https://gist.github.com/ashishrawat2911/8a8cd94761b491e6876c8b1308f0cb78#file-jsonmethod-dart

Complete code.

https://gist.github.com/ashishrawat2911/0787c959bd151270bef9bee7ad546b37#file-newsjson-dart

The final app will look like this:

If you still have any problem, I have linked my Github Repo

ashishrawat2911/Flutter-NewsWeb
Contribute to ashishrawat2911/Flutter-NewsWeb development by creating an account on GitHub.github.com

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.
Connect with me on Linkedin and Github


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.


Cupertino (iOS-style) ActionSheet in Flutter | Know Your Widgets

0

This is the first article of our Know Your Widgets series.

Know Your Widgets is a brand new series in which we’ll be explaining all the important widgets that you should know when starting to develop applications in Flutter.

We have decided to dive into all the flutter widgets and try to explain each one to you.

In this article, I am going to show you How to use CupertinoActionSheet.

If you are wondering what is Cupertino then

Cupertino in Flutter is a set of widgets implementing the current iOS design language.

Have a look

Cupertino ActionSheet

An action sheet is a specific style of alert that presents the user with a set of two or more choices related to the current context.

An action sheet can have a title, an additional message, and a list of actions. The title is displayed above the message and the actions are displayed below this content.

This action sheet styles its title and message to match standard iOS action sheet title and message text style.

First of all, we need to import the Cupertino package

package:flutter/cupertino.dart

Everything in flutter is a Widget so is CupertinoActionSheet, we can use it anywhere in the layout but we want our ActionSheet to show it in with a modal sheet.

So we will use

showCupertinoModalPop

In this, we have two required parameters

@required BuildContext context,
@required WidgetBuilder builder,

Now

showCupertinoModalPopup( 
context: context,
builder: (BuildContext context) => CupertinoActionSheet());

In CupertinoActionSheet we have title:, message: and actions:

CupertinoActionSheet(                                 
title: const Text('Choose Options'), message: const Text('Your options are'), actions: <Widget>[]
);

Inside actions: <Widget>[] we will list all the options that we are required to show.

To show a particular option item in the actions: <Widget>[] , we will use a CupertinoActionSheetAction()widget.

CupertinoActionSheetAction( 
child: const Text(‘Option 1’),
onPressed: () {
//do some action
}
);

We can add as many as CupertinoActionSheetAction()inside actions: <Widget>[].

Now the code will look like this

showCupertinoModalPopup(
context: context,
builder: (BuildContext context) => CupertinoActionSheet(
title: const Text('Choose Options'),
message: const Text('Your options are '),
actions: <Widget>[
CupertinoActionSheetAction(
child: const Text('One'),
onPressed: () {
Navigator.pop(context, 'One');
},
),
CupertinoActionSheetAction(
child: const Text('Two'),
onPressed: () {
Navigator.pop(context, 'Two');
},
)
],
),
);
CupertinoActionSheetAction in CupertinoActionSheet

In CupertinoActionSheet()

we also have cancel button parameter in, it just separates a single option with other options inactions: <Widget>[]

cancelButton: CupertinoActionSheetAction(            
child: const Text('Cancel'),
isDefaultAction: true,
onPressed: () {
Navigator.pop(context, 'Cancel');
},
)),

it will look like this

Cancel in CupertinoActionSheet

Now Let’s see the actual code

showCupertinoModalPopup(
context: context,
builder: (BuildContext context) => CupertinoActionSheet(
title: const Text('Choose Options'),
message: const Text('Your options are '),
actions: <Widget>[
CupertinoActionSheetAction(
child: const Text('One'),
onPressed: () {
Navigator.pop(context, 'One');
},
),
CupertinoActionSheetAction(
child: const Text('Two'),
onPressed: () {
Navigator.pop(context, 'Two');
},
)
],
cancelButton: CupertinoActionSheetAction(
child: const Text('Cancel'),
isDefaultAction: true,
onPressed: () {
Navigator.pop(context, 'Cancel');
},
)),
);

Now You are good to go

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.


Know Your Widgets: Container in Flutter

0

If you are new to flutter you must be wondering what is Container then,

A Container is a convenience widget that combines common painting, positioning, and sizing widgets.

You can use Container to any widgets to add some styling properties.

Let’s look into the parameters of a container.

Container({
Key key,
this.alignment,
this.padding,
Color color,
Decoration decoration,
this.foregroundDecoration,
double width,
double height,
BoxConstraints constraints,
this.margin,
this.transform,
this.child,
})

That’s a lot of properties, but no worries we have everything sorted.

Let’s dive into each and every property.

Color :

Center(
child: Container(
color: Colors.amber,
),
),

Child :

We can only add one child to the Container as it is a Single-child layout widget.

Container(
color: Colors.amber,
child: FlutterLogo(
size: 400,
),

),
)

Alignment Property:

You can use Alignment, FractionalOffset, and AlignmentDirectional class for the alignment property in Container.

Alignment

In Alignment (0,0) means the center of the screen so if you assign Alignment(0,0) to the alignment property then it will be on the center of the screen.

Container(
color: Colors.amber,
child: FlutterLogo(
size: 200,
),
alignment: Alignment(0, 0),
),
)
Container(
color: Colors.amber,
child: FlutterLogo(
size: 200,
),alignment: Alignment(1.0, 1.0),
)
Container(
color: Colors.amber,
child: FlutterLogo(
size: 200,
),alignment: Alignment(-1.0, -1.0),
)
child: Container(
color: Colors.amber,
child: FlutterLogo(
size: 200,
),alignment: Alignment(1.0, -1.0),
)
Container(
color: Colors.amber,
child: FlutterLogo(
size: 200,
),alignment: Alignment(-1.0, 1.0),
)

You can use constants that are already defined by Alignment Class.

Example:

Container(
color: Colors.amber,
child: FlutterLogo(
size: 200,
),alignment: Alignment.bottomRight,
)

There are many other constants :

// The top left corner.
static const Alignment topLeft = Alignment(-1.0, -1.0);
// The center point along the top edge.
static const Alignment topCenter = Alignment(0.0, -1.0);
// The top right corner.
static const Alignment topRight = Alignment(1.0, -1.0);
// The center point along the left edge.
static const Alignment centerLeft = Alignment(-1.0, 0.0);
// The center point, both horizontally and vertically.
static const Alignment center = Alignment(0.0, 0.0);
// The center point along the right edge.
static const Alignment centerRight = Alignment(1.0, 0.0);
// The bottom left corner.
static const Alignment bottomLeft = Alignment(-1.0, 1.0);
// The center point along the bottom edge.
static const Alignment bottomCenter = Alignment(0.0, 1.0);
/// The bottom right corner.
static const Alignment bottomRight = Alignment(1.0, 1.0);

FractionalOffset

You can also user FractionalOffset with the alignment property of the Container.

In FractionalOffset, (0,0) means the top left of the screen so if you assign Alignment(0,0) to the alignment property then it will be on the top left of the screen.

FractionalOffset(double dx, double dy)

Example:

Container(
color: Colors.amber,
child: FlutterLogo(
size: 200,
),alignment: FractionalOffset(0,0),
)

You can use constants that are already defined by FractionalOffset Class.

Example:

Container(
color: Colors.amber,
child: FlutterLogo(
size: 200,
),alignment: FractionalOffset.topLeft,
)

There are many other constants :

/// The top left corner.
static const FractionalOffset topLeft = FractionalOffset(0.0, 0.0);
/// The center point along the top edge.
static const FractionalOffset topCenter = FractionalOffset(0.5, 0.0);
/// The top right corner.
static const FractionalOffset topRight = FractionalOffset(1.0, 0.0);
/// The center point along the left edge.
static const FractionalOffset centerLeft = FractionalOffset(0.0, 0.5);
/// The center point, both horizontally and vertically.
static const FractionalOffset center = FractionalOffset(0.5, 0.5);
/// The center point along the right edge.
static const FractionalOffset centerRight = FractionalOffset(1.0, 0.5);
/// The bottom left corner.
static const FractionalOffset bottomLeft = FractionalOffset(0.0, 1.0);
/// The center point along the bottom edge.
static const FractionalOffset bottomCenter = FractionalOffset(0.5, 1.0);

AlignmentDirectional

You can also user AlignmentDirectional with the alignment property of Container

AlignmentDirectional(this.start, this.y)

An offset that’s expressed as a fraction of a Size, but whose horizontal component is dependent on the writing direction.

Container(
color: Colors.amber,
child: FlutterLogo(
size: 200,
),alignment: AlignmentDirectional(-1,1),
)

You can use constants that are already defined AlignmentDirectional Class

Example:

Container(
color: Colors.amber,
child: FlutterLogo(
size: 200,
),alignment: AlignmentDirectional.topEnd,
)

There are many other constants :

/// The top corner on the "start" side.
static const AlignmentDirectional topStart = AlignmentDirectional(-1.0, -1.0);
/// The center point along the top edge.
///
/// Consider using [Alignment.topCenter] instead, as it does not need
/// to be [resolve]d to be used.
static const AlignmentDirectional topCenter = AlignmentDirectional(0.0, -1.0);
/// The top corner on the "end" side.
static const AlignmentDirectional topEnd = AlignmentDirectional(1.0, -1.0);
/// The center point along the "start" edge.
static const AlignmentDirectional centerStart = AlignmentDirectional(-1.0, 0.0);
/// The center point, both horizontally and vertically.
///
/// Consider using [Alignment.center] instead, as it does not need to
/// be [resolve]d to be used.
static const AlignmentDirectional center = AlignmentDirectional(0.0, 0.0);
/// The center point along the "end" edge.
static const AlignmentDirectional centerEnd = AlignmentDirectional(1.0, 0.0);
/// The bottom corner on the "start" side.
static const AlignmentDirectional bottomStart = AlignmentDirectional(-1.0, 1.0);
/// The center point along the bottom edge.
///
/// Consider using [Alignment.bottomCenter] instead, as it does not
/// need to be [resolve]d to be used.
static const AlignmentDirectional bottomCenter = AlignmentDirectional(0.0, 1.0);
/// The bottom corner on the "end" side.
static const AlignmentDirectional bottomEnd = AlignmentDirectional(1.0, 1.0);

Constraint Property:

Container(
color: Colors.amber,
child: FlutterLogo(
size: 200,
),
alignment: Alignment.center,
constraints: BoxConstraints(
maxHeight: 400,
maxWidth: 400,
minHeight: 100,
minWidth: 100,
),

)

Decoration Property:

The decoration parameter is to paint behind the child.

We can use the BoxDecoration class to decorate the container.

To know more about B0xDecoration I have linked a blog below.

Flutter — BoxDecoration Cheat Sheet

Margin Property:

A margin is a property specifying to add space to surround the container.

We do it with EdgeInsets.

EdgeInsets.all

EdgeInsets.all(double value)

Example :

Container(
alignment: Alignment.center,
color: Colors.amber,
child: FlutterLogo(
size: 200,
),margin: EdgeInsets.all(50),
)

EdgeInsets.symmetric

EdgeInsets.symmetric({ double vertical = 0.0,
double horizontal = 0.0 })

Example:

Container(
alignment: Alignment.center,
color: Colors.amber,
child: FlutterLogo(
size: 200,
),
margin: EdgeInsets.symmetric(horizontal: 70, vertical: 30),
)

EdgeInsets.fromLTRB :

EdgeInsets.fromLTRB(this.left, this.top, this.right, this.bottom)

Example :

Container(
alignment: Alignment.center,
color: Colors.amber,
child: FlutterLogo(
size: 200,
),
margin: EdgeInsets.fromLTRB(20, 30, 40, 50),
)

EdgeInsets.only:

EdgeInsets.only({
this.left = 0.0,
this.top = 0.0,
this.right = 0.0,
this.bottom = 0.0
});

Example :

Container(
alignment: Alignment.center,
color: Colors.amber,
child: FlutterLogo(
size: 200,
),
margin: EdgeInsets.only(left: 70, bottom: 50),
)

Padding Property :

When we add padding to a widget, we just add space inside of a widget, unlike margin which adds space outside the widget.

Container(
alignment: Alignment.center,
color: Colors.amber,
child: FlutterLogo(
size: 200,
),
padding: EdgeInsets.only(left: 70, bottom: 50),
)

Before and after padding

EdgeInsets properties will be the same as of margin.


You must have got an overview of a Container widget.

Now you are good to go.

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.