Home Blog Page 18

Dependency Injection in flutter using get it package

0
flutter dependencies injection
dependencies injection in flutter

Making an object’s dependencies, which are typically referred to as services, accessible through another object is a technique called dependency injection.

A quick search of the Dependency Injection in Flutter Community will give you a list of articles. All are very informative and offer libraries and service locators to implement Dependency Injection in flutter . This post will offer an alternative to implementing code and or annotations to supplying  DI in flutter app .

What Is Dependency Injection ?

Dependency Injection (DI) is a technique used to increase code reuse by reducing tight coupling between classes. The dependent classes and objects are supplied to or injected into your class rather than being created or instantiated by your class, maintaining a sort of external library to create and manage object creation in your project. These classes can now clearly concentrate on their actual application logic because you have decoupled object creation from your actual view and model. Furthermore, some of the classes that we construct are singletons as a result of you as well.


Why does Flutter use Dependency Injection?

so as to increase code reuse by reducing coupling between classes.

to design a class that is not dependent on anything else.

Additionally, it lessens the possibility that you will need to modify a class simply because one of its dependencies changed.
A class can become independent of its own dependencies by using dependency injection. Because every class can call any dependencies it requires, you can divide your application’s various components into more easily maintainable sections. By doing this, a loosely coupled application is produced, making it easier and quicker to fix bugs and add new features.


Advantages of dependency injection

Applications built with Flutter can benefit greatly from dependency injection. Some of the main advantages are as follows:

  1. The injection is offered everywhere.
  2. This method automatically tracks instances.
  3. Registration against interfaces is feasible.
  4. The streamlined setup code can be used.

Disadvantages of Dependency injection

While dependency injection has a number of advantages, there are also some potential disadvantages to take into account:

1): The top priority for dependency injection techniques is not disposing .

2) :It complies with lazy coding standards which makes development challenging  .

3): The fact that it is a global object adds to the complexity .

Overall, in spite of the fact that dependency injection can have many benefits. it may not always be the best choice but Before deciding whether dependency injection is the best course of action for your specific use case. It is necessary to consider its advantages and disadvantages.


Now implement the other side….. 

By developing a sample app, we will show you how to using  GetIt and Injectable to implement dependency injection in your  Flutter application . We will discuss the following :

Why use GetIt and Injectable?

This is a simple Service Locator for Dart and Flutter projects that includes some extra goodies that were heavily influenced by Splat. It can be used to access objects, such as those in your UI, instead of InheritedWidget or Provider.

Common Dependency Injection Techniques include:

i): The fundamental strategy we use to inject dependencies using constructors.

ii):  A class called Inherited Injection should extend from inherited widgets. (But passing objects without context becomes complex in this technique)

Now , implement Dependency Injection Through GetX

Installation

Step 1): Add this following dependencies project pubspec.yaml file:

get_it: ^any
get: ^any

Step 2): Then import it. after installing the package using the terminal command line:

flutter pub get

Step 3): import the file

import 'package:get_it/get_it.dart';

Step 4):  Create a locator.dart file :

Create a get_it instance

GetIt locator = GetIt();

Add this

import 'package:get_it/get_it.dart';

void setupLocator()
{
 /// doo here your logic
}

Step 5) : Use this given code and  set in the your project directory main.dart file to import locator and you can continue :

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

 When creating locators there are two ways to register class types using get_it . thorough explanation of this is provided below:

i) Factory: Each time your request for an instance of this class type is processed by the service provider, you will receive a fresh instance. This technique works well for registering view models that must execute the same logic upon startup or for models that must be fresh upon view opening.

ii) Singleton: You have two options for registering this method. You can either provide an implementation at the time of registration or a lama that will be called the first time your instance is requested. When this method is called, the locator will always return the single instance of your registered type that it has stored.

To register your classes, add a locator.dart file or use the code below:

void setupLocator()
{
// Add class here
locator.registerFactory(()=>AppInfo());
}

Step 7) : Next….. use the given code to add injectors or locators to the application screens:

var appInfo = locator<AppInfo>();

Usage

We have add dependency injection using getx

GetX Dependency Injection Techniques Have These Benefits:

  1. The streamlined setup code can be used.
  2. Registration against interfaces is feasible.
  3. Injection is accessible everywhere.
  4. This method automatically tracks instances.

To inject the object of the class use Get.put

When this method is used the dependency will load immediately and can be used directly by implementing below code 

 HomeController homeController = Get.put(HomeController());

Use “Get.find” to locate the controller in our application lifecycle following injection.

When multiple shared instances need to be updated separately, we can also use the Get.find tag property. Use the following code to accomplish this:

 HomeController homeNextController = Get.put(HomeController());

If the route using Get.put is removed from the navigation stack, the dependencies will also be deleted. Therefore, we must stop this from happening and maintain the dependencies in internal memory for the duration of the app session using permanent properties, as demonstrated below:

Get.put(Controller(), permanent: true);

The main three types of dependency injection are:

  • 1 Constructor Injection
  • 2 Property Injection
  • 3 Method Injection
1) Constructor Injection

a class’s function Object() is used to send dependencies to it ,  For an example  the class’s Object() function would accept the service as a parameter if the class required an instance of the authentication service.

class AuthenticationService {
  // Authentication service implementation
}
class UserRepository {
  AuthenticationService authService;
  UserRepository(this.authService);
  /// UserRepository implementation
}
2) Property Injection

Dependencies are set as properties of a class in the property injection method. For an example you would create a property for the service and set it when creating an object of the class .  if your class required an instance of an authentication service.

class AuthenticationService {
  ///  Authentication service implementation
}

class UserRepository {
  AuthenticationService authService;
  setAuthenticationService(AuthenticationService authService) {
    this.authService = authService;
  }
  /// UserRepository implementation
}
3) Service Locator

An object called a service locator keeps track of dependencies and gives users access to them. In this method  you would call up instances of dependencies as needed using a service locator.

class AuthenticationService {
  /// Authentication service implementation
}

class UserRepository {
  /// UserRepository implementation
}

class ServiceLocator {
  AuthenticationService getAuthenticationService() {
    return AuthenticationService();
  }

  UserRepository getUserRepository() {
    UserRepository repository = UserRepository();
    repository.setAuthenticationService(getAuthenticationService());
    return repository;
  }
}

Inside the global getIt object, we specified Auth as the actual implementation of AuthRepository.

With getIt, we can now access AuthRepository from anywhere in our UI code:

Future<void> _onClickSignIn() async {
  await getIt<AuthRepository>().signIn(email, password);
}
/// here add gorilllas app to appstate method


let’s start

Step 1): Create a UserData model :

class UserData {
  String name;
  String email;

  UserData({required this.name, required this.email});
}

Step 2): Create an interface for the UserRepository

abstract class UserRepository {
  Future<UserData> getUserData();
  Future<void> setUserData(UserData userData);
}

Step 3): The UserRepo known as UserRepository was injected . That uses  GetStorage in our application to store and retrieves the  user data.

import 'package:get_storage/get_storage.dart';
import 'user_data.dart';

class UserRepositoryImpl implements UserRepository {
  final storage = GetStorage();

  @override
  Future<UserData> getUserData() async {
    final data = storage.read('userData');
    if (data != null) {
      return UserData.fromJson(data);
    } else {
      return UserData(name: '', email: '');
    }
  }

  @override
  Future<void> setUserData(UserData userData) async {
    await storage.write('userData', userData.toJson());
  }
}

Step 4 ): Create a class that uses UserRepository to manage user data. Calling UserDataController now

import 'package:get/get.dart';
import 'package:get_it/get_it.dart';
import 'user_data.dart';
import 'user_repository.dart';

class UserDataController extends GetxController {
  final UserRepository _userRepository = GetIt.I<UserRepository>();
  Rx<UserData> userData = UserData(name: '', email: '').obs;

  @override
  void onInit() {
    super.onInit();
    getUserData();
  }

  Future<void> getUserData() async {
    userData.value = await _userRepository.getUserData();
  }

  Future<void> setUserData(UserData userData) async {
    await _userRepository.setUserData(userData);
    this.userData.value = userData;
  }
}

In this class we use GetIt inject the UserRepository instance and we use Rx<UserData> to make the user data observable .

Step 5): Establish dependencies Put it in the main Dart file:

import 'package:get_it/get_it.dart';
import 'user_repository.dart';
import 'user_repository_impl.dart';

void main() {
  GetIt.instance.registerLazySingleton<UserRepository>(() => UserRepositoryImpl());
  runApp(MyApp());
}

For this example code click here 👍

Conclusion

Flutter’s use of DI makes it simple to manage dependencies, testability, and provides a more scalable architecture. Dependencies can be easily swapped out during testing, mocked, or even have different implementations depending on the environment thanks to DI.

Overall, implementing DI in Flutter can result in cleaner, more maintainable code, aid in code separation and organization, and make it simpler to collaborate on bigger projects with multiple team members.

Is this a small example of dependency injection in flutter , you can modify this code by your needs.

Thanks for reading this article….. ❤️‍

Have a nice day…..

A Deep Dive into Flutter pdf package

0
flutter pdf

The PDF ( Portable Document Format) package is a  file format . software technology that enables reliable electronic document exchange and  display regardless of software, hardware and operating system. For many , different things, including electronic books, forms, manuals and PDF files are more used.

Programmers can create, edit, view and share PDF files with the use of the features and tools provided by the flutter PDF package.

Developers can work with PDF files in their Flutter applications thanks to the PDF package for Flutter, which is a collection of libraries. Developers can add annotations, images, and other components to PDF documents as well as create, read, and edit PDF files using the PDF package. Additionally, the package contains tools for rendering PDF files in Flutter programmers and for supporting zooming, panning, and scrolling inside PDF files. The PDF package for Flutter is a complete solution for working with PDF files in Flutter applications because it also supports security features like passwords and encryption.

Step 1): Configuring our pubspec.yaml

pdf: ^any

Step 2): installing the package

flutter pub get

Step 3): import the file

import 'package:pdf/pdf.dart';

Using the tools or features offered by the flutter  PDF package, users can create, edit, view, and share PDF files. Several significant features of the PDF package include:

Creation of PDF files:

The library enables programmers to create new PDF files , add pages with different page formats (like A4 size ), and embellish the pages with widgets like text, images, tables and charts etc.

/// Create a new PDF file
final pdf = pw.Document();

/// Add a new page in to the PDF document
pdf.addPage(
  pw.Page(
    pageFormat: PdfPageFormat.a4,
    build: (pw.Context context) {
      return pw.Center(
        child: pw.Text("PDF package explanation", style: pw.TextStyle(fontSize: 24)),
      );
    },
  ),
);

// Save the PDF document to disk
final bytes = await pdf.save();
final file = File('output.pdf');
await file.writeAsBytes(bytes);

With the help of the pdf library this code creates a new PDF file, adds a page, changes the page format to A4 size adds a centered text widget to the page and then save the PDF file to local storage under the name “pdfName.pdf.” In addition to supporting the addition of images, tables, charts, and annotations as well as fonts, colors, and styles, the pdf library provides many more features for working with PDF files.


Editing of PDF files:

// Open an existing PDF file
final bytes = File('input.pdf').readAsBytesSync();
final pdf = pw.Document().loadFromBytes(bytes);

// Get the first page of the PDF file
final page = pdf.pages[0];

// Modify the text on the first page of the PDF file
page.addText(
  pw.Text(
    'Modified text',
    style: pw.TextStyle(fontSize: 24),
  ),
);

// Save the modified PDF file to disk
final modifiedBytes = await pdf.save();
final modifiedFile = File('output.pdf');
await modifiedFile.writeAsBytes(modifiedBytes);

This code retrieves the first page of an existing PDF file from storage using the pdf library , modifies the text on that page and then saves the modified PDF file to storage with the name pdfName .pdf extention . The pdf library offers tools for adding and editing images, tables and annotations highlights , underlines etc…… as well as support for changing the font, color, and style.


Conversion of PDF files:

The Flutter pdf package also includes tools for converting PDF files to other formats like image, HTML or text etc……  Here is an example of code that turns a PDF file into an image using the pdf library:

/// Open an existing PDF file here
final bytes = File('input.pdf').readAsBytesSync();
final pdf = pw.Document().loadFromBytes(bytes);

/// Convert the PDF file to an image format
final image = await pdf.asImage(
  format: PdfPageFormat.a4,
  dpi: 300,
);

/// Save the image to storage
final pngBytes = await image.pngBytes;
final pngFile = File('output.png');
await pngFile.writeAsBytes(pngBytes);

The user can choose a PDF file have it converted file to an image and then see the image as a result of their selection in this code definition of a Flutter application with a single page. The PDF file is converted to a PNG image using the pdf library as Image method the result image is saved to a temporary directory in local storage  before being shown in the application .


Security features:

A number of security features are offered by the pdf package in Flutter to guard against unauthorized access and modification of PDF files. Encryption, password protection, and digital signatures are some of these security features.

Here show example of how to use Flutter pdf library to encrypt and password-protect a PDF file in flutter application :

To prevent unauthorized access, you can encrypt a PDF file with a password. An extensively used encryption standard, 128-bit AES encryption, is supported by the package.

pdf file can have set  various levels of permissions including printing , copying , editing, annotating etc . Both the user and the file owner can receive these permissions individually.

final _formKey = GlobalKey<FormState>();
  final _passwordController = TextEditingController();
  final _pdfController = TextEditingController();
  File _pdfFile;

  Future<void> _encryptPdf() async {
    // Open the PDF file
    final bytes = await _pdfFile.readAsBytes();
    final pdf = pw.Document().loadFromBytes(bytes);

    // Get the encryption parameters from the form
    final password = _passwordController.text;
    final userPerms = pw.Permissions(
      canPrint: true,
      canCopy: true,
      canModify: false,
      canAnnotate: true,
    );
    final ownerPerms = pw.Permissions(
      canPrint: true,
      canCopy: true,
      canModify: true,
      canAnnotate: true,
    );

    // Encrypt the PDF file with the specified password and permissions
    pdf.encrypt(
      userPassword: password,
      userPermissions: userPerms,
      ownerPassword: password,
      ownerPermissions: ownerPerms,
    );

    // Save the encrypted PDF file to disk
    final directory = await getTemporaryDirectory();
    final encryptedFile = File('${directory.path}/encrypted.pdf');
    await encryptedFile.writeAsBytes(pdf.save());

    // Display a dialog with the location of the encrypted file
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('PDF encrypted'),
        content: Text('The encrypted PDF file is located at:\n\n${encryptedFile.path}'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
            },
            child: Text('OK'),
          ),
        ],
      ),
    );
  }

Annotation tools:

To highlight or annotate PDF documents, a variety of annotation tools are available in the Flutter PDF package. Several of the annotating tools included in the PDF package are as follows:

late PDFViewController _pdfViewController;

  void _addAnnotation() async {
    final page = await _pdfViewController.getCurrentPage();
    final point = await _pdfViewController.getPoint();

    await _pdfViewController.addTextAnnotation(
      page!,
      point!,
      "This is an example of a text annotation.",
    );
  }

OCR (Optical Character Recognition):

Text in scanned images or PDF files can be easily edited and searched thanks to OCR (Optical Character Recognition) technology. Using OCR, you can extract text from a PDF file for purposes such as editing, copying, and searching.

Here are the fundamental actions you can take:

1): Open the PDF file and read its content into a byte buffer using the Flutter dart:io library.

2): To extract the text from the PDF byte buffer, use a PDF parsing library like pdf or dart_pdf.

3): Remove any extraneous characters or formatting from the extracted text, such as page numbers, headers, and footers.

4): Depending on your needs, return the processed text as a string or list of strings.

To help you get started, here is some sample code:

import 'dart:io';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pdfwidgets;

void main() {
  /// Open the PDF file
  final file = File('path/to/pdf/file.pdf');
  final bytes = file.readAsBytesSync();

  /// Parse the PDF and extract the text
  final pdf = PdfDocument.openBytes(bytes);
  final pages = pdf.pages.map((page) => page.text).toList();

  /// Process the extracted text
  final processedPages = pages.map((page) {
    /// Remove any unwanted characters or formatting
    return page.replaceAll('\n', '').trim();
  }).toList();

  /// Print the processed text
  print("processedPages :: $processedPages");
}

Form filling and signing:

For many applications, the ability to fill out and sign forms in PDF files is a crucial component. Flutter’s PDF package includes tools for electronically filling out and signing PDF forms. This package makes it simple to create PDF forms, fill them out with user input, and add a digital signature. Checkboxes, radio buttons, and other form elements can also be added to PDF forms with the help of this package.

pdf.addPage(pw.Page(
  pageFormat: PdfPageFormat.a4,
  build: (context) {
    return pw.Center(
      child: pw.Form(
        child: pw.Column(
          children: [
            pw.Text('Name:'),
            pw.TextField(),
            pw.SizedBox(height: 20),
            pw.Text('Age:'),
            pw.TextField(),
            pw.SizedBox(height: 20),
            pw.Text('Gender:'),
            pw.RadioButtonGroup(
              options: ['Male', 'Female'],
            ),
            pw.SizedBox(height: 20),
            pw.Text('Country:'),
            pw.DropDown(
              items: ['USA', 'Canada', 'Mexico'],
            ),
            pw.SizedBox(height: 20),
            pw.Text('Comments:'),
            pw.TextField(),
          ],
        ),
      ),
    );
  }
));

Signature field can added using the pw.Signature widget provided by the pdf package.

pdf.addPage(pw.Page(
  pageFormat: PdfPageFormat.a4,
  build: (context) {
    return pw.Center(
      child: pw.Form(
        child: pw.Column(
          children: [
            pw.Text('Name:'),
            pw.TextField(),
            pw.SizedBox(height: 20),
            pw.Text('Age:'),
            pw.TextField(),
            pw.SizedBox(height: 20),
            pw.Text('Gender:'),
            pw.RadioButtonGroup(
              options: ['Male', 'Female'],
            ),
            pw.SizedBox(height: 20),
            pw.Text('Country:'),
            pw.DropDown(
              items: ['USA', 'Canada', 'Mexico'],
            ),
            pw.SizedBox(height: 20),
            pw.Text('Comments:'),
            pw.TextField(),
            pw.SizedBox(height: 20),
            pw.Text('Signature:'),
            pw.Signature(),
          ],
        ),
      ),
    );
  }
));

to obtain this example code, click here….


Conclusion

The PDF package can be used to create apps that run on both Android and iOS platforms making the development of cross platform software simple . The package includes support for multicolumn layouts , headers and footers and custom page sizes among other layout options for working with PDF files. Due to the package’s fast and effective PDF rendering capabilities, working with large PDF files doesn’t have to compromise performance.

Here is a brief description of a pdf package; modify it to suit your needs.

Thanks for reading this article…..

Have a beautiful day…… 

How to Create a New Branch in Git

0
How to Create New Branch in Git

We usually create a new branch in git repository, when we are working on a new project to be added into the codebase without affecting the current working code or when your current code has a bug and need to fix it on a testing server at such situation we simple create new branch git.

The best advantage in making a new git branch is that, we can alter our code & experiment with the codebase independently trial & error, without interfering with main codebase, then finally when testing is done and your git new branch work perfectly we can merge the changed of it to git main branch.

Additionally, By creating new branch in github repo allows your project team to freely test their own ideas & Implement new feature without the risk of breaking main branch codebase.


Git create branch

To make new branch in your github repository, run below commonds in root folder of your project:

git branch <branch-name>

Here, Replace ‘<branch-name>’, with a new branch name.

Example, I want to create a branch by my name “rajat-code”, use the below commands:

git branch rajat-code

This will create a branch by name “rajat-code”.

Note: The above cmd will simple create a new branch in git but will not automatically switch to new branch. To do so follow below step


git switch branch command

git checkout <branch-name>

Replace <branch-name> with you given new branch name.

Eg:

git checkout rajat-code

The 10 Best Programming Languages for AI Development

0
10 Best Programming Language for AI Development

The impact of AI on the globe has been far-reaching and unprecedented. Many individuals, particularly younger ones, don’t realize it because they assume AI has always existed in society. Around 37% of corporations and organizations now use AI. Recent years have seen the introduction of a wide range of algorithms, from specialized recommendation systems to interactive humanoid robots. Yet, the effects of these AI examples are limited to the global scale.

Artificial intelligence (AI) is used by businesses to improve production, management, and customer satisfaction, which is more relevant here. AI’s progress seems ideal, with its potential uses in areas such as analytical decision-making, automating, decreasing error rates, and data mining. The first step in developing AI is selecting the appropriate programming language.

Why Should You Employ AI for Your Upcoming Project?

AI aims to simplify everyday tasks like scheduling appointments, managing a home or workplace, or even driving a vehicle. About 51% of online retailers rely on AI to deliver a smooth customer experience. Therefore, picture a scenario where your tech is smart enough to anticipate and provide for your requirements. Doing this would make your every day more enjoyable and freer of worry and provide additional time to spend on yourself. 

In What Ways Does Artificial Intelligence Operate?

The information its users provide to an AI system is crucial to its success. There is an abundance of tech that uses AI. Around 77% of devices employ some AI system. The size of its error range is proportional to the reliability of these numbers. Regularly providing your AI system with sufficient and reliable data can increase its efficacy, dependability, and precision. The three cognitive abilities that AI acquires to improve its efficiency are:

best language for AI development
  • Procedures for Learning: It’s a kind of AI software that gathers pertinent information to create rules for turning raw data into valuable insights. Algorithms are the rules that tell computers what to do and how to do it systematically.
  • Mechanisms for Reasoning: The appropriate AI algorithm for accomplishing a task is identified throughout this programming procedure.
  • Procedures for Self-Correction: This branch of AI programming constantly adjusts algorithms to improve accuracy, resulting in reliable outcomes.

Top 10 Languages for Artificial Intelligence Development

AI programming computer image

Several languages are available for use in the creation of AI. The top 10 programming languages for creating AI and machine learning systems are the following:

Python

Python is the most often used language for AI development because of its accessibility and widespread use. It has several uses in networking, desktop software, the internet, science, data science, AI, and ML. It’s ready for AI development because of its extensive collection of libraries like  PyTorch, MXNet, Keras, Pybrain, TensorFlow, and Scikit-learn.

Python’s easy syntax is ideal for AI and NPL (Natural Language Processing) applications, and it also provides enhanced text processing tools, programming with modular layouts, and more. Python’s conciseness and clarity make it easy to pick up and master. In addition, there is a sizable community of dedicated users behind it.

Haskell

The winning features of Haskell are its speed and security. Haskell is a cutting-edge, completely functioning programming language with many practical applications in AI. Its more sophisticated features include type classes, which make type-safe operator overloading possible.

Lambda expressions, pattern matching, type classes, type polymorphism, and list comprehension are more characteristics. Haskell’s rich features make it well-suited for educational and professional use. Haskell is one of the most secure AI programming languages due to its adaptability and mistake-handling capability.

Lisp

From its inception in the 1960s, Lisp has seen extensive application in academia, particularly for studying natural languages, verifying theorems, and solving AI issues. Lisp was developed as a practical mathematical notation for programming, but AI programmers now widely use it.

Lisp is great for solving problems, iterating quickly, or creating dynamic software. The popular tools like Grammarly, Routinic, and DART were all developed using Lisp. Despite its flaws, Lisp remains a promising programming language for advancements in artificial intelligence.

R

The R Foundation for Statistical Computing maintains R, an open software platform with a programming language for statistical computation and graphic elements. Although not ideal for AI applications, this language excels in number-crunching. 

Complex procedures for expressing and analyzing numerical data are fundamental to the development of AI. R outperforms Python in this scenario as it is more adept at handling complicated mathematical equations. 

Java

Another language that is popular among AI developers because of its adaptability, friendliness, and wealth of resources. Java is not as quick as other programming languages but is robust and may be used in AI projects.

Importantly, it works on several platforms without constantly changing your code. Java can also create high-quality images. It is not necessary for you to be very concerned with the clarity of the AI graphics.

Prolog

Program in Logic, or Prolog for short, is another computer programming language. In 1972, a rule-based framework for the language was created. It finds most of its usage in computational linguistics and artificial intelligence projects.

Regarding jobs that need a database, natural language processing, and symbolic reasoning, Prolog is the preferred language! It’s the top pick for language support in artificial intelligence exploration.

Scala

Scala improves the efficiency, simplicity, and effectiveness of the coding process. Developers may find useful tools and libraries for working with Scala in the index called Scaladex. It’s compatible with the Java Virtual Machine (JVM) and facilitates the creation of intelligent applications.

Scala is a powerful programming language that is cross-platform with Java and JS and has many valuable features such as pattern matching, browser extensions, fast functions, and adaptable user interfaces. Scala has pleased experts in AI and is considered one of the top solutions for AI development.

Julia

This dynamic language was developed to provide superior performance in numerical analysis and computational research. Since MIT first released the language in 2012, Julia has gained popularity because of its high computing capability, rapid execution, and script-like syntax.

Scikitlearn.Jl, TensorFlow. Jl, Flux, Mocha. Jl and many more are just a few examples of machine learning components that have arisen in recent years to support this language.

C#

Another long-standing language that can still hold its own in artificial intelligence is C#. The language’s extreme adaptability is a significant factor, making it a good fit for demanding programs that need plenty of memory and CPU time. The AI model is best handled in production when written in C#, a low-level language.

C# is considered to be one of the best .NET frameworks. Many developers tends to use libraries like accord.NET and TenserFlow.NET to develop and integrate machine learning frameworks in C#. Therefore companies prefer to hire  .NET development company to leverage the best functionality of the .Net framework.

While it’s true that numerous profound machine learning frameworks are developed in C#, this fact is often overlooked by AI developers. In addition, C#’s efficiency and performance are top-notch since it translates user code into machine-readable code.

JavaScript

Most programmers nowadays utilize JavaScript to build more interactive and secure online applications. It is also an excellent language for creating AI. Since JavaScript provides developers unrestricted access to server-side and client-side processes, it simplifies the process of building AI software. This language ensures a brisk pace in creating AI, higher performance, and more safety.

JavaScript enables parallel processing and interaction with several source codes, including HTML and CSS. That’s an essential quality for advancing AI. Also, this programming language has a sizable community that may assist programmers. React.js, Underscore.js, and jQuery are a few JavaScript frameworks that make creating AI easier.

Conclusion

Incorporating AI into anything that impacts daily life marks the arrival of the technological future. AI has increased in popularity to enhance professional and personal endeavors. A surprising truth about AI is that just 34% of customers know they are encountering AI in some form or another.

Many languages are available to programmers, a boon for developers looking to improve AI software. The ideal language for oneself is the one in which you can express yourself effectively. If you are starting, choosing a language that makes the development process easier is essential since this will help you the most.

Integrate Facebook ads in Flutter

0
Facebook Ads In Flutter
How to add facebook ads in flutter app

This article will show you , how to quickly make money from your Flutter application using Facebook ads.

By incorporating Facebook ads into their Flutter apps developers can monetize their work by displaying Facebook ads inside of them. To ensure that the ads are appearing as intended.it is necessary to create a Facebook Ads account, configure the Facebook SDK, add the Facebook Audience Network plugin, initialise the Facebook Audience Network SDK, create an ad widget using the FacebookBannerAd widget and run the app. Developers can easily integrate Facebook ads into their Flutter apps using these steps to start making money. This article will show you how to quickly monetize your Flutter application using Facebook ads.

Create an App in facebook console

The app development flow gets the bare minimum of data required to create an exclusive ID for your app. After completing the flow, you will arrive at the App Dashboard where you can either continue designing and testing your app or add more details about it.

Starting…..

Your Facebook developer account must be active

Launch the app development process.

1) : Click the “Get Started” button in the upper right corner of the page while you are on the Facebook for Developers website.

2) : You’ll need to open a Facebook account if you don’t already have one. Use your login information to access your account if you have one.

Step 1) : Creating Facebook Application & get APP name & App ID

To create Facebook App Id & App name, you can follow these steps.

A) : Open https://developers.facebook.com and create your application and you have to show like this type page

Create an app

Choose your app type , the recommended option here is Consumer. Then click on Next,.

Fill in the appName and email address here then choose Create app.

B): After you’ve finished creating the application .begin adding the Facebook Login project.

In this step select the Facebook login option and click on the Setup button. Your app ID which you can use in your Facebook ads, is located here. You’ll need this ID later so , make a note of it.

Step2 🙂 Once you have created your application click the “Set Up” button and choose “Audience Network” from  list of possibilities.

Your app ID which you can use in your Facebook ads is located here.

i)Visit Facebook Ads Manager at  https://www.facebook.com/adsmanager/ and log in to your account to get placement ID.

ii) first selecting platform then decide on the purpose of your advertisement. such as Audience Network, Facebook, Instagram etc….

iii) To create an advertisement

iv) When deciding on the platform you want to use decide what your advertisement will be used for.

v) You will be given a placement ID after choosing the placement. which you can use in your Facebook advertisements. You’ll need this ID later so make note of it.

You should able to register an app in the Facebook console and get an app ID and placement ID by following the instructions and visible screenshots provided here. Let me know if you have any other inquiries.

The steps below can be used to add Facebook Ads to a Flutter app:

You should be able to register an app in the Facebook console and get an app ID and placement ID by following the instructions and visible screenshots provided here. 

The steps below can be used to add Facebook Ads to a Flutter app:

Step 1) : Set up an app in the Facebook Developer Dashboard after creating a Facebook Developer account.

Step 2) : Your Flutter app should now include the Facebook Ads SDK. This is accomplished by including the following dependencies in your pubspec.yaml file:

dependencies:
  flutter_facebook_ads: ^any

Step 3) : Packages can be installed using the command line:

flutter pub get

Step 4) : Import file

import 'package:facebook_audience_network/facebook_audience_network.dart';

We will use testing project id and placement id to display different ads, such as banner ads and interstitial ads. To obtain a real project id, we must submit our application to Facebook for review. Once they approve, we receive project id, and we can then create placement id in accordance with our needs.

Step 5) :Install Facebook Ads SDK into your app . You can do by adding the following code your main method :

void main() {
  FacebookAds.instance.initialize(
    appId: 'your_app_id',
  );
  runApp(MyApp());
}

Types of Facebook Mobile Ads

Adding Banner Ad In Flutter App

In an app’s layout, banner ads take up space at the top or bottom of the device screen. They remain visible while users use the app and can automatically refresh after a set amount of time.

FacebookBannerAd(
       bannerSize: BannerSize.LARGE,
       keepAlive: true,
       placementId: "Your Placement ID",
     ),

Adding an Interstitial Ad

Interstitial advertisements are interactive, full-screen advertisements that hide the host app or website’s interface. These advertisements are placed at natural transition points or breaks, such as in between activities or game levels, because they appear between content.

We must first create a method to call the interstitial ad in order to add an interstitial ad to your Flutter project. If the advertisement loads successfully, the user will see it.

 FacebookInterstitialAd.loadInterstitialAd(
    placementId: "Your Placement Id",
    listener: (result, value) {
      if (result == InterstitialAdResult.LOADED)
        FacebookInterstitialAd.showInterstitialAd(delay: 2000);
    },
  );

Reward ad

Users who view Facebook reward ads receive virtual currency or other in-app rewards in exchange for watching a video ad. These advertisements are made to encourage user interaction with advertising in way that is advantageous to both the advertiser and the user.

Using the Facebook Ads SDK, you can incorporate Facebook reward ads into a Flutter application. The procedure involves loading a paid video ad, initializing the Facebook Ads SDK in your app, and presenting it to the user. The specified virtual currency or another in-app reward is given to the user after they watch the advertisement.

 _rewardedVideoAd = RewardedVideoAd(
      placementId: 'your_placement_id',
      listener: (result, value) {
        print('Rewarded Video Ad $result => $value');
        if (result == RewardedVideoAdResult.rewarded) {
          // reward user
        }
      },
    );
    _rewardedVideoAd.load();
onPressed: () {
            if (_rewardedVideoAd.isLoaded) {
              _rewardedVideoAd.show();
            }
          },

Your_placement_id should be replaced with the Placement ID you obtained from the Facebook Developer Dashboard.

The entire implementation is contained in this GitHub repository.

link here : 


Conclusion

Try out your ads. To test your ads and make sure they are functioning properly, use Facebook’s Ad Manager or the Facebook Ads Helper tool.

I hope you found this Flutter facebook ads tutorial to be useful.

I’m done now! These instructions explain how to set up paid facebook ads in a Flutter app using the Facebook Ads SDK.

Thanks for reading this article…..

Have a good day…..

AR(Augmented Reality) in flutter

0
AR Core- Augmented Reliality in flutter
AR - Augmented Reliality in flutter

Augmented reality can be implemented in flutter applications using the stunning ARcore plugin. One of the recently introduced new technologies is this one With this plugin we’ll talk about the various features that the flutter plugin offers. so let’s get started.

In this tutorial, you’ll discover how to leverage augmented reality in Flutter to enhance the app’s user experience.

Augmented reality is used in mobile applications to enhance the user experience. Customers may see items in front of them thanks to the usage of several mobile apps for product display.

An augmented reality app is a piece of software that incorporates digital visual content—occasionally audio and other kinds as well—into the user’s physical environment.

This technology is mainly focused on this two tasks : 

1)detecting the position of the mobile device as it travels and creating 

2)real-world understanding,according to Google’s description on ARCore.

You must take the following actions in Android Studio in order to make 

Activate AR & set up


Activate AR & set up

You must take the following actions in Android Studio in order to make 

ARCore functionality available:-

Step 1):  Add entries to the manifest that are AR Required or AR Optional.

AR Required : 

<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>

AR Optional :

<uses-permission android:name="android.permission.CAMERA" />
<uses-sdk android:minSdkVersion="14" />
<application>
    <meta-data android:name="com.google.ar.core" android:value="optional" />
</application>

Step 2): the following to build.gradle

allprojects {
   repositories {
       google()
}
}

dependencies {
 implementation 'com.google.ar:core:1.16.0'
}

Step 3): The following dependencies should be added to your app’s build.gradle file.

android {
    compileOptions {
        sourceCompatibility 1.8
        targetCompatibility 1.8 
}
dependencies {
    implementation 'com.google.ar.sceneform.ux:sceneform-ux:1.8.0'
    implementation 'com.google.ar.sceneform:core:1.8.0'
}

Following the steps listed below, we will integrate augmented reality into Flutter.

Step 1): Integrating the AR Core Plugin

Add the arcore_flutter_plugin package to your pubspec.yaml file:

arcore_flutter_plugin: ^any

For my project.. I am using this plugin.

Step 2):  Run the flutter packages and then package installed.

Step 3): In your Flutter application import the arcore_flutter_plugin package:

import 'package:arcore_flutter_plugin/arcore_flutter_plugin.dart';

ArCoreView

The ARview type is returned by this class, It contains two different types of views.

i)  AUGMENTEDFACE

ii) STANDARDVIEW


It contains 4 properties:

i) onArCoreViewCreated

ii) enableTapRecoginzer

iii) enableUpdateListener

iv) type

i) onArViewCreated

It accepts an ARObjectManageras a parameter. ARObjectManagerwill be covered in our later section.

ii) enableTapRecoginzer

Set to false at first. It is utilized by the MethodChannel as an argument.

iii) enableUpdateListener

Set to false at first. It is utilized by the MethodChannel as an argument.

iv) type

It is a view type; one of AUGMENTEDFACE, STANDARDVIEW is available. By default, it is set to STANDARDVIEW .


ArController

Using the addArNode, addArNodeWithAncher, and removeNode functions, this controller could add an ArNode, an ArNode with an anchor, and remove a node.

new augmented reality scene

You must include an ArView widget in your app in order to create a brand-new AR scene. The main interface for interacting with the ARCore platform is this widget. Here an illustration of how to make a fresh AR scene:

ArCoreController? arCoreController;

body : ArCoreView(
        onArCoreViewCreated: _onArCoreViewCreated,
      ),

 void _onArCoreViewCreated(ArCoreController controller) {
    arCoreController = controller;
  }


Step 5): Insert 3D models

Using the ArCoreReferenceNode widget, you can include 3D models in your AR scene. With the help of this widget, you can position and load 3D models into your scene. To add a 3D model to your scene, follow these steps:

ArCoreReferenceNode(
  name: "node name",
  objectUrl: "object value",
  position: Vector3(0, 0, -1),
  rotation: Vector3(0, 180, 0),
  scale: Vector3(0.2, 0.2, 0.2),
),

 Step 6): Control your AR experience.

ArCore can be used to manage an AR experience. With this controller, you can change the camera angle and add or remove nodes from the AR view, among other things. Below is an example of managing an AR experience.

void _onArCoreViewCreated(ArCoreController controller) {
  arCoreController = controller;

  // Move the camera to a new position
  arCoreController?.moveCamera(
    CameraUpdate.newPosition(
      Vector3(0, 0, -2),
    ),
  );
}

main.dart file

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  runApp(
    MyApp(),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      color: Colors.blue,
      title: "Ar implementation in flutter app",
      home: ArItemScreen(),
    );
  }
}

Create a dart file with name ar_item_screen and set this code

Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(title: const Text("AR in flutter")),
        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.all(15),
            child: Container(
              height: 100,
              alignment: Alignment.center,
              padding: const EdgeInsets.only(left: 10, right: 10, top: 15),
              decoration: const BoxDecoration(
                color: Colors.blue,
                borderRadius: BorderRadius.only(
                    topRight: Radius.circular(30),
                    topLeft: Radius.circular(30)),
              ),
              child: GestureDetector(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => ARViewScreen(
                        itemImg: "assets/items/img_chair.jpg",
                        itemName: "Eula Modern Accent Dining Chair",
                      ),
                    ),
                  );
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(
                      width: 80,
                      height: 80,
                      child: Image.asset(
                        "assets/items/img_chair.jpg",
                        width: 60,
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(left: 20.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children:  <Widget>[
                          Text(
                            "EDining Chair",
                            style: TextStyle(fontSize: 16, color: Colors.blue.shade900),
                          ),
                          Text(
                            "Eula Modern Accent Dining Chair",
                            style:
                                TextStyle(fontSize: 10, color: Colors.blue.shade900),
                          ),
                        ],
                      ),
                    ),
                     SizedBox(
                      width: 60,
                      child: Text(
                        "5,000",
                        style: TextStyle(fontSize: 14, color: Colors.blue.shade900),
                      ),
                    )
                  ],
                ),
              ),
            ),
          ),
        ));

Complete Source Code – AR Core – Augmented Reality in flutter

Click here to access this example app code……

https://github.com/kevalv001/ar_application.git

You can modify this code with your needs.


Conclusion..

Flutter offers a strong framework for creating augmented reality (AR) applications that work flawlessly on both Android and iOS devices. Developers can easily create immersive and interesting augmented reality (AR) experiences thanks to the combination of ARKit, ARCore, and Flutter.

Developers can quickly iterate and test their AR applications thanks to Flutter’s widget-based approach and hot-reload function. Flutter’s support for 2D and 3D graphics, animations, and interactivity also contributes to the development of rich and interesting AR experiences.

The development process is further streamlined by the availability of plugins and packages for incorporating AR functionality into Flutter applications. Developers can quickly access the AR capabilities of the underlying platform and incorporate them into their Flutter apps by using plugins like Apple’s ARKit Plugin and Google’s ARCore Plugin.

Thanks for reading this article 

Have such a wonderful day………..