Home Blog Page 20

Exploring the Potential of Google Bard AI and OpenAI (chatgpt)

0
google bard ai vs chatgpt
bard ai vs chatgpt

The growth of Artificial Intelligence (AI) technologies has seen a significant boost in recent times. Notable among these advancements are Google’s Bard AI and OpenAI’s Generative Pre-trained Transformer (GPT). This article delves into the capabilities of Google Bard AI and OpenAI’s GPT and examines their usage in various industries. Additionally, we will explore ways to improve existing systems and processes using these technologies. The article will also address the limitations of these technologies and predict future advancements. Lastly, it will touch upon how organizations can use these technologies to gain a competitive edge.

Google bard AI and The pre-trained transformer OpenAI

Google’s Bard AI and OpenAI’s Generative Pre-trained Transformer i.e ( GPT) have took the Artificial Intelligence (AI) industry way high. Google created its own AI system names “Bard AI” using which a software developer can build a complete new AI applications. It includes an AI engine, a collection of machine learning models, and an open source development platform.

OpenAI’s Generative Pre-trained Transformer (ChatGPT) is an advanced language model which is been trained completely by give massive amount of text data to it. This chatGPT model generate given text into a remarkable human-like fluency, This AI is so accurate that it don’t make any grammatically and syntactically mistakes. More over, it has the ability to think and provide text in more natural and more realistic. ChatGPT is best in generating text automatically based on given context by the user.

Applications of Google Bard AI and OpenAI Generative Pre-trained Transformer

Google’s Bard AI and OpenAI’s Generative Pre-trained Transformer (GPT) are leading-edge AI innovations created by Google and OpenAI in recent times. Bard AI, developed by Google, is a natural language processing system that can generate text. It uses a recurrent neural network, which has been trained on a vast amount of text data, to generate new text and accurately convey the intended meaning of the input text.

GPT is an advanced deep learning model that is built on a transformer architecture. It has the ability to generate text that is both semantically and syntactically similar to the input. This cutting-edge technology can be utilized for a variety of text-related tasks, including summarization, question-answering, dialogue generation, and more.

Google Bard AI & OpenAI GPT are being increasingly used in various applications such as natural language processing, machine translation, dialogue systems, document summarization and more.

Google Bard AI has been used to create a deep learning system that can generate text in response to user queries.

OpenAI GPT has been used to create a text-to-speech system that can generate audio narration of the content. Both these technologies have been used to create powerful AI applications that can improve existing systems and processes.

They are also utilised for more artistic purposes like making music and videos. Future applications will make greater use of these AI technologies, which will also keep developing and getting better.

Benefits of Google Bard AI and OpenAI Generative Pre-trained Transformer

Bard AI is a Natural Language Processing (NLP) tool developed by Google. Bard is basically designed to help software developer to build and improve their applications by teaching the AI system human language. As you all know that AI-powered tool makes use of the latest technologies such as speech recognition, natural language processing, and machine learning to provide developers with an easy-to-use platform that can be used to create applications.

OpenAI GPT model is an AI-powered language model developed by OpenAI. GPT is a large-scale language model that uses deep learning and transformer architectures to basically to generate human-like texts. ChatGPT will keep learning by the question usually asked by peoples and it has the ability to generate text based by the context provide to it. The model is pre-trained on a large amount of data and can be used to generate text in various languages and various people for different country ask chatGPT in various languages.

Limitations of Google Bard AI and OpenAI Generative Pre-trained Transformer

Google Bard AI and OpenAI (GPT) are two of the most progressed Artificial Intelligence (AI) technologies on the market today i.e. 2023. as you all know that Google Bard AI is new in AI world and is a deep learning platform that uses natural language processing to understand and generate written content to the users. GPT is an AI-powered tool that has the ability to generate text, images, and audio, videos.

The measure limitation of Google Bard AI and OpenAI GPT is that they make use of statistical models, Which simply means looking into statistical data it has there might be some situation where the output given contain errors in it.

but this AI system can learn from the mistakes and revolutionize the human being use it . I simply want to say that this AI technologies continue to learn, evolve and improve itself as we human being make mistakes are learn for the mistakes.

Conclusion

In conclusion here is, Google’s Bard AI and OpenAI’s (GPT) has opened the gate in looking the world in advancement of A.I technologies They may be used to enhance current procedures and systems and discover fresh possibilities. While these technologies has limitations at the moment, research and development are ongoing, which might lead to many more uses and applications. Finally, Google Bard AI and GPT have the potential to transform the way we interact with machines and help us to construct more intelligent, automated systems.

Stopwatch-timer in Flutter (with or without package)

0
How to Implement Stop Watch in Flutter
stop watch

It shows how the stopwatch timer will function in your flutter applications. It displays when the code is successfully executed, the user presses the start timer button, the countdown timing begins, and the user also presses the stop and cancel timer buttons. It will be displayed on your devices.

Returning to the main topic of this article, let’s make a stopwatch app. There are some posts on how to build a stopwatch (such as this one), but I’d like to share an alternative method.

How does a stopwatch work as a timer?

The elapsed time can be obtained in a variety of formats, including elapsed, elapsedMilliseconds, elapsedMicroseconds, and elapsedTicks. Start the stopwatch by calling start. Use stop to stop or pause the stopwatch. When only temporarily pausing, use starts to resume.

Flutter has a Stopwatch class. It can be started and stopped, and the elapsed time is displayed in the elapsedMilliseconds property. In theory, we could create a page with a Stopwatch instance and then simply display the stopwatch. elapsedMilliseconds.

However, there is one issue: Stopwatch does not provide any callbacks, so we don’t know when to re-render. The Timer class comes in handy here. It sets off a callback at the specified interval. As a result, we can trigger the re-render with a Timer, read stopwatch.elapsedMilliseconds, and rebuild the page.

This blog will go over the Stopwatch Timer in Flutter. We will look at how to implement a stopwatch timer demo programme and show how to create it in your flutter applications.

Flutter StopWatch Example

How to Implement Code in a Flutter without using package:

Inside the lib folder, create a new dart file called StopWatchTimerDemoPage.dart

First, we’ll make a const countdownDuration is equal to Duration as a ten minutes variable and a duration variable. We’ll also make a timer variable and a bool countDown equal to true.

static const countdownDuration = Duration(minutes: 10);
Duration duration = Duration();
Timer? timer;

bool countDown =true;

We will define the initState() method. The resetTime() function will be added to this method. We will define the code below.

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

We’ll define the resetTime() function:

We’ll make a resetTime() method. If countDown is true in this method, we will add duration equal to countdownDuration to setState((){}). Otherwise, duration equals Duration in setState((){}) .

void resetTime(){
  if (countDown){
    setState(() =>
      duration = countdownDuration);
  } else{
    setState(() =>
      duration = Duration());
  }
}

We’ll now write a startTimer() function. That dart will be imported: async;

import 'dart:async';

We’ll add a timer variable that’s the same as the Timer. The periodic add duration was one second, and the addTime() method was used. The code will be defined further below.

void startTimer(){
  timer = Timer.periodic(Duration(seconds: 1),(_) => addTime());
}

We will define the addTime() method as follows:

Inside the addTime method, we will add the final addSeconds equal to the count. If down is true,  countDown is true then -1 else 1. We will include setState(){}. Inside, the duration is equal to the final seconds. addSeconds plus inSeconds. If the second is less than zero, the timer is triggered. cancel() Otherwise, the duration equals the Duration (seconds: seconds).

void addTime(){
  final addSeconds = countDown ? -1 : 1;
  setState(() {
    final seconds = duration.inSeconds + addSeconds;
    if (seconds < 0){
      timer?.cancel();
    } else{
      duration = Duration(seconds: seconds);
    }
  });
}

We’ll now write a stopTimer() method. If the resetTime is equal to true, then the resetTime() method is called. We’ll include a timer. In the setState((){}) method, cancel.

void stopTimer({bool resetsTime = true}){
  if (resetsTime){
    resetTime();
  }
  setState(() => timer?.cancel());
}

Insert the body portion into the buildTime() and buildButtons() widgets. The code will be defined further below.

children: [
    buildTime(),
    SizedBox(height: 80,),
    buildButtons()
  ],

We will define the buildTime() widget as follows:

In this method, we will generate a final hour that is equal to two digits (duration.inHours). The sum of the final minutes is equal to twoDigits(duration.inMinutes.remainder(60)). Final seconds added equals twoDigits(duration.inSeconds.remainder(60)). Row will be returned (). Inside, we’ll add three buildTimeCard() methods, with arguments time and headers. The code will be explained further below.

Widget buildTime(){
  String twoDigits(int n) => n.toString().padLeft(2,'0');
  final hours =twoDigits(duration.inHours);
  final minutes =twoDigits(duration.inMinutes.remainder(60));
  final seconds =twoDigits(duration.inSeconds.remainder(60));
  return Row(
    mainAxisAlignment: MainAxisAlignment.center,
    children: [
      buildTimeCard(time: hours, header:'HOURS'),
      SizedBox(width: 8,),
     buildTimeCard(time: minutes, header:'MINUTES'),
     SizedBox(width: 8,),
     buildTimeCard(time: seconds, header:'SECONDS'),
  ]
  );
}

We will define the buildTimeCard() widget as follows:

We will pass two arguments to this widget: time and header. Column will be returned. Inside, add a container with decoration and its child, to which we will add text when the time comes. We’ll also include another text as a header.

Widget buildTimeCard({required String time, required String header}) =>
    Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          padding: EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(20)
          ),
          child: Text(
          time, style: TextStyle(fontWeight: FontWeight.bold,
          color: Colors.black,fontSize: 50),),
        ),
        SizedBox(height: 24,),
        Text(header,style: TextStyle(color: Colors.black45)),
      ],
    );

The buildButtons() widget will be defined as follows:

In this widget, we will add the final isRunning is equal to the timer is equal to null, then false, otherwise timer.

isActive. We will include a final isCompleted equal to duration. inSeconds equals zero. We’ll return isRunning || isCompleted before inserting a Row() widget. Insert the ButtonWidget class inside. We will define the code below. Two buttons were stopped, and the others were canceled. We will also include a start timer button.

Widget buildButtons(){
  final isRunning = timer == null? false: timer!.isActive;
  final isCompleted = duration.inSeconds == 0;
   return isRunning || isCompleted
       ? Row(
     mainAxisAlignment: MainAxisAlignment.center,
     children: [
       ButtonWidget(
           text:'STOP',
           onClicked: (){
             if (isRunning){
               stopTimer(resetsTime: false);
             }
           }),
       SizedBox(width: 12,),
       ButtonWidget(
           text: "CANCEL",
           onClicked: stopTimer
       ),
     ],
   )
       : ButtonWidget(
       text: "Start Timer!",
       color: Colors.black,
       backgroundColor: Colors.white,
       onClicked: (){
         startTimer();
       });
}

The class ButtonWidget will be defined as follows:

We will make an ElevatedButton in this class(). We’ll add the onPressed method and text inside.

class ButtonWidget extends StatelessWidget {
  final String text;
  final Color color;
  final Color backgroundColor;
  final VoidCallback onClicked;

  const ButtonWidget({Key? key, required this.text, required this.onClicked,
    this.color = Colors.white, this.backgroundColor = Colors.black}) : super(key: key);
  @override
  Widget build(BuildContext context) => ElevatedButton(
    style: ElevatedButton.styleFrom(
      primary: backgroundColor,
      padding: EdgeInsets.symmetric(horizontal: 32, vertical: 16)
    ),
      onPressed: onClicked,
      child: Text(text,style: TextStyle(fontSize: 20,color: color),)
  );

}

Output :


Stopwatch-Timer using Flutter package :

We will now implement the stopwatch Timer using the flutter stop_watch_timer package.

What is the purpose of a stopwatch?

A stopwatch is a watch with buttons that you press at the start and end of an event to determine how long it takes.

Implementation

Step 1: Your requirements should contain the following packages: 

stop_watch_timer: ^any

Step 2: Import the library

import 'package:stop_watch_timer/stop_watch_timer.dart';

Step 3: Run flutter packages from your app’s root directory.

Features of stopwatch:

1: CountUp

2: CountDown

Set the mode of stopWatch

1. CountUp :

This is the default setting. Set StopWatchMode.countUp to mode if you want to set it explicitly.

final stopWatchTimer = StopWatchTimer(
  mode: StopWatchMode.countUp
);

2. CountDown :

StopWatchMode can be configured. countDown mode and millisecond delay.

final stopWatchTimer = StopWatchTimer(
  mode: StopWatchMode.countDown,
  presetMillisecond: StopWatchTimer.getMilliSecFromMinute(1), // millisecond => minute.
);

Stopwatch operation

/// Start
_stopWatchTimer.onExecute.add(StopWatchExecute.start);

/// Stop
_stopWatchTimer.onExecute.add(StopWatchExecute.stop);

/// Reset
_stopWatchTimer.onExecute.add(StopWatchExecute.reset);

/// Lap time
_stopWatchTimer.onExecute.add(StopWatchExecute.lap);

Making use of callbacks

final _stopWatchTimer = StopWatchTimer(
  onChange: (value) {
    final displayTime = StopWatchTimer.getDisplayTime(value);
    print('displayTime $displayTime');
  },
  onChangeRawSecond: (value) => print('onChangeRawSecond Value :: $value'),
  onChangeRawMinute: (value) => print('onChangeRawMinute Value :: $value'),
);

Using the stream Show time formatted stopwatch. Using the “rawTime” and “getDisplayTime” functions.

_stopWatchTimer.rawTime.listen((value) => print('rawTime $value ${StopWatchTimer.getDisplayTime(value)}'));

Code implement

Stream builder code example.

StreamBuilder<int>(
  stream: _stopWatchTimer.rawTime,
  initialData: 0,
  builder: (context, snap) {
    final value = snap.data;
    final displayTime = StopWatchTimer.getDisplayTime(value);
    return Column(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.all(8),
          child: Text(
            displayTime,
            style: TextStyle(
              fontSize: 40,
              fontFamily: 'Helvetica',
              fontWeight: FontWeight.bold
            ),
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(8),
          child: Text(
            value.toString(),
            style: TextStyle(
                fontSize: 16,
                fontFamily: 'Helvetica',
                fontWeight: FontWeight.w400
            ),
          ),
        ),
      ],
    );
  },
),
),

Every minute, “minuteTime” will send a notification.

_stopWatchTimer.minuteTime.listen((value) => print('minuteTime $value'));

StreamBuilder<int>(
  stream: _stopWatchTimer.minuteTime,
  initialData: 0,
  builder: (context, snap) {
    final value = snap.data;
    print('Listen every minute. $value');
    return Column(
      children: <Widget>[
        Padding(
            padding: const EdgeInsets.all(8),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                const Padding(
                  padding: EdgeInsets.symmetric(horizontal: 4),
                  child: Text(
                    'minute',
                    style: TextStyle(
                      fontSize: 17,
                      fontFamily: 'Helvetica',
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 4),
                  child: Text(
                    value.toString(),
                    style: TextStyle(
                        fontSize: 30,
                        fontFamily: 'Helvetica',
                        fontWeight: FontWeight.bold
                    ),
                  ),
                ),
              ],
            )
        ),
      ],
    );
  },
),

The getDisplayTime func can be used to calculate the parsing time. It displays time in the manner of a traditional stopwatch timer.

Hours \Minute \Second \Millisecond

For example, “02:50:50.50” is 1 hour, 30 minutes, 50 seconds, and 20 milliseconds.

In addition, the display time and split character can be set.

Set the Preset Time

A preset time can be set. “00:01.23” is the time in this case.

This can be set when the timer is in the idle state.

/// Set Millisecond.
_stopWatchTimer.setPresetTime(mSec: 1234);

/// Set Hours. (ex. 1 hours)
_stopWatchTimer.setPresetHoursTime(1);

/// Set Minute. (ex. 30 minute)
_stopWatchTimer.setPresetMinuteTime(30);

///Set Second. (ex. 120 second)
_stopWatchTimer.setPresetSecondTime(120);

Output:

You can refer to this code by clicking on the defined text here.

Link to the GitHub code:

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

Conclusion

I explained the basic structure of the Stopwatch Timer in a flutter in the article; you can modify this code to suit your needs. This was my brief introduction to Effect On User Interaction, and it works with Flutter.

I hope this blog has given you enough information to try out the Stopwatch Timer in your flutter projects. We will demonstrate what the Introduction is. It demonstrates that when the user presses the start timer button, the countdown timing begins, and that the user can also press the stop and cancel timer buttons in your flutter applications. So please give it a shot.

Thank you for taking the time to read this 🙂 Have a Happy day……..

Jai Shree Ram, Drawing “Hanuman ji” Sketch with Python Turtle library

0
python drawing

Let’s Draw a Sketch image of Hanuman using Python turtle library.

Using Python Turtle library, we can give commands to generate a graphics like sketch image on the screen.

Drawing Sketch in python using turtle

Before running below code you need to install few library that are required to run below code successfully.

pip install PythonTurtle
pip install svgpathtools
pip install tqdm
pip install opencv-python
pip install tqdm

python turtle graphics code Source Code

import turtle as tu
import cv2
from svgpathtools import svg2paths2
from svg.path import parse_path
from tqdm import tqdm
class sketch_from_svg:

    def __init__(self,path,scale=30,x_offset=350,y_offset=350):

        self.path = path
        self.x_offset = x_offset
        self.y_offset = y_offset
        self.scale = scale

    def hex_to_rgb(self,string):
        strlen = len(string)
        if string.startswith('#'):
            if strlen == 7:
                r = string[1:3]
                g = string[3:5]
                b = string[5:7]
            elif strlen == 4:
                r = string[1:2]*2
                g = string[2:3]*2
                b = string[3:4]*2
        elif strlen == 3:
                r = string[0:1]*2
                g = string[1:2]*2
                b = string[2:3]*2
        else:
            r = string[0:2]
            g = string[2:4]
            b = string[4:6]
        
        return int(r,16)/255,int(g,16)/255, int(b,16)/255

    

    def load_svg(self):
        print('loading data')
        paths,attributes,svg_att = svg2paths2(self.path)
        h = svg_att["height"]
        w = svg_att['width']
        self.height = int(h[:h.find('.')])
        self.width = int(w[:w.find('.')])

        res = []
        for i in tqdm(attributes):
            path = parse_path(i['d'])
            co = i['fill']
            #print(co)
            col = self.hex_to_rgb(co)
            #print(col)
            n = len(list(path))+2       
            pts = [((int((p.real/self.width)*self.scale))-self.x_offset, (int((p.imag/self.height)*self.scale))-self.y_offset) for p in (path.point(i/n) for i in range(0,n+1))]
            res.append((pts,col))
            #res.append(pts)
        print('svg data loaded')
        return res

    def move_to(self,x, y):
        self.pen.up()
        self.pen.goto(x,y)
        self.pen.down()


    def draw(self,retain=True):
        coordinates = self.load_svg()
        self.pen = tu.Turtle()
        self.pen.speed(0)
        for path_col in coordinates:
            f = 1
            self.pen.color('black')
            #print(path_col)
            path = path_col[0]
            #print(path_col)
            col = path_col[1]
            #print(col)
            self.pen.color(col)
            self.pen.begin_fill()
            next = 0
            for coord in path:
                #for coord in path_col:
                x,y = coord
                y *= -1
                #print(x,y)
                if f:
                    self.move_to(x, y)
                    f=0
                else:
                    self.pen.goto(x,y)
            self.pen.end_fill()

        if retain == True:
            tu.done()
pen= sketch_from_svg('hanumanji.svg',scale=70)  
pen.draw()

python turtle example to draw sketch of svg image, I am just providing hanumanji png image download it from below and convert it to svg format using any online tools.

hanuman ji png image

unclickable button in flutter if the form is not valid

0
Moving Button On Hover Flutter

Hi Guy’s This is a fun article on How to create an unclickable button that keeps moving when you hover on it, until the form text Field is not valid.

moving button in flutter

main.dart

import 'package:flutter/material.dart';
import 'package:waste_button/onHover.dart';
import 'package:velocity_x/velocity_x.dart';
import 'package:fluttertoast/fluttertoast.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(
      title: 'Moving Button if Form InValid',
      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> {
  TextEditingController emailController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              controller: emailController,
              keyboardType: TextInputType.text,
              decoration: InputDecoration(
                  filled: true,
                  fillColor: Colors.white,
                  hintText: "Email",
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.all(Radius.circular(10.0)))),
            ).p4().px24(),
            TextField(
              controller: passwordController,
              keyboardType: TextInputType.text,
              decoration: InputDecoration(
                  filled: true,
                  fillColor: Colors.white,
                  hintText: "Password",
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.all(Radius.circular(10.0)))),
            ).p4().px24(),
            OnHover(builder: (isHovered){
              return
                ElevatedButton(onPressed: (){
                  print('Clicked');
                  Fluttertoast.showToast(
                      msg: "Form Submited Successfully",
                      toastLength: Toast.LENGTH_SHORT,
                      gravity: ToastGravity.BOTTOM,
                      timeInSecForIosWeb: 1,
                      backgroundColor: Colors.red,
                      textColor: Colors.white,
                      fontSize: 16.0
                  );
                }, child: Text("Sign-In"));
            }),
          ],
        ),
      ),
    );
  }
}

onHover.dart

import 'package:flutter/material.dart';

class OnHover extends StatefulWidget {

  final Widget Function(bool iaHovered) builder;

  const OnHover({Key? key, required this.builder}) : super(key: key);

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

class _OnHoverState extends State<OnHover> {

  bool isHovered = false;

  @override
  Widget build(BuildContext context) {
    final hovered = Matrix4.identity()..translate(130,0,130);
    final transform = isHovered ? hovered : Matrix4.identity();

    return MouseRegion(
      onEnter: (_)=> onEntered(true),
      onExit: (_)=> onEntered(false),
      child: AnimatedContainer(
        duration: Duration(milliseconds: 150),
        transform: transform,
        child: widget.builder(isHovered),
      ),
    );
  }

  void onEntered(bool isHovered){
    setState(() {

      this.isHovered = isHovered;
    });
  }
}

Flutter disable back button

0
flutter disable back button

There may be some pages where you want to disable back button in flutter app. In this Flutter article let’s checkout how to disable back button in flutter.

So, To disable back button in flutter, we can make use of Flutter WillPopScope Widget and within the widget we can use onWillPop property that will simply return false like shown below:

WillPopScope(
      onWillPop: () async {
        /* Do something here if you want */
        return false;
      },
      child: Scaffold(
          /* ... */
          ),
  );

The Complete Code to Disable Back Button press in flutter

// main.dart
import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        // Remove the debug banner
        debugShowCheckedModeBanner: false,
        title: 'Sample App',
        theme: ThemeData(
          primarySwatch: Colors.amber,
        ),
        home: const HomePage());
  }
}

// Home Page
class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: const Text('ProtoCodersPoint.com'),
      ),
      body: Center(
        child: ElevatedButton(
          child: const Text('Go to OtherPage'),
          onPressed: () {
            Navigator.of(context).push(
                MaterialPageRoute(builder: (context) => const OtherPage()));
          },
        ),
      ),
    );
  }
}

// Other Page
class OtherPage extends StatelessWidget {
  const OtherPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        // show the snackbar with some text
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
            content: Text('The System Back Button is Deactivated')));
        return false;
      },
      child: Scaffold(
        appBar: AppBar(
          automaticallyImplyLeading: false,
          centerTitle: true,
          title: const Text('Other Page'),
        ),
        body: const Padding(
          padding: EdgeInsets.all(30),
          child: Text(
            'Are you looking for a way to go back? Hmm...',
            style: TextStyle(fontSize: 24),
          ),
        ),
      ),
    );
  }
}

The above code will prevent our app getting closed when user press back button, so we have simple disabled back button in flutter by using WillPopScope widget.

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