Google search engine
Home Blog Page 35

Rendering Image From Byte Buffer/Int8List In Flutter

0

Images are major to each application. They can give urgent data by filling in as visual guides or just working on the stylish of your application. There are numerous ways of adding an image to your Flutter application.

At the point when you make an application in Flutter, it incorporates both code and resources (assets). An asset is a document, which is packaged and sent with the application and is open at runtime. Showing pictures is the major idea of most versatile applications.

This blog will explore the Rendering Image From Byte Buffer/Int8List In Flutter. We will see how to implement a demo program. We are going to learn about how we can render an image in your flutter applications.


Table Of Contents::

Introduction

Code Implement

Code File

Conclusion

GitHub Link



Introduction:

Perusing byte data from a given URL of an image and you can change this move to suit what is happening, like getting byte data from a file or a database Utilizing Image. memory to render the image from byte data.

Demo Module :

The above demo video shows how to render an image in a flutter. It shows how rendering an image from a byte will work in your flutter applications. It shows an image with its URL instead of the detour of getting its bytes from the URL and then using this byte list to display the image. It will be shown on your device.

How to implement code in dart file :

You need to implement it in your code respectively:

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

In Flutter, you can render a picture from an Int8List of bytes by utilizing the Image. memory constructor like:

Image.memory(Uint8List.fromList(myBytes));

Assuming that what you have are byte buffers, utilize this:

Image.memory(Uint8List.fromList(myBuffer.asInt8List()));

In the main. dart file, we will create a HomeScreen class. In this class, first, we will add Int8List byte data that will be used to render the image.

Int8List? _bytes;

Now, we will create a _getBytes() method. In this method, we will get byte data from an image URL. Inside, we will add the final ByteData data is equal to the NetworkAssetBundle(). We will add _bytes is equal to the data.buffer.asInt8List().

void _getBytes(imageUrl) async {
final ByteData data =
await NetworkAssetBundle(Uri.parse(imageUrl)).load(imageUrl);
setState(() {
_bytes = data.buffer.asInt8List();
print(_bytes);
});
}

Now, we will create an initState() method. In this method, we will add _getBytes(Your Url’).

@override
void initState() {
// call the _getBytes() function
_getBytes(
'https://upwork-usw2-prod-assets-static.s3.us-west-2.amazonaws.com/org-logo/425220847461273600');
super.initState();
}

In the body, we will add the Center widget. In this widget, we will add _bytes is equal-equal to null then, show CircularProgressIndicator. Else, show an Image.memory(). Inside this function, we will add Uint8List.fromList(_bytes!), width, height, and fit is equal to BoxFit.contain.

Center(
child: _bytes == null
? const CircularProgressIndicator()
: Image.memory(
Uint8List.fromList(_bytes!),
width: 250,
height: 250,
fit: BoxFit.contain,
)),

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

Final Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:typed_data';

import 'package:flutter_rendering_image/splash_screen.dart';

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

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

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

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

@override
State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
Int8List? _bytes;

void _getBytes(imageUrl) async {
final ByteData data =
await NetworkAssetBundle(Uri.parse(imageUrl)).load(imageUrl);
setState(() {
_bytes = data.buffer.asInt8List();
print(_bytes);
});
}

@override
void initState() {
_getBytes(
'https://upwork-usw2-prod-assets-static.s3.us-west-2.amazonaws.com/org-logo/425220847461273600');
super.initState();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
'Flutter Rendering Image From Byte Buffer/Int8List',
style: TextStyle(fontSize: 16.5),
),
centerTitle: true,
automaticallyImplyLeading: false,
),
body: Center(
child: _bytes == null
? const CircularProgressIndicator()
: Image.memory(
Uint8List.fromList(_bytes!),
width: 250,
height: 250,
fit: BoxFit.contain,
)),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Rendering Image From Byte Buffer/Int8List in your flutter projectsWe will show you what the Introduction is. Make a demo program for working with rendering an image from Int8List in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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


Implement Dark Mode in Flutter using Provider

Hi everyone, In this article, we will be learning how to implement the dark theme in our app using the provider package

As we all now Dark theme is trending and most of the popular app has the feature to turn into the dark mode.

There are two ways to turn on the dark mode in any app:

1: Adding a custom option to change to the dark mode (Eg: Twitter, Medium app)

2: Depends on the Phone system setting (Eg: Instagram)

We already have both the options in flutter.

If you check the MaterialApp widget you will see

We have the theme and darkTheme parameter in MaterialApp widget we can provide the dark ThemeData in darkTheme and light ThemeData in theme if we want our app to change the theme according to the system preferences.

And if we have a custom button or something to change the dark theme then we just have to put some condition to change it.

Let’s implement the dark mode to an app

Implementation

Step 1: Add the dependencies

Add dependencies to pubspec.yaml file.

dependencies:
flutter:
sdk: flutter
shared_preferences: "<newest version>"
provider: "<newest version>"

we are using the SharedPreferences to set the value in the memory so even if we close the app and reopens it, our data won’t lose.
Provider is used to manage the state when the dark theme is implemented on the app.

Step 2: Create a class for SharedPreferences

https://gist.github.com/ashishrawat2911/a600a32490b250014b5f9f43c2de1e50#file-dark_theme_preference-dart

We are creating a separate class for the SharedPreferences so the code won’t mess up.

We have created a class DarkThemePreference where we are storing the bool value in for the dark theme, we have two methods for saving and retrieving the bool value.

Step 3: Create a model class for provider

https://gist.github.com/ashishrawat2911/6023c8db181a3ff1935bcb60de314ead#file-dark_theme_provider-dart

We are accessing the preference value through the provider so whenever there is any change the notifyListeners() UI will be updated if we have attached the provider to the screen.

Step 4: Add custom theme data for dark mode

if you see we have to provide the ThemeData , so I have created a method for dark and light mode.

https://gist.github.com/ashishrawat2911/220778e84eb5c9d44ec0604c3a6b1d15#file-dark_theme_styles-dart

Step 5: Add the provider to Material app

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

when we run our app the first widget will be MyApp which will have MaterialApp .

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {


@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: SplashScreen(),
routes: <String, WidgetBuilder>{
AGENDA: (BuildContext context) => AgendaScreen(),
},
);
}
}

Now in the initState of our MyApp we will check for the value that is stored in the SharedPreferences through the Provider.

DarkThemeProvider themeChangeProvider = new DarkThemeProvider();

@override
void initState() {
super.initState();
getCurrentAppTheme();
}

void getCurrentAppTheme() async {
themeChangeProvider.darkTheme =
await themeChangeProvider.darkThemePreference.getTheme();
}

If you see the getCurrentAppTheme method, I am fetching the value from the preferences and set the value in the provider.

Now we will add notifier to the material app which is ChangeNotifierProvider and set a provider model to it, if any change happens in the provider it will notify its descendants.

https://gist.github.com/ashishrawat2911/8bbf5740abeb688b7864937a9db6c4cd#file-my_app_dark_theme-dart

To listen to the changes in the UI we can use Consumer will listen to the changes and update the MaterialApp .

We can also use this instead of Consumer<T> .

var darkThemeProvider = Provider.of<DarkThemeProvider>(context)

Final Step: Turn on the dark theme

For example, we have a CheckBox through which we are setting the theme.

@override
Widget build(BuildContext context) {
final themeChange = Provider.of<DarkThemeProvider>(context);
...
Checkbox(
value: themeChange.darkTheme,
  onChanged: (bool value) {
  themeChange.darkTheme = value;
})

When the value is “true” the provider will set the theme to dark and turn into a light mode when the value is true.

and Kaboom 💥

We have successfully learned how to add a dark theme to your app.

We also have created a Devfest app for Google Developers Group New Delhi in which we had implemented a dark mode with some animation.

Check out the whole code here

flutter-devs/Flutter-Devfest
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…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! For any flutter-related queries, you can connect with us on FacebookGitHubTwitter, and LinkedIn.

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


What’s New in Flutter 1.12?

0

As we all know Flutter has come up with new announcements in Flutter Interact which was recently held on Dec 11, 2019. Generally, developers eagerly wait for new announcements that Google Flutter is going to make and then observe and work with them, this time also Google Flutter wanted to make it a big release and for that, they prepared for it. In this release according to flutter they have merged 1905 pull requests from 188 contributors including Google and non-Google contributors.

Since its first release from Flutter 1.0 to Flutter 1.12, it’s 5 stable versions have been released and the flutter team always improved its shortcomings and in Flutter 1.12 they have come up with few new concepts and were focused on the concept of Ambient Computing.

Before we review announcements of Flutter 1.12 let’s take the overview of Ambient Computing.

Ambient Computing: When developers start developing an app they always find themselves in the dilemma that which gadget they need to aim while they are developing an app.

Actually, the fact is we daily use different internet-connected devices with the same purposes so the Flutter development team has decided to create a milieu that makes users use all services across all the devices now they have come with the concept of “ Write Once, Read Everywhere” and this is the ambient computing.

Announcements in Flutter 1.12

  1. Release of Dart 2.7
  2. Beta web support
  3. macOS Desktop support
  4. ios 13 Dark Mode
  5. Add-to-app
  6. Updated Dart Pad
  7. Adobe XD to Flutter plugin
  8. New Google font Packages
  9. Multi-device Debugging

Release of Dart 2.7

In all the flamboyant announcements this is the most awaited release because it is addressing one important problem which will help to handle and prevent errors when variable get a zero value and parse an integer. This string handling ability makes it the richest among all.

Beta web Support

Flutter for Web has been an astonishing release among the developer community and now the Flutter development team has added another feather in the cap by shifting it into beta version and by making it easier to apply Dart Compiler and Flutter architecture efficiently.

macOS Desktop Support

In this segment, developers will able to use release mode to develop a fully optimized macOS application with the help of Flutter

Desktop app support got rich with various new updates like menu dropdown keyboard navigation, visual density assistance, checkboxes, radio buttons and many more.

Linux and Windows support is also in the up-gradation Stage and soon will be upgraded.

iOS 13 Dark Mode

Flutter 1.12 also described the addition of complete dark mode in iOS13, previously flutter also provided support for auto toggling to dark mode on 
Android 10, all the iOS-like widgets, named Cupertino are available in dark mode. they can automatically be enabled by turning the dark mode on.

image source Flutterdevs & AeologicTechnologies

Add-to-app

Another Feature of Flutter 1.12 is it makes developers enable to add flutter in the current Android and iOS app, Migration of an app in flutter is possible once, instead of creating it from the beginning.

Here in this video of Flutter dev, you can get an idea of doing it easily.

image Source Flutter-dev

Updated DartPad

In updated DartPad not only the entire code can be edited but also can be assessed the rendered UI and running the flutter code efficiently.

Adobe XD to Flutter Plugin

Now flutter has come up with a new collaboration with Adobe XD and XD is accessible for flutter plugins. Actually flutter is trying hard to make developers work easy and this is the kind of effort where the latest XD in Flutter changes the XD designs automatically into code and makes it usable part of flutter development.

New Google Fonts Package

Flutter added this improvement in order to beautify user experience by adding 1000s open-source font families.

It helps to designers to add different typography while developing within a few code lines.

Multi-device Debugging

As a developer, we always develop and debug our flutter UI and when we want to debug it on different devices we need to debug it separately for the individual device but now flutter has come with the solution for this by adding multi-device debugging.

These were the important new features every developer should go with.

What is really needed to make it more efficient and compete with others

Flutter is trying hard to take the lead over the debate on Flutter 
Vs React native and this is a gamechanger effort that is surely going to get a lead. After all these announcements if we are still missing something which is pushing of codes of the designed apps directly.

Hope Flutter team will surely work on it and in upcoming announcements, we might see some new features in all segments.

Thanks for reading this article, if you find something you better know Please let me know, I will welcome it with full gratitude.


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 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 Facebook, GitHub, and Twitter for any flutter related queries.

Selecting Multiple Item in List in Flutter

0

Being an app developer we are always at a point when we want to implement the item selection and performs operations on it.

In this article, you will learn how to add the selection of items in your app.

Suppose we only have a name ( String ) and rank ( int ) on our list.

class Item {  
String imageUrl;
int rank;
Item(this.imageUrl, this.rank);
}

We need to create two lists, itemList for all items and selectedList for selected items.

List<Item> itemList;  
List<Item> selectedList;
@override 
void initState() {

loadList();
super.initState();
}
loadList() {    
itemList = List();
selectedList = List();

List.generate(20,(index){
itemList.add(Item("assets/pringles.png", index+1));
}
}

Let’s jump into UI.

@override 
Widget build(BuildContext context) {
return Scaffold(
appBar: getAppBar()
);
}

For AppBar , I have created a separate widget method because you must have seen in apps when selecting it’s the app bar changes. We also need to update the app bar whenever we are selecting items.

We will check in the selectedList length whether it has any item in the list and change the app bar accordingly.

getAppBar() {
return AppBar(
title: Text(selectedList.length < 1
? "Multi Selection"
: "${selectedList.length} item selected"),
);
}
}

I have created a separate widget for the grid item and has a callback in it which will provide the bool value to tell whether it is selected or not.

https://gist.github.com/ashishrawat2911/3cdb0238fc68f78ae0fa5777ad445d60#file-griditem-dart

Now generate the list.

body: GridView.builder(
itemCount: itemList.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 4,
childAspectRatio: 0.56,
crossAxisSpacing: 2,
mainAxisSpacing: 2),
itemBuilder: (context, index) {
return GridItem(
item: itemList[index],
isSelected: (bool value) {
setState(() {
if (value) {
selectedList.add(itemList[index]);
} else {
selectedList.remove(itemList[index]);
}
});
print("$index : $value");
},
key: Key(itemList[index].rank.toString()));
}),

If you see, I have added the item in the selected list in the when the item is selected and removes when the item is deselected.

Now we have implemented the selection the grid, let’s implement some action.

https://gist.github.com/ashishrawat2911/aa9914ba5557124072d1c18d94861cf7#file-sellectionappbar-dart

I have added the delete button on the AppBar to delete the item in the itemList that are present in the selectedList .

If you are wondering why I am using the key because when I was deleting the values it was only updating in the widget tree but not exactly in the element tree.

To know more about keys in flutter check out

That’s it for this article.

Check out the GitHub repo used for this article.

ashishrawat2911/Flutter-MultiSelection
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

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! For any flutter-related queries, you can connect with us on FacebookGitHubTwitter, and LinkedIn.

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


Text Recognition with ML-Kit | Flutter

0

Hi everyone, In this article, you will learn how to implement the ML-Kit text recognition in your app.

What is ML-Kit?

Implementation

Step 1: Add Firebase to Flutter

Add Firebase to your Flutter app | Firebase
Follow this guide to add Firebase products to a Flutter app. Firebase supports frameworks like Flutter on a best-effort…firebase.google.com

Step 2: Add the dependencies

Add dependencies to pubspec.yaml file.

dependencies:
flutter:
sdk: flutter
  firebase_ml_vision: "<newest version>"
camera: "<newest version>"

firebase_ml_vision uses the ML Kit Vision for Firebase API for flutter that is built by the Flutter team.
We also need the camera plugin to scan the text.

Step 3: Initialize the camera

CameraController _camera;

@override
void initState() {
super.initState();
_initializeCamera();
}

void _initializeCamera() async {
final CameraDescription description =
await ScannerUtils.getCamera(_direction);

_camera = CameraController(
description,
ResolutionPreset.high,
);

await _camera.initialize();

_camera.startImageStream((CameraImage image) {

// Here we will scan the text from the image
// which we are getting from the camera.

});
}

We will be using a prewritten class by Flutter Team in their Demo which has some utility method to scan and detect the image from Firebase Ml-kit.

https://gist.github.com/ashishrawat2911/07c53c9a8eb16d36889ff8382dedbfae#file-scanner_utils-dart

Step 4: Scan the image

When we get the Image from the camera and scan it will we get the VisionText .

VisionText _textScanResults; 
TextRecognizer _textRecognizer = FirebaseVision.instance.textRecognizer();

https://gist.github.com/ashishrawat2911/b721a8e2312644767ac64be92e2f0796#file-camera_scan-dart

Step 5: Get the result

Now _textScanResults will have the result.

If you see VisionText , we can get the whole text, block, lines, and words also.

They are dependent on our choices that what type of result we want.

To get the

Text block :

List<TextBlock> blocks = _textScanResults.blocks;

Text Lines:

List<TextLine> lines = block .lines;

Text words :

List<TextElement> words = line.elements;

Step 6: Build the UI

To show the image result we just need to have the CameraPreview and pass the CameraController object.

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Stack(
      fit: StackFit.expand,
      children: <Widget>[

      _camera == null
            ? Container(
          color: Colors.black,
        )
            : Container(
            height: MediaQuery
                .of(context)
                .size
                .height - 150,
            child: CameraPreview(_camera)),
      ],
    ),
  );
}

Show scanned text outlines

To show the outline we can draw them by using CustomPainter because of the VisionText parameters provide the TextContainer and we can find the coordinates and draw on it.

https://gist.github.com/ashishrawat2911/03e14dd6ec2252384ddccab70862781b#file-text_detector_painter-dart

Widget _buildResults(VisionText scanResults) {
CustomPainter painter;
// print(scanResults);
if (scanResults != null) {
final Size imageSize = Size(
_camera.value.previewSize.height - 100,
_camera.value.previewSize.width,
);
painter = TextDetectorPainter(imageSize, scanResults);
getWords(scanResults);

return CustomPaint(
painter: painter,
);
} else {
return Container();
}
}

https://gist.github.com/ashishrawat2911/167a980ce78726bf428eede41ab381d0#file-outline-dart

Now if we see the app.

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! For any flutter-related queries, you can connect with us on FacebookGitHubTwitter, and LinkedIn.

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

Working with Callback In Flutter

0

Hello Folks! We all are working in flutter and most of the time we all need to work with Callback and VoidCallback because we need to send data from one method to another and vice versa.

if you are a beginner then chances are you are struggling to handle the flow of data actually there are various ways to do that but Callback is the best suitable way to handle this. So lets first understand What is Callback ??

Callback:

If we go by definition, the Callback is a function or a method which we pass as an argument into another function or method and can perform an action when we require it.

Let’s understand why we use it

For Example, if you are working in any app and if you want any change in any value then what would you do?

Here you are in a dilemma that what you want to change either state() or a simple value/values. If you need to change states then you have various state-changing techniques but if you want to change simple values then you will use Callback.

Let’s Understand it by a small example I have made to make you understand,

here are two images below one is showing a text(“Want to change Text”) and a button by which you will navigate to next screen, In next screen, there is a text field and a button which navigate to the previous screen with the changed text you will enter in the text field.

Now see in the code

https://gist.github.com/shivanchalpandey/2ebbb6eadd0fd902406d0e0d53db01d7#file-homepage-dart

here in the above code snippet, a text is defined which is a default text and when we will receive a String value from callback it will be changed, then we will navigate to next class where we will perform Callback

https://gist.github.com/shivanchalpandey/3c3794086757e086e1517c10b516a83b#file-editingpage-dart

here in the EditingPage we have defined the Callback function

typedef VoidCallback = void Function();

which will return the value we will change to the previous page,

In the EditingPage class, Callback function has been initialized and below in code with the help of controller value has been assigned to it, when we will navigate to the previous page we will receive it here

here the value which has been sent by using Callback is being initialized to the “editableText “ variable and it will update the text.

So simple idea is that when you want to change any value you can use Callback and can handle the data flow easily.

So it was a small explanation to make you understand actually how it works and why and when you should use it.

Thanks for reading this article, if you find something you better know Please let me know, I will welcome it with full gratitude.


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 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 Facebook, GitHub, and Twitter for any flutter related queries.

Why Flutter is important in 2020

0

Before I explain anything about it, chances are you have come across various blogs in which you have studied almost everything you should know about Flutter.

This year has been a thriller to mobile developers because mobile developers had various options to develop their app but with the introduction of Flutter whole scenario changed rapidly and the community found their new crush to pay attention to.

Now instead of explaining about flutter, I would recommend you visit the official Flutter site to get some knowledge about it.

After reading from the official site let me explain a few key points to summarize it.

Flutter consists of an SDK that helps to develop your application and compile code of iOS and Android. It also consists of a UI library of toolkits.

What would you get from Flutter:

1. Same Codebase for all platforms

In flutter, the developer needs to write a single code base for all platforms and this is one of the biggest advantages flutter developers have, here you have the same business logic and same UI in all platforms whether it is android, iOS, web it enables you to work in the concept of write once run everywhere.

2. Hot-Reload

In the native platforms, it has always been a problem to observe sudden and small changes while writing code and especially during UI design, Flutter has overcome this drawback with its hot-reload feature. It will not only help you to fix bugs easily but also add new features without compromising its speed.

3. Architecture

Building an app is easy but managing it according to business logic is quite a critical task so you need to follow an architecture to manage it and MVP(Model–view–presenter)is the best suitable architecture for it. its benefits in easy integration, maintaining speed and responsiveness of it.

4. Performance

If you compare native apps and flutter on the basis of its performance in the flutter code is written in dart and which excludes JavaScript bridge and it helps to boost its performance in terms of speed which is 60 FPS.

5. Dart

This is another reason why developers love flutter because Dart is an object-oriented, garbage-collected, class defined, language using a C-style syntax that trans-compiles optionally into JavaScript.

Let’s just understand a few key features of dart:

  1. AOT Dart uses ahead of time compilation and because of it not only it helps to start fast but also to customize its Flutter widgets.
  2. JIT Dart also uses JIT means just in time compilation which enables you to use the feature of hot reload.
  3. Garbage Collector Dart is also enabled with the garbage collector in the language it helps flutter to function smoothly and enables it to achieve 60 FPS. Dart has similarities with other languages and this quality makes dart so powerful for development.

6. Material Design

In every technology, there are some key features that make the technology different from others in the league and in the Flutter material design has this opportunity. For using the material design you only need to use this widget and it will enable you to material design guidelines throughout the app. While in native platforms it is not that easy.

7. Add to App

Another Feature of Flutter 1.12 is it makes developers enable to add flutter in the current Android and iOS app, Migration of an app in flutter is possible once, instead of creating it from the beginning.

Here in this video of Flutter dev, you can get an idea of doing it easily.

You can find out all the new features including this in this blog written by me mentioned below.

What’s New in Flutter 1.12?
As we all know Flutter has come up with new announcements in Flutter Interact which was recently held on Dec 11, 2019…medium.com

8. Testing

Testing has always been an important part and it the native and in the flutter, both have a bit the same testing procedure but there are also some differences that make it fast in a flutter.

Native

  • Unit Test
  • Integration Test
  • UI Test

Flutter

  • Unit Test
  • Integration Test
  • Widget Test

In native we have various testing frameworks for Unit Testing like JUnit and Mockito for running unit tests and Espresso for UI test.

In Flutter there are also three components of testing and the widget test is quite similar to UI test, you can also use Mockito by using Mockito package in the flutter, for integration test you can add a package flutter_driver.

9. Animation

In flutter, there are some inbuilt basic animations to make beautiful applications but if you want to add more animations in your app there is Rive (previously 2Dimensions)to make your wish completely true, by importing Rive directly you can add it.

10. Fuchsia

Fuchsia is being developed by Google which is an open-source operating system and as explained by Google flutter has been developed keeping Fuchsia in mind. These days it is a need of time a common operating system that can run on smartphones, desktop, embedded systems and many more and Fuchsia has its own micro-kernel called Zircon.

After these small discussions now its time to pay attention to whether Flutter will make it’s ground big if we compare to native, actually flutter is still in the development phase and new libraries and plugins are still adding in its armory. So we can hope new and big announcements on this.


Thanks for reading this article, if you find something you better know Please let me know, I will welcome it with full gratitude.


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 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 Facebook, GitHub, and Twitter for any flutter related queries.

Multi Theme Using Provider in Flutter

Themes have always been an Omnipotent part of User Interface for app developers. With the recent key advancements in app developing process, Customisation in themes is an apparent need of developers.

Flutter has although to whopping extent ease off the process of customising themes & their individual components. Here, In this article we are going to create Multi themes using provider state management technique :

For Beginner’s, Do Checkout this video of Google I/O’19 For Dark Theme:

Dark themes has been introduced in flutter which is easily applicable by either through the app settings or phone settings. Dark themes is a hot buzz nowadays as it reduce the luminous emission through screens which-in-turn helps in reducing the blue ray emitted by devices preventing eye strain, adjusting brightness to current lighting conditions, and facilitating righteous screen use in dark environments — also longevity of battery life.

This article assumes you have Pre-requisite knowledge about: Inherited Widgets. If you don’t know about Inherited Widget, these are some interesting articles about them, for example here :

Let’s Begin :

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
  • Add the current latest version of provider package under the dependencies in pubspec.yaml file.
dependencies:   
provider: ^latest version

2. Have a look at the snippet for better understanding:

As we can infer from the above snippet:

Multiprovider state management has been used for the state management in with its child as MyApp().Provider consist of ChangeNotifierProvider in which non-null create a ChangeNotifier which is automatically disposed up on its removal from widget tree.

In Class MyApp(), Consumer is used which Obtains Provider<T> from its ancestors and passes its value to the builder.Also, In MaterialApp routes and ThemeData elements are provided using model class.

Create Theme:

We can create multiple themes as referring to our needs via the help of panache ( a flutter theme editor) . Themes once created, we create a ThemeModel class to notify us of a theme change through with the help of notifylisteners each time a change is occurring so that it will notify them to its descendants:

setAccentTempShadeColor(Color value) {
_accentTempShadeColor = value;
notifyListeners();
}

Here, both option have been availed —

One involving Change of Primary maincolor from the Multi theme option and other giving some custom changes which can be made by picking the appropriate shadecolor from the colorpicker .Though here , I have restrained myself for only some custom changes but the list is growable as we have multiple attributes which can be changed up in MaterialApp.

Custom & Main Option:-

All the attributes can be mutated by selectively choosing the shadecolor from the colorpicker in the custom tab whereas the generic option will apparently change the primary main colour On-tapping the right container, tapping is made sure of with a display of Toast.

Using a Custom Font Family:

A discrete directory named fonts with font-family Gilroy has been added that is further defined in pubspec.yaml as-

fonts:
- family: GilroySemiBold
fonts:
- asset: fonts/gilroy.otf

which can be applied to textstyle for custom fonts also:

style: TextStyle( fontFamily: 'GilroySemiBold'),

you can also pass it in the main file so that it may be the Default font of your app.

That’s it. With just a few lines of code we can dynamically change the theme of our app. Let’s see what it looks like:

Check out the whole code and a motion gif here:

flutter-devs/flutter_multitheme_demo
A flutter App showing the use of multi theme in flutter. – flutter-devs/flutter_multitheme_demogithub.com

Also, Check the module used in the blog from here.

Closing Thoughts

Themes are a Quintessential tool in modern applications as they provide us with the ease of customising User-Interface of the app as per user needs. They also provide the app it’s fondness and customizability as per particular needs. The key purpose of this article is to avail you an Insight of How we can create multiple themes based flutter application using Provider State management technique.

If you have not used Themes, I hope this article has provided you with content information about what’s all about Multi-theme, and you will give it — a Try. Initiate using Themes for your apps. !!!


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 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 Facebook, GitHub, and Twitter for any flutter related queries.

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

Thank you for reading. 🌸

Flutter Testing: Let’s Observe

0

Flutter automated testing enables you to achieve higher responsiveness in your app because it helps to find bugs and other issues occurring in your app. It is also important in other perspectives like credibility as a developer.

Here comes a question which may come to your mind:

How can you know if your app is working or not if you have changed or added any features? And the answer is by writing test cases. So let’s understand how to do it.

We have 3 different testing features available

  1. Unit Test
  2. Widget Test
  3. Integration Test

Unit Tests

A unit test can be understood by its name, in the Unit test we test small parts of our code like single function, method or a class and it is very handy to do. It can be implemented by importing test package and if you want additional utilities for test flutter_test can be used.

Steps to Implement Unit Testing

  1. Add the test or flutter_test dependency.
  2. Create a test file.
  3. Create a class to test.
  4. Write a test for our class.
  5. Combine multiple tests in a group.
  6. Run the tests.

Till now we have understood how to import dependency so and let’s understand about the project structure

counter_app/
lib/testing_class.dart
test/
unit_test.dart

Now in your project, you can see that there is already a test folder in which we will create our own class for testing,

Let’s create a file testing_class.dart in which we will be multiplying two digits

Now write a class unit_test.dart in the test folder, where we will write this set of code, in this file there is a main() function and inside this function, we will write code for testing, as you can see in the “test” method object of testing class has been created and with the help of reference variable method of the testing class has been called and we are expecting the output value which should be the exact result.

And to test this code we will run the command(given below) in the terminal and observe the output of this.

flutter test test/widget_test.dart

Now let us understand the testing with the help of Mockito

Mockito is used to mock interfaces so that a dummy functionality can be added to a mock interface that can be used in unit testing.

Here we are going to understand how can we implement it.

Let’s understand it step by step

Create a simple project then delete the sample code from the main.dart file. then fix all the errors of class.

import 'package:flutter/material.dart';
import 'package:flutter_test_demo/home_page.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}

Now we are going to test our HTTP request and for this, we are using JSONPlaceholder to find the API link then we create a model class by using the response. you can also create it by using different JSON to dart converter sites.

// To parse this JSON data, do
//
// final userInfoModel = userInfoModelFromJson(jsonString);
import 'dart:convert';
UserInfoModel userInfoModelFromJson(String str) => UserInfoModel.fromJson(json.decode(str));
String userInfoModelToJson(UserInfoModel data) => json.encode(data.toJson());
class UserInfoModel {
int userId;
int id;
String title;
String body;
  UserInfoModel({
this.userId,
this.id,
this.title,
this.body,
});
  factory UserInfoModel.fromJson(Map<String, dynamic> json) => UserInfoModel(
userId: json["userId"],
id: json["id"],
title: json["title"],
body: json["body"],
);
  Map<String, dynamic> toJson() => {
"userId": userId,
"id": id,
"title": title,
"body": body,
};
}

Now we have a model class, after this, we need to make a separate class to make requests and get responses and for this, we would implement the most popular technique HTTP in api_provider class.

import 'package:flutter_test_demo/src/models/user_info_model.dart';
import 'package:http/http.dart' show Client;
import 'dart:convert';
class ApiProvider {
Client client = Client();
fetchData() async {
final response = await client.get("https://jsonplaceholder.typicode.com/posts/1");
UserInfoModel userInfoModel = UserInfoModel.fromJson(json.decode(response.body));
return userInfoModel;
}
}

Now its time to create a test class for testing, so we would be creating a file in the Test folder. when you will open this folder you will get an auto-generated file but we will delete this and create our own you can give any name to the file but remember one thing your file name should contain “_test” like api_provider_test.dart because if you don’t write then flutter would not be able to find it as a test file.

Now you need to import a few Packages to complete all the tests.

import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart';
import 'package:http/testing.dart';
import 'dart:convert';

Here HTTP package is used to use tools to mock HTTP requests and the flutter_test provides methods for testing.

Now it’s time to create a method for tests in api_provider_test.dart

import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart';
import 'package:http/testing.dart';
import 'dart:convert';
import 'package:flutter_test_demo/src/resources/api_provider.dart';
void main(){
test("Testing the network call", () async{
//setup the test
final apiProvider = ApiProvider();
apiProvider.client = MockClient((request) async {
final mapJson = {'id':1};
return Response(json.encode(mapJson),200);
});
final item = await apiProvider.fetchData();
expect(item.id, 1);
});
}

Here in the main() function we write the test method in which first we give a description of our test then we create the object of that api_provider class and by using its reference variable we will change the client() object into MockClient() actually MockClient is a package provided by ‘package:http/testing.dart’ which imitates an HTTP request instead of real request to the server as you can see in the above code.

In HTTP calls we make requests and get responses and we have already defined requests here.

apiProvider.client = MockClient((request) { });

And then we create response objects in this MockClient function

final mapJson = {'id':1};
return Response(json.encode(mapJson),200);

Here you can see the response object is returning the JSON object which is the body of the response and the second object is status code which is the success code of the response then we call the fetchData() which returns UserInfoModel object contains the Key ‘id’ and value “1” or not. Then in the expect method which is provided by test.dart package will compare the result we are expecting from fetchData() method.

Now let’s check whether the test cases are passing or not by running this command in your terminal.

flutter test test/api_provider_test.dart

Here api_provider_test.dart is your class name which you created for testing if your test cases pass the test you will get this response.

So this was all about unit testing in Flutter. Stay tuned for more articles related to other testing types.

Thanks for reading this article.

If you find it interesting Please Clap! and if you found anything wrong please let me know I would appreciate it for your contribution.

Connect with me on GitHub repositories.


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 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 Facebook, GitHub, and Twitter for any flutter related queries.

GraphQL and Flutter

0

If you are here that means you are seeking some information or knowledge or implementation technique of GraphQL, before going over the implementation of it with flutter you need to know what is it and why we need to implement it because without having a basic knowledge it might be a waste of time. So let’s take a look

What is GraphQL: It is a query language that allows us to create queries that will be executing on the server… Not Getting this bookish definition ??

Okay, Let me explain suppose if you are taking an exam and a few key points of any topic have been asked would you write whole info of that topic or specific points? Of course, key points because explaining it all would not be worthy, same in the GraphQL when you make API calls for the server you get no. of data fields but what if you need only two or three data fields from a huge collection? obviously you can use required data fields and all data fields which remained unused will not harm your app but in large scale projects, it reduces apps responsiveness so with the use of GraphQL we make queries for the specific data and we get exact data we required. it also helps especially when your internet connection is slow and then you need not fetch whole data because in the query you only request for specific data or only required data.

This was a small description about GraphQL and let us see

Here you can easily see that by using GraphQL server data is being fetched but in the query, only the name of the users has been asked and after pressing the top button, on the right side of the screen you can see the response that we got.

Now you would be thinking that it’s quite easy to make queries but how would a user get to know what kind of data the API is having. You need not be worry… GraphQL server also provides a schema of the API so you easily understand that

In this image of Documentation Explorer, there are two fields one is Query and the other is Mutation and by clicking on it you can find the required data for making query or mutation requests. This is my GraphQL API link you can try it.

So this was the introduction part now let’s implement it on fluter

Flutter Starts from here

First of all, you need to import a package of GraphQL in your pubspec.yaml

graphql_flutter:

You can find the latest version here and import

import ‘package:graphql_flutter/graphql_flutter.dart’;

GraphQL basically does two things

  1. Query: Query is used to fetching the required data.

2. Mutation: Mutation is used to update and insert data like for post/delete/put requests.

Then the first thing which comes to work with GraphQL is Client, and to use the client we first need to use link and cache here we are using httpLink as a link and OptimisticCache as a cache, We are also using ValueNotifier which is used to notify their listener when any value is changed.

Then we wrap our whole page with GraphQLprovider and after that, we will be able to make requests to the GraphQL server without specifying the endpoint and header and now we need to pass the query and then GraphQL provider will take care of it, it means it will perform actions for us.

In the query, there are two fields,

  1. options: Options are used to send the query you want to send.
  2. builder: builder is the same builder of flutter which is used to manage the states

In options, we use QueryOptions and use the documentNode function to pass the query which we have made and pass this through gql() because it parses GraphQL query strings into the standard GraphQL AST.

And this is the query that is being used to fetch the list of the data for this you can also use for testing in this GraphQL server. (you can see in the above picture)

query{
artworkAttributionClasses
{
name
}
}

Now in the builder function, we will fetch the data from the server and show in the screen,

For the full source code, you can click here

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

and for more knowledge about GrpahQL, please visit

graphql_flutter | Flutter Package
A GraphQL client for Flutter, bringing all the features from a modern GraphQL client to one easy to use package.pub.dev

It was a small description about GraphQL.

Thanks for reading this article if you find anything that could be improved please let me know, I would love to improve.


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 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 Facebook, GitHub, and Twitter for any flutter related queries.