Home Blog Page 23

Animated page transition in flutter

0
animated page transition in flutter
page transition in flutter

Page Transitions are used in Flutter to describe the movement of objects from one position to another.

When it comes to Flutter, these elements are similar to Widgets.

What are Page Transitions in flutter?

In general, A transition is nothing but moving an object from one place to another. In flutter, it is also the same but in terms of widgets like container, button, and also pages since everything in flutter is itself a widget.

To animate our tradition between two different pages, we will use the PageRouteBuilder method. You will definitely get an impression of all the different types of transitions that are possible, and you will also be able to customize them and create your own Custom Transition.

Page Transitions can improve the aesthetics of your flutter app user. This may improve the flow between pages or the speed with which pages load. They can also be used to give video backgrounds or other assets time to load before being displayed.

To animate our transition between pages or widgets, we will use a specific transition technique.


Different Transition Styles in Flutter

In Flutter, there are various types of transitions like:

1)  Slide Transition 

2)  Fade Transition

3)  Scale Transition

4)  Size Transition

5)  Rotation Transition

So, let’s start by understanding each transition individually and writing some code lines for them.


Implementation of Page Navigation with Animation in flutter app

We will need a PageRouteBuilder to create the transition because it gives us the necessary function Object() {Constructor} in return.

We are aware of how simple it is to switch between routes in Flutter. All we have to do is push and pop using Navigator.

For push: The below code will navigate the user from one page to another.

Navigator.push(
   context,
   MaterialPageRoute(builder: (context) => SecondRoute()),
 );

For pop: The below code will remove the top most page/widget/view from the Widget tree stack

Navigator.pop(context);

We discovered that page transitions can really beautify your UI when we started experimenting with animations. Use CupertinoPageRoute if you want a slide transition similar to iOS. There is nothing more to say.

Navigator.push(
   context, CupertinoPageRoute(builder: (context) =>NextScreen()))

However, for customized transitions There are numerous transition widgets offered by Flutter. Let’s examine their potential uses.

We are aware that the two arguments for Navigator.push are BuildContext context and Route<T> route. With some transition animation, we can design our own unique page route. Start off with a straightforward slide transition.


PageRouteBuilder

A class called PageRouteBuilder extends PageRoute and creates a route that delegates control to builder callbacks.

Class PageRouteBuilder<T> Zero safety a utility class for callback-based definition of one-time page routes. The pageBuilder function, which generates the main contents of the route, must be defined by callers. Define the transitionsBuilder function to add transitions.

PageRouteBuilder properties :

  • barrierColor
  • barrierDismissible
  • maintainState
  • opaque
  • pageBuilder
  • transitionDuration
  • transitionBuilder

PageBuilder, transitionDuration, and transitionsBuilder will be used.

PageBuilder:

The routes content is created using this property.

pageBuilder: (context, animation, anotherAnimation) {
  return ReturnPage();
},

transitionDuration:

It takes time for the pages to transition between each other.

transitionDuration: Duration(milliseconds: 1000),

transitionBuilder:

The transitions themselves are constructed using this property.

transitionsBuilder:
   (context, animation, anotherAnimation, child) {
 animation = CurvedAnimation(
     curve: curveList[index], parent: animation);
 return FadeTransition(
   opacity:animation,
   child: child,
 );
}

Slide Transition: 

We will make use of the SlideTransition widgets to implement SlideTransition. A fractional translational transition is produced.

SlideTranstion’s positional property cannot be null.
It is a slightly different transition from the others because it uses Animation Offset rather than Animation Double.Therefore, Animation <Offset> is needed for this transition. Offset essentially refers to the canvas’s coordinate system. It contains both the dx and dy.

Slide Transition widget :

SlideTransition(
   position: Tween(
           begin: Offset(1.0, 0.0),
           end: Offset(0.0, 0.0))
       .animate(animation),
   child: child,
);

Fade Transition:

A fade/opacity transition is produced.We can use this transition to make any widget or image fade.
The “opacity” property is necessary .The opacity property cannot be empty.

FadeTransition(
 opacity:animation,
 child: child,
);

Scale Transition:

The scale of the widget is animated during this transition. In this, the necessary property is “scale.”Other properties include child, filterQuality, and alignment.

By altering the child’s scale, this transition brings the route to life.

On the other hand, the widget’s scaling direction is specified by the alignment property.

It is Alignment.center by default.

ScaleTransition(
 scale: animation,
 child: child,
);

Size Transition:

A size transition is produced by this transition.

The arguments for axis, sizeFactor, and axisAlignment cannot be null. By default, the axis argument is set to Axis.vertical. The child is centered along the main axis during the transition when the axisAlignment’s default value of 0.0 is used.

This transition takes into account the size of the specific widget.

Align(
 child: SizeTransition(
   sizeFactor: animation,
   child: child,
   axisAlignment: 0.0,
 ),
);

Rotation Transition:

This transition assists in animating a widget’s rotation.

It needs the “turns” property in order to be animated.

RotationTransition(
 turns: animation,
 child: child,
);

Setting up a PageRouteBuilder

pageBuilder: (context, animation, anotherAnimation) {
  return ReturnPage();
},

Navigator.of(context).push(PageRouteBuilder (
page Builder: (context, animation, anotherAnimation) {
return ReturnPage();
},
transitionDuration:Duration (milliseconds: 1000),
transitionsBuilder:
     (context, animation, anotherAnimation, child) {
animation = CurvedAnimation (
       curve: Curves.bounceIn, parent: animation);
return Rotation Transition(
     turns: animation,
     child: child,
  );
  },
),
)

Source Code for references:

In my project, I have used every possible transition. Each transition has a separate file that I’ve created. I’ve connected every file. As you can also see from the gist.

You can prefer this app code , code for click here : 

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

Conclusion 

We have covered how to incorporate various transitions into our app in this blog.

I hope it will aid in your comprehension and provide you with a basic understanding of it.

Gratitude for reading

Have a Good day..!

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.