Home Blog Page 24

Custom Paint In Flutter

0
Custom Paint in Flutter
Custom Paint in Flutter

A widget that provides a canvas for drawing on during the paint phase. To paint in Flutter, use the CustomPaint widget, which basically takes the size of its parent if the child is not provided. Two methods are overridden by the CustomPaint subclass: paint() and shouldRepaint().

What is the CustomPaint in flutter ?

Flutter allows developers to use every pixel on the screen and draw custom shapes. This has been one of Flutter’s main selling points. We use the Custom Paint class to accomplish this.

Custom Paint is a Flutter SDK widget that allows you to draw various shapes on a canvas.

Characteristics of Custom Paint:

This are characteristic of flutter custom paint widget:

painter: The painter who paints before the child. Create a class that extends CustomPaint in this case.

size: The size of this CustomPaint is initially equal to Size.zero, which means that if you do not define a size or a child, the CustomPaint will not appear.

foregroundPainter: The painter who paints after the children. It also requires a class that extends Custom Painter.

child: The widget below this widget tree.

basic syntax:

CustomPaint(
  painter: ,
  foregroundPainter: ,
  size: ,
  child: ,
)

You have two options when using CustomPaint: specify a size property without a child or use the child property with a widget.


What is the Importance of using Custom Paint in Flutter:

Custom Paint essentially ensures the UI design of those components that cannot be derived from the regular shapes provided by Flutter. It means that you can draw your own shapes by using it. This widget distinguishes flutter from its competitors in terms of customizability. Custom Paint is: A widget that serves as a canvas for drawing during the paint phase.

To paint in Flutter, use the Custom Paint widget, which basically takes the size of its parent if the child is not provided.

How to use CustomPainter in a class


Two methods are overridden by the Custom Paint subclass: paint() and shouldRepaint() .

class Rectangle extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    /// implement paint here
  }

  @override
  bool shouldRepaint(covariant CustomPaint oldDelegate) {
    /// implement shouldRepaint
    throw UnimplementedError();
  }
}

As shown above, the paint() method will be called whenever the object needs to be repainted, and it will take two parameters: Canvas and Size. As we will see later, the Canvas class is used to create various shapes, and the Size method returns the size of this canvas, which includes both the height and width properties that you can use when creating shapes.

When a new instance of the CustomPaint is created, the shouldRepaint() method is called. If the new instance’s property value is always the same, the method can simply return false.

The paint() function returns the Canvas instance, which we can then use to call the drawing functions. It also gives us the canvas size, which is either the child size or the size parameter.

Next, let’s look at the actual drawing logic by investigating the Canvas class.

Painting On Canvas

Most people who have used the CustomPaint widget a few times should be familiar with what has been shown thus far. In this section, we’ll look at drawing on a canvas and all of the possibilities it provides.

All of the drawing will be done within the CustomPaint’s paint() method.

Painting classes that are commonly used

Paint

The paint class stores information about painting or drawing objects on the screen. Here are a few key characteristics:

color: Determines the color of the painting.

strokeWidth: The thickness of each drawn line stroke

var paint = Paint()
      ..color = Colors.yellow
      ..strokeWidth = 20.0;

Rect

A Rect class generates a virtual rectangle with width and height, which is typically used to draw an actual rectangle or set bounds for a shape inside. A Rect can be made in a variety of ways, including:

Rect.fromCenter(
      center: Offset(100, 100),
      width: 50,
      height: 80,
    );

Path

The Flutter Custom Paint includes functions for drawing common shapes like circles and rectangles. Paths, on the other hand, allow us to trace out custom shapes when we need to draw them.

  Path()
      ..moveTo(0, 0)
      ..lineTo(100, 100)
      ..lineTo(0, 100)
      ..lineTo(0, 0);

Flutter Custom Paint Widget Example

Let’s start drawing using CustomPaint 

Draw a Rectangle

Before you can add shapes to the canvas, you must first understand the coordinates. The canvas will have coordinates (0,0) in the upper left corner, as in the web, and coordinates (max width,0) in the upper right corner. The coordinates (0,max height) will be in the lower left corner, while the coordinates (max width,max height) will be in the lower right corner.

To draw a rectangle, we must first create a Flutter Custom Paint widget:

CustomPaint(
    size: Size(size.width * 0.5, size.height * 0.1),
    painter: Rectangle(),
)

We give the Flutter Custom Paint its own size here, so the canvas will fit within that size. The Rectangle class must then be created:

 bool? isFilled;
  Rectangle({this.isFilled});
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint();
    paint.color = Colors.shade900;
    if(isFilled != null){
      paint.style = PaintingStyle.fill;
    }
    else {
      paint.style = PaintingStyle.stroke;
    }
    paint.strokeCap = StrokeCap.round;
    paint.strokeJoin = StrokeJoin.round;
    paint.strokeWidth = 5;
    Offset offset = Offset(size.width * 0.5, size.height);

    Rect rect = Rect.fromCenter(center: offset, width: 50, height: 50);
    canvas.drawRect(rect, paint);
  }

  @override
  bool shouldRepaint(covariant Rectangle oldDelegate) {
    return false;
  }

This would result in the following:

If we look at the code above, we can see that we are first using the Paint class, which is used to style the canvas. We give it the color blue, and because isFilled is null, PaintingStyle.stroke is used to paint the rectangle’s edges, and we also give it the Paint object width 5. Then we make an Offset that is half the width and height of the canvas. Following that, we create the Rect object by calling Rect.fromCenter, which constructs a rectangle based on its center point, width, and height. Finally, we invoke the drawRect method, passing it the arguments rect and paint.

Another option is to use the Flutter  Custom Paint widget’s child property:

CustomPaint(
    child: Container(child: const Text("Hello World!"),),
    painter: Rectangle(isFilled: true),
),

The canvas would now be the size of the Container, and because we’re using the painter property, the text would appear above the rectangle. You must use the foregroundPainter property if you want the text to appear behind the rectangle.

This would result in the following:


Drawing a Line

To draw a line without using the Flutter Custom Paint widget, you must also create another class that extends the Flutter Custom Paint class:

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint();
    paint.color = const Colors.blue.shade900;
    paint.strokeWidth = 5;
    paint.strokeCap = StrokeCap.round;

    Offset startingOffset = Offset(0, size.height);
    Offset endingOffset = Offset(size.width, size.height);

    canvas.drawLine(startingOffset, endingOffset, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }

We also use the Paint object to style the Line in this case, and we give it a width of 5. Then we need to make a starting point and an ending point to represent the beginning and end of the line. So, we specify that the starting point must be on the X-axis with coordinate 0 and the Y-axis with maximum height, while the end point must be on the X-axis with maximum width and the Y-axis with maximum height, resulting in a straight horizontal line.

This would result in the following:


Drawing a Circle

You can draw a circle on the canvas object by calling the drawCircle() method:

@override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint();
    paint.color = Colors.blue.shade900;
    paint.style = PaintingStyle.fill;
    paint.strokeCap = StrokeCap.round;
    paint.strokeJoin = StrokeJoin.round;

    Offset offset = Offset(size.width * 0.5, size.height);
    canvas.drawCircle(offset, 30, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return false;
  }

As with the other shapes, we style the canvas with the Paint object and then use the Offset object to determine the position of the circle in relation to the size of the canvas.

This would result in the following:


Drawing an arc

Using the canvas, we can draw an arc of a circle. drawArc() is a method for drawing an arc. This simplifies the creation of Pacman:

void paint(Canvas canvas, Size size) {
    var center = size / 2;
    var paint = Paint()..color = Colors.yellow;

    canvas.drawArc(
      Rect.fromCenter(
        center: Offset(center.width, center.height),
        width: 50,
        height: 50,
      ),
      0.5,
      2 * pi - 0.8,
      true,
      paint,
    );
  }

This would result in the following:


Drawing Rounded Rectangles


Round Rectangle(RR), like the Rect class, represents rounded rectangles in Flutter. This class contains information about the corner radii as well as basic rectangle information. If all corner radii are the same, you can use a normal Rect and the corner radius to create a rounded rectangle. The final rounded rectangle is painted to the screen by the drawRRect() method:

 @override
void paint(Canvas canvas, Size size) {
  var center = Offset(size.width/2, size.height/2);
  var roundedRectangle = RRect.fromRectAndRadius(
    Rect.fromCenter(center: center, width: 300.0, height: 150.0),
    const Radius.circular(32.0),
  );
  var paint = Paint()
    ..color = Colors.blue.shade900
    ..style = PaintingStyle.fill;
  canvas.drawRRect(roundedRectangle, paint);
}

This would result in the following:


Drawing Ovals

Ovals are more difficult to draw than circles because they can take on a variety of shapes and sizes. You can use the same Rect class as before to define the oval’s boundaries and the drawOval() method to paint it on the screen:

@override
void paint(Canvas canvas, Size size) {
  var center = Offset(size.width/2, size.height/2);
  var rectangle = Rect.fromCenter(center: center, width: 300.0, height: 150.0);
  var paint = Paint()..color = Colors.blue.shade900..style = PaintingStyle.fill;
  canvas.drawOval(rectangle, paint);
}

This would result in the following:


Drawing Paint

The Canvas class’s drawPaint() method simply paints the entire canvas with the given paint:

@override
void paint(Canvas canvas, Size size) {
  var paint = Paint()..color = Colors.blue;
  canvas.drawPaint(paint);
}

This would result in the following:


Drawing Color

While the drawColor() method appears to be similar to the previous method in that paint is applied to the entire canvas, it differs in that this method adds a ColorFilter to the canvas rather than simply painting the entire canvas one color. You can also specify the BlendMode to control how the new color and the color on the existing canvas blend together. The code is as follows:

@override
void paint(Canvas canvas, Size size) {
  canvas.drawPaint(Paint()..color = Colors.blue);
  canvas.drawColor(Colors.purple, BlendMode.plus);
}

This would result in the following:

This matches the existing content on the canvas:


Drawing Text

A call to drawParagraph() is hidden deep within the Text widget and finally paints the given text on the screen. The majority of what the Text widget does is related to layout and sizing rather than text rendering. Here’s a simple example of painting ‘Demo Text’ on the screen:

@override
void paint(Canvas canvas, Size size) {
  var center = size / 2;
  var style = const TextStyle();

  final ui.ParagraphBuilder paragraphBuilder = ui.ParagraphBuilder(
    ui.ParagraphStyle(
      fontSize: style.fontSize,
      fontFamily: style.fontFamily,
      fontStyle: style.fontStyle,
      fontWeight: style.fontWeight,
      textAlign: TextAlign.justify,
    ),
  )
    ..pushStyle(style.getTextStyle())
    ..addText('Draw custom paint  text');
  final ui.Paragraph paragraph = paragraphBuilder.build()
    ..layout(ui.ParagraphConstraints(width: size.width));
  canvas.drawParagraph(paragraph, Offset(center.width, center.height));

This would result in the following:


Drawing Vertices

The Canvas’s drawVertices() method is a convenient way to draw connected vertices, allowing you to easily create grids and patterns. The method can generate three types of patterns:

i) Triangles: Selects three adjacent points from the list, shapes them into a triangle, and then moves on to the next. (Each point is used only once.)

ii) Triangle Strip: Draws a triangle from each set of three adjacent points. (Each point may be used multiple times.)

iii) Triangle Fan: The first point serves as the center point, with each subsequent point serving as a triangle vertex. (In all triangles, the first vertex is used; all others may be used up to twice.)

@override
void paint(Canvas canvas, Size size) {
  var vertices = ui.Vertices(VertexMode.triangleStrip, [
    Offset(100, 100),
    Offset(200, 100),
    Offset(350, 300),
    Offset(400, 100),
    Offset(500, 300),
    Offset(700, 200),
  ]);
  canvas.drawVertices(
    vertices,
    BlendMode.plus,
    Paint()..color = Colors.blue,
  );
}

This would result in the following:


Adding Polygons

Polygons can be made by defining multiple points and then passing them along a path. addPolygon() is a method for adding polygons. The method also includes a boolean that can be used to specify whether the polygon should be closed after the final defined point. Here’s an illustration:

@override
void paint(Canvas canvas, Size size) {
    var path = Path();

  var points = [
        Offset(100, 100),
    Offset(150, 100),
    Offset(200, 200),
    Offset(150, 200),
    Offset(125, 125),
    ];

  path.addPolygon(points, true);
}

Git link :

https://github.com/Mitali8620/custom_paint_app_flutter.git

I hope this blog has given you enough information to experiment with custom paint in your flutter projects. Thank you for taking the time to read this article.

What if I’m mistaken? Please let me know in the comments section. I’d like to improve.

Clap 👏 If you found this article useful.

The source code for the Flutter CustomPaint Demo is available on GitHub.

Thank you …have a Happy day!!

10 tips to improve programming logic skills

0
How to Improve Programming Logic

Here are 10 tips on:

How to improve logical thinking for programming.

1. Keep the concept clear

Always Keep your base strong, I mean to say keep basic of a programming language strong. In order to solve any real world problem by coding you should be cleared with the concepts.

2. Be Consistent

Is you are beginner in coding/programming practicising coding on daily will build you core. Take one problem: solve it, There is a quote : “Practice Makes a man perfect”. The same applies in programming world.

Practicing consistently will improve you coding and logic thinking.

3. Think with a Pen and Paper

Then you have coding don’t directly start typing on you IDE, “Programming is Thinking first, Typing later”. Think clearly about the problem and how you can solve it, and in how many ways. To find a best ways use Pen & Paper.

4. Learn New Things daily

Keep yourself updated with latest technologies arrived in software world, Any courier field you choose of has a life long learning. You aim in life should be in solving latest problem that come in your life or in code, don’t be stuck into a old pattern or algorithm logic and search for success.

5. Mathematical Concepts should be strong

In programming, Mathematics plays information role when applying logic while coding. Be good in Maths took to improve your programming skills.

No need to be super strong in mathematics but you should at least have high school level math knowledge.

6. Build Projects

The best thing to do to improve logic in coding is by building real project by yourself like a full stack developer who build complete project by himself by this you will get good knowledge in frontend as well as backend.

All you need to do is search for a company who assigns freelances projects.

7. Preparations of notes

Making Notes is boring, But preparing it will makes you learn new technology and you will remember for a long and also the concept will be clearer as you theoretically write in on a book.

8. Break the problem into smaller sub-tasks.

Once you get a real time projects to be done, break a complete project into small small tasks. Like this you can learn faster and complete it sooner.

9. Participate in coding events

If there is any coding competition going on in your town, take part in those coding event that will make your coding logic to build faster, And you will come across to many programming and explore the coding world more.

10. Be Patience in learning

In life to achieve anything you need to be patience. Likewise to develop coding logic, you have be consistent in practicing and patience.

I seen many people who comes into programming and after few days they leave the field just because they go stuck into a problem.

AI-generated images in Flutter using OpenAI

0
OpenAI Image Generation In Flutter

Hi Guy’s Welcome to Proto Coders Point. In this Flutter Article we will make use of OpenAI DALL-E 2 API and explore the super power of OpenAI, By creating an flutter application that can convert a given Text into an AI image. You will learn how to we make use of OpenAI API to generate a unique & stunning AI realistic image , and how to implement it into our Flutter app to generate AI Image from a given Text Sentence.

In below Flutter Video Tutorial on Youtube, I have cover everything from setting up the API, to making API calls and displaying the generated images in the flutter app. By the end of this tutorial, You will learn how to use OpenAI DALL-E 2 API to convert text to AI generated image and show it in your own flutter app and create a beautiful & realistic AI images.

Creating an Account

Step 1: Create an account in openai.com

In browser, search for openai.com and SignIn using Google account or any other account.

Step 2: You need to activity a billing

Added your credit card for billing, Initially OpenAI gives you $15 free to generate images from Text. Then you will be charged.

Here are charges depending on the Image Size you order for:

RESOLUTIONPRICE
1024×1024$0.020 / image
512×512$0.018 / image
256×256$0.016 / image

Step 3: Generate a openai API key

Create a Flutter App to Generate an AI Image from Text by using open ai image generation

Implementing OpenAI in Flutter App

Step 1: Install http package

As we are going to make internet call in our flutter app generate an AI Image to open ai API, we need a http package to do so.

In flutter project, open pubspec.yaml file and under dependencies section add http package.

dependencies:
  flutter:
    sdk: flutter
  http:

Step 2: Import the http class

In main.dart file of flutter project, Import http.dart file

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

Step 3: Create a async function

Now, Create a function generateAIImage() that makes a HTTP call to OpenAI DALL-E Image Generation API by passing desired Text of which you want AI to generate a Image.

void generateAIImage() async{
    if(inputText.text.isNotEmpty){
      
      var data ={
        "prompt": inputText.text,
        "n": 1,
        "size": "256x256",
      };
      
      var res = await http.post(Uri.parse(url),
          headers: {"Authorization":"Bearer ${apikey}","Content-Type": "application/json"},
          body:jsonEncode(data));

      var jsonResponse = jsonDecode(res.body);

      image = jsonResponse['data'][0]['url'];
      setState(() {

      });
      
    }else{
      print("Enter something");
    }
  }

The above function will make a http post request to openai, so in this http request we are passing the data and in header we are passing openai authorization api key.

In request body we need to pass this parameters

prompt: a Text of which AI should generate an image.

n: Number of different image to be generate of the given text.

size: The size of the generated images.

Step 4: Show the image response in app

Once the above function return the response, we need to parse the JSON response from the API and extract only url of the generate image.

And thus make use of Image.network() flutter widget to display the AI generated image in flutter app.

Complete Source Code – Flutter open ai image generation

main.dart

import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

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

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController inputText = TextEditingController();
  String apikey = 'tsk-nTRcf1113XPQht7r22T3Bvadapavlb5kFJYz1yz5b4xifuyzpoiyom2ooNIQehy';
  String url = 'https://api.openai.com/v1/images/generations';
  String? image;
  void getAIImage() async{
    if(inputText.text.isNotEmpty){
      
      var data ={
        "prompt": inputText.text,
        "n": 1,
        "size": "256x256",
      };
      
      var res = await http.post(Uri.parse(url),
          headers: {"Authorization":"Bearer ${apikey}","Content-Type": "application/json"},
          body:jsonEncode(data));

      var jsonResponse = jsonDecode(res.body);

      image = jsonResponse['data'][0]['url'];
      setState(() {

      });
      
    }else{
      print("Enter something");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Open AI DALL.E"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            image != null ? Image.network(image!,width: 256,height: 265) : Container(child: Text("Please Enter Text To Generate AI image"),),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: TextField(
                controller: inputText,
                decoration: InputDecoration(
                    hintText: "Enter Text to Generate AI Image",
                    filled: true,
                    fillColor: Colors.blue.shade100,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                      borderSide: BorderSide.none,
                    )
                ),
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          getAIImage();
        },
        tooltip: 'Generate AI Image',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

App Lifecycle In Flutter – A complete guide

0
Flutter LifeCycle
Flutter LifeCycle

Communication between UI widgets and Flutter life cycle methods.

The Flutter App’s lifecycle displays how the application will modify its State. It aids in comprehending the principle underlying the easy development of our apps. Since everything in Flutter is a widget, we should consider Flutter’s widget before considering its lifecycle.

flutter lifecycle

The Lifecycle of an Flutter App

The Lifecycle of a Flutter App shows how the app will alter its State. It aids in comprehending the idea underlying the fluid movement of our applications. I want to impart everything I’ve learned about creating widgets in Flutter. Let’s start…

Widgets refer to all of the user interface elements that are visible on the screen. Based on the widget’s capacity to be reloaded during runtime, widgets may be roughly classified into two classes.

Flutter has majorly two types of widgets :

  • Stateless
  • Stateful Widget.

We must comprehend the differences between the two widgets before learning about the Lifecycle.

1. Stateless Widget :

Stateless In Flutter, a widget is a component whose state, once generated, cannot be altered; examples include variables, buttons, icons, and other components whose states cannot be altered in order to access data. replaces the build method and then returns a widget. When the UI depends on data contained within the object itself, we utilize it. In short , Stateless widgets are ones that do not alter dynamically during execution and do not need managing the state.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

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

  @override
  Widget build(BuildContext context) {
    return const Container();
  }
}

2. Stateful Widget :

A stateful widget keeps track of data and reacts to everything the data does while being used by the application. It is rendered several times over its lifespan since it is a changeable widget.

When a user dynamically changes the application screen, we use this. The fact that this widget features a status widget, which lets everyone know when anything has changed on our screen, makes it the most significant of all the widgets. In short , Stateful widgets are ones that keep track of the current state and allow for dynamic runtime changes to the user interface.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

Thus, as “Stateful Widgets” are those that handle the State, we will focus on them when we talk about the LifeCycle of Flutter.

Lifecycle Flow Chart For Flutter App.

Lifecycle Flow Chart For Flutter App

Stages of Flutter App Lifecycle:

The state and how it changes affect the life cycle. We may describe the flutter life cycle based on a stateful widget’s state. The life cycle stage:

  • createState()
  • initState()
  • didChangeDependencies()
  • build()
  • didUpdateWidget()
  • setState()
  • deactivate()
  • dispose()

Due to the creation and re-construction of the Widgets and their State, you’ll see a lot more “states” for the making than the destruction.Let’s explore more into life cycle stages:

1)  createState()

The Flutter framework will give instructions to construct a method called createState() in override when we create a stateful widget. An instance of the state that this method is linked with will be returned.
I used the stateful class name “MyHomepage” in this life cycle example. When the ‘buildContext’ is assigned and located on a tree, all widgets’ bool mounted values change to true. Until dispose is called, the value will be retained.
class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState(); 
}

2) initState()

This tactic is taken into account when the Widget is created in an engaging manner and is called precisely once for each State object. The initState() function will execute any characterised or added code first, even before the widgets are constructed.

This function must call super.initState(), which executes the parent widget’s initState (Stateful widget). Your variables, objects, streams, AnimationController, and other items may all be initialised here.

@override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

3)  didChangeDependencies()

When the widget is created for the first time, this function is invoked immediately after initState(). If a modification is required and your StatefulWidgets depend on an InheritedWidget, they will call again.There aren’t many functions you can include, such as variable re-initializations and API requests reliant on parent data changes.

@override
void didChangeDependencies() {
  super.didChangeDependencies()
}

4) build()

This approach serves as the primary technique since it is essential to the presentation of all widgets. Every time we need to display UI Widgets on the screen, it is called.

The Flutter framework changes the build() method whenever you need to update your UI or, alternatively, on the off chance that you hit hot-reload!. You may use setState(), which instructs the framework to once again run the form function, if you need to specifically redesign the UI whenever any information is changed.

@override
Widget build(BuildContext context) {
  return Container()
}

5) didUpdateWidget()

When the parent Widget makes a modification and the UI has to be redrew, it will be invoked. It basically runs every time we hot reload the programme to check for widget changes.

When a parent widget has to edit a child widget with a comparable Runtime Type because the parent’s properties or designs have changed, didUpdateWidget is triggered. This turns away from the new widget and accepts the arrangement modifications made by it.

@protected
void didUpdateWidget(MyApp oldWidget) {
 super.didUpdateWidget(oldWidget);
}

6)  setState()

The framework schedules a build for this State of object after being informed by the setState() function that the internal state of the object has changed in a way that might affect the UI.

Calling this function after the framework calls dispose is incorrect.

void function(){
 setState(() {});
}

7)  deactivate()

This approach is taken into account when the State is eliminated from the tree, but it may also be re-inserted into the tree at a different location.

This approach is taken into account when the widget is not yet connected to the Widget Tree but may very likely be added at a later time. The part when you utilise Navigator is the finest example of this. Deactivate is used when a client wants to return to the previous screen after pushing to the next one, in which case the widget will once more be added to the tree.

@override
void deactivate(){
 super.deactivate();
}

8)  dispose()

This approach, which is crucial, basically runs counter to the initState() function. It is taken into account when the item and its State ought to be permanently removed from the Widget Tree and won’t ever reassemble.

You may dismiss documents, cancel timers, dispose of animation controls, unsubscribe from streams, and more here. You can ultimately provide each and every asset in this plan. Currently, if the widget is later added to the widget tree again, the entire lifespan will be repeated.

When removing something permanently, such as when releasing a resource produced by an item or stopping animation, we employ this technique.

@override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

Flutter App LifeCycle – Code Example

Create a new dart file called widget_lifecycle_demo.dart inside the lib folder. And paste below code into this.

import 'package:flutter/material.dart';
class LifeCycleDemoScreen extends StatefulWidget {
 @override
 _LifeCycleDemoScreen State createState() => _LifeCycleDemoScreen State();
}

class _LifeCycleDemoScreen State extends State<LifeCycLifeCycleDemoScreen leExm> with WidgetsBindingObserver {

 @override
 void initState() {
   super.initState();
   WidgetsBinding.instance!.addObserver(this);
   print("initState");
 }

 @override
 void didChangeAppLifecycleState(AppLifecycleState state) {
   super.didChangeAppLifecycleState(state);
   print('AppLifecycleState: $state');
 }

 @override
 void dispose() {
   WidgetsBinding.instance!.removeObserver(this);
   super.dispose();
 }

 @override
 void deactivate() {
   // TODO: implement deactivate
   print("deactivate");
   super.deactivate();
 }

 int _counter = 0;

 void _incrementCounter() {
   setState(() {
     _counter++;
   });
 }

 @override
 Widget build(BuildContext context) {
   print("build");
   return Scaffold(
     appBar: AppBar(title: Text("Flutter Widget Lifecycle")),
     body: Center(
       child: Column(
         mainAxisAlignment: MainAxisAlignment.center,
         children: <Widget>[
           Text(
             'You have pushed the button this many times:',
           ),

           Text(
             '$_counter',
             style: Theme.of(context).textTheme.headline4,
           ),
           SizedBox(height: 8.0,),
         ],
       ),
     ),
     floatingActionButton: FloatingActionButton(
       onPressed: _incrementCounter,
       tooltip: 'Increment',
       child: Icon(Icons.add),
     ),
   );
 }
}

Conclusion

I’ve described the fundamentals of the App Lifecycle in a flutter in the post; you may change the code to suit your preferences. This was a brief introduction from my end to the app life cycle on user interaction, and it functions using Flutter.

I’m hoping that this post will provide you enough knowledge to set up the App Lifecycle in your Flutter applications. We’ll demonstrate the Flutter app’s lifecycle for you. This blog post looked at the flutter app’s lifetime. I’m hoping that this blog will better your understanding of the life cycle. Please give it a try.

Thank you for reading this post.  

Clap 👏 If you find this post useful. Have a nice day………….

Retrieving a List of Files in a Directory using Node.js

0
nodejs list files in directory

Hi Guy’s Welcome to Proto Coders Point, In this article let’s check out how to list files in a folder/directory using node.js.

In Node.js, we can make use of fs module with promises (fs.promises) to asynchronously list out all the files in a directory.

Example on how to list all files in a directory using NodeJS

Below is my nodejs project structure, which has a files folder with document such a image, text files. I want to list all the files using nodeJS code.

nodejs project structure

In NodeJS fs library module, we can make use of fs.readdir() function to get list of files in defined directory.

Here is an example on How to use fs.readdir() function in nodejs

const fs = require('fs');
const path = require('path');

const directoryPath = path.join(__dirname, 'files');  // here files is my folder name.

fs.readdir(directoryPath, (err, files) => {
    if (err) {
        return console.log(`Unable to scan directory: ${err}`);
    }
    files.forEach((file) => {
        console.log(file);
    });
});

output

nodejs example to list all files contained in a directory

In above code example, ‘path.join()’ function is used to concat path of your project directory + the directory name you provide. Then fs.readdir() function takes parameter that is the ‘directoryPath’ generated and in second argument is a callback function that will list the array of the files in the directory.

Flutter Offstage widget to hide/show any widget

0
Flutter Offstage widget

Hi Guy’s Welcome to Proto Coders Point. In this Flutter tutorial will check how to programmatically hide show widget in flutter app.

Flutter provides a inbuilt widget called “Offstage”, which is been used to hide or show any widget programmatically depending on user action/event.

Video Tutorial

Syntax of Flutter Offstage widget

 Offstage(
          offstage: true or false,
          child: <Any Child Widget>
      ),

Flutter Offstage widget has a property ‘offstage’, which accept Boolean value.

The child widget is hidden when the offstage property is set to true.

Likewise if property is set to ‘false’, the child widget is shown.

How to use OffStage Widget in flutter

Here’s an example of how to use the Offstage widget to conditionally hide or show a container with icon widget(or any widget):

 Offstage(
              offstage:isHidden ,
              child: Container(
                width: 100,
                height: 100,
                color: Colors.blue,
                child: Icon(Icons.flutter_dash,size: 70,color: Colors.black,),
              ),
       ),

In above snippet code example, The Container widget is been wrapped with Offstage widget, and will be hidden if 'isHidden' is set to true, and will be shown if the 'isHidden' value is set to false.

How to Programmatically hide/show widget in flutter using OffStage

You can also hide/show any widget depending on the state of another widget.

Complete source code on how to use Offstage widget in flutter

import 'package:flutter/material.dart';

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

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

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

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
bool isHidden = false;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Offstage(
              offstage:isHidden ,
              child: Container(
                width: 100,
                height: 100,
                color: Colors.blue,
                child: Icon(Icons.flutter_dash,size: 70,color: Colors.black,),
              ),
            ),
            SizedBox(height: 20,),
            ElevatedButton(onPressed: (){
                setState(() {
                  isHidden = !isHidden;
                });
            }, child: Text(isHidden? "Show":"Hide"))
          ],
        ),
      )
    );
  }
}

Here In above example, I have used a button to toggle and show/hide widget in flutter.