Flutter draw route polyline and calculate distance on Google Map.


MorUde Frrr - (Fly Or Not)



Many developer looking same things, how to draw polyline/route on map? So here you are on right place we going to draw route on Google Map.

So first of all, You have to create Flutter project and need to add below dependancy in pubspec.yaml file.

[google_maps_flutter]

We are going to use official Flutter google map plugin. You have to follow all the requirement septs to add google map plugin in the project  and also need to generated google map API KEY.

Well thats enough right now. We are going on coding funda. Let's open your project. Right now you have set it up Google Map API KEY for iOS and Android platform.

I don't want to write details because many tutorials you can find how to integrate Google Map in the Flutter app.

So, Let's start for route on the map.






Here we have declare  _initialCamera to display current visible area of the map.
Two LatLng for draw route line source to destination here,  variable name will be anything you want.




Added marker for source and destination LatLong.





In the build method we have integrated initial Google Map.










Here below is main code that will use to draw the route.

https://maps.googleapis.com/maps/api/directions/json?origin=Lat,Long&&destination=Lat,Long&key=XYZ

By calling above url, you will get steps  and also you will get the distance between source and destination.

Instead of write code here, You can check full code from my GitHub repo. Below is the link, Download and check the code The result will be.







Good Luck!!!


How many types of buttons and clickable widgets in the Flutter?





MorUde Frrr - (Fly Or Not)







Hello people, We can not imagine any language that has not click event because without click it's very hard to trigger any actions. So here in Flutter we are talking about some buttons and clickable widgets very quickly in the Flutter. Here we are not going to explain deeply because it's enough to understanding about new widgets. Deeply and clear explanation already you will be found on official document of Flutter. 



1) FlatButton

-> Simple button that has not much highlighted decoration, Mostly use on toolbar, dialog and etc. For more info to usage, check out official document.
-> FlatButton has two required property child and onPressed() Lets look at below example.

        FlatButton(
          child: Text('I am FlatButton'),
          onPressed: (){
            print('You tapped on FlatButton');
          },
        ),




Here we are using child as Text Widget but you can use as you want and suitable for Flutter. onPressed() is simple voidCallback that is call back with no argument and no return.

Below are more property of FlatButton widget.


    Key key,
    @required VoidCallback onPressed,
    ValueChanged<bool> onHighlightChanged,
    ButtonTextTheme textTheme,
    Color textColor,
    Color disabledTextColor,
    Color color,
    Color disabledColor,
    Color highlightColor,
    Color splashColor,
    Brightness colorBrightness,
    EdgeInsetsGeometry padding,
    ShapeBorder shape,
    Clip clipBehavior = Clip.none,
    MaterialTapTargetSize materialTapTargetSize,
    @required Widget child,

You can play with above properties. You can also find all the properties of any widget/method by short-cut Mac User - (Command+ClickOnWidget/Method)  for others may be use Ctrl instead of Command.





2) RaisedButton

-> It's material button same like flatButton but it has elevation that will increase when it pressed.
-> Do not used with Widgets that has already raise-content like dialog, card etc. Use with flat content like long list, wide range of widget


        RaisedButton(
          child: Text('I am RaisedButton'),
          onPressed: (){
            print('You tapped on RaisedButton');
          },
        ),





For know more property of RaisedButton you can see by above short-cut that I mentioned above.

If you want to display icon+text with FlatButton and RaisedButton you can do it by FlatButton.icon() and RaisedButton.icon()






3) FloatingActionButton

-> Simple circular icon with hover, mostly single per screen.
-> Display on screen for trigger positive action like, add, share or navigate to screen and etc.
-> Use child as Icon widget, not any rule you can also use whatever
-> Mostly use with Scaffold widget that has property name is floatingActionButton 
-> For more info to usage, check out official document.



        FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: (){
            print('You tapped on FloatingActionButton');
          },
        ),




-> If you want to change default behaviour of FloatingActionButton means icon+text simply use FloatingActionButton.extended() it has two require property label and icon here child will removed which help you to display icon with text by FloatingActionButton. Look at below example 





        FloatingActionButton.extended(
          icon: Icon(Icons.add),        
         label: Text('I am Extended'),
          onPressed: (){
print('You tapped on FloatingActionButton'); }, ),




For know more property of 
FloatingActionButton you can see by above short-cut that I mentioned above.






4) IconButton


-> Simple display touchable icon, Trigger action when clicked.
-> Mostly use with AppBar widget with actions property.




IconButton(
    icon: Icon(Icons.volume_up),
    tooltip: 'Increase volume by 10%',
    onPressed: () { print('Volume button clicked');},
);





About it's properties you can same like other buttons. 
Also you can find BackButton and CloseButton is type of IconButton you can find out more information by check-out links.
I'm thinking that's enough for button's and click. I know about DropdownButton and PopupMenuButton but I'll explain it later.



But apart of buttons there are some widgets that uses for trigger click event. For example If you have some text and you want this text should be worked as clickable text. You may have seen clickable text in so many applications or websites that has clickable text. For clickable text use InkWell widget and there is no any rules like InkWell widget only use in case of clickable text but you can make any widget as clickable by InkWell widget.

     Another Widget is also trigger clickable event, name is GestureDetector, It is very powerful widget there are so many clickable event like, singleTap, doubleTap, tapUp, tapDown and etc. Let's look.






5) InkWell

-> A rectangle area of the material that response on touch.-> Simply you can wrap it to any material widget so that will be clickable.
-> Below Ex. we made simple text work as link.



  InkWell(
   onTap: () {
     print('Clicked on URL by InkWell Widget');
   },
   child: Text("https://quickstartflutterdart.blogspot.in/",
       style: TextStyle(
         color: Colors.blue,
         fontSize: 13,
         decoration: TextDecoration.underline)),
    );


Just copy and pasted above code on your editor. You can see in console when click on url link.

-> Simple and short when any material widget that you want to make it as clickable at that time use InkWell widget that's it.

-> For more information you can check official document.






6) GestureDetector

-> It's work same like InkWell widget but it has more powerful click events.
-> It has many click/drag and other events.
-> Look at below Ex. We used same code as above just change widget InkWell to GestureDetector.



GestureDetector(
      onTap: () {
        print('Clicked on URL by GestureDetector Widget');
      },
      child: Text("https://quickstartflutterdart.blogspot.in/", 
        style: TextStyle(
        color: Colors.blue, 
        fontSize: 13,
        decoration: TextDecoration.underline)
      ),
    );


-> It works same. But instead of onTap() it has so many other event.



this.child,
this.onTapDown,
this.onTapUp,
this.onTap,
this.onTapCancel,
this.onDoubleTap,
this.onLongPress,
this.onLongPressUp,
this.onVerticalDragDown,
this.onVerticalDragStart,
this.onVerticalDragUpdate,
this.onVerticalDragEnd,
this.onVerticalDragCancel,
this.onHorizontalDragDown,
this.onHorizontalDragStart,
this.onHorizontalDragUpdate,
this.onHorizontalDragEnd,
this.onHorizontalDragCancel,
this.onForcePressStart,
this.onForcePressPeak,
this.onForcePressUpdate,
this.onForcePressEnd,
this.onPanDown,
this.onPanStart,
this.onPanUpdate,
this.onPanEnd,
this.onPanCancel,
this.onScaleStart,
this.onScaleUpdate,
this.onScaleEnd,
this.behavior,
this.excludeFromSemantics = false

You can check it by trick that I mentioned before. If you want more info about this widget simple check it out official document.


That's it! I think, this is enough for quick learning bout button and other clickable widget.

Thank's for reading/support.

Flutter what is Widget, RenderObject, Element, Context.


I wrote this article based on my understanding I'm not going to explain deeply because already very good article has been wrote on those topics. We want to learn quickly as our blog title said :D . and also I have added some very important links at the end of the article. You should also check it out for more understanding. 


We are starting from beginner level so when you started to learn flutter, you might be seen word(s) “Widget”, "Element", "BuildContext", "RenderObject" and Etc. So what is Widget? Let’s try to understand Widget quickly ;)

  • Widget:

=> In flutter everything is Widget means whatever you have seen on the screen that all are made up by Widget like (AppBar, Text, Buttons, Dropdown, List, Popup, Dialogs and Etc means everything). In other word you can also visualise Widget as visual component of the application.

=> Each Screen in the Flutter arrange Widgets by Widget Tree means child-parent widgets. Widget that wrapped by another Widget that known as parent widget and widget that get wrapping is known as child widget. 

=> There are mainly two types of the Widget, StatelessWidget and StatefullWidget for more information about it Please check my another post.

=> In the Flutter framework, Widget is an immutable description of part of a user interface. 

=> Widget just hold configuration information, Like Opacity widget only holds opacity value either 1 or 0. That’s why we create new widget each time while build method get call. It’s not much expensive.

































  • RenderObject: 


=> When you create any Widget, then widget itself has only configuration information mean If you create Opacity widget then main work of Opacity widget is to manage 'opacity' property that either 0 or 1. They don't care about it's child. Actually Child is created/Render some where else. That's why we called each time create widget is not more expensive.

=> So we can say Widget is only blue-print, Layout/Rendering has been done some where else.


  • Element:

=> Element is nothing but instance of the widget at particular location in Widget tree.

=> When widget created, It inflated into Element. And element get inserted it into the tree at particular location.

=> Widget is immutable but element is mutable property
Most of Elements has single child property like, Container, Opacity, Center etc and Some Elements has multiple children call children property. Like Column, Row, ListView and Etc.

=> Element are created by "createElement()" method

=> For more information about Element and it's life cycle you can check out official document of Element.



  • Context:

=> Context is nothing but that indicates location of the widget in widget tree.
=> Each widget in Widget tree has own context, and context is directly attached to state of object.  Attachment is permeant mean context of the widget will not be change in entire life time of the App.

=> Same like widget we can imaging context in Parent/child manner.
Take example If you have Widget tree like Container -> Column -> Text->Button->Image. Here Each Widget in widget tree has own context like Container has it's own context. Column has it's own context... same for others. And context is permanent for it's widget.

=> In above  example Container widget known as Parent widget in Widget tree and others are child widgets. So same We can imagine Context of Container widget also know as Parent context and others are child context.


That's it, If you want to learn more about all the above topics you can go with below links.

1) Nice article wrote by Didier Boelens  you can check out below link


=> https://www.didierboelens.com/2018/06/widget---state---context---inheritedwidget/


2) For element, renderObject very deeply and clear explained by Norbert, checkout link


=> https://medium.com/flutter-community/flutter-what-are-widgets-renderobjects-and-elements-630a57d05208





    How to create slide menu or drawer in flutter.



    Drawer in flutter, it's old and very easy to integrate. Because you may be found so many tutorials on this topic.

    So don't west much time for explanation or theory. But for iOS user might be found issue in swipe to navigation back page after click on menu item.

    Instead of use below code in onTap() Method of ListTile



    onTap: () {
      Navigator.pop(ctxt);
      Navigator.push(ctxt, new MaterialPageRoute(builder: (ctxt) => new FirstPage()));
    }

    Use pushReplacement in onTap().


    onTap: () {
      Navigator.pushReplacement(ctxt, new MaterialPageRoute(builder: (ctxt) => new FirstPage()));
    }
    For more information about pushReplacement.


    Please Click Here to download source code.





    How to convert String to Date and Date To String in Flutter.


    MorUde Frrr - (Fly Or Not)


    Many developer has question like how to convert String to Date or Date to String in Flutter? I’m gonna explain you both.

    First we need to add new package date_format in “pubspec.yaml” file. Below is link that will help you for more information.











    x


    After installing the “date_format” package you have to import package in you .dart file.


    import 'package:date_format/date_format.dart';

    1)Convert Date to String

    void convertStringFromDate() {
      final todayDate = DateTime.now();
      print(formatDate(todayDate, [yyyy, '-', mm, '-', dd, ' ', hh, ':', nn, ':', ss, ' ', am]));
    }
         
    Call above function by convertStringFromDate() that will print date that you given format. Also check your self by changing “yyyy to yy/ mm to MM or m/ dd to d” etc.
    2)Convert String to Date

    void convertDateFromString(String strDate){
      DateTime todayDate = DateTime.parse(strDate);
      print(todayDate);
      print(formatDate(todayDate, [yyyy, '/', mm, '/', dd, ' ', hh, ':', nn, ':', ss, ' ', am]));
    }
      

    Call above function by convertDateFromString('2018-09-27 13:27:00') and output will be flutter: 2018/09/27 01:09:00 PM


    Create Login form and validation in flutter




    Before we start simple login form, let me tell you some basic scenario what types of main widgets and GlobalKey  we are using here 

    • Form widget :: Actually form widget is container controller or we can said it’s group for form fields. When we use form widget also we have to set GlobalKey for uniquely identify current form and you can access other property of the form.

    • TextFormField Widget  :: Form without input field? We can’t visualize. We are creating form because end-user can input some data so here we are using TextFormField for get input from the end-use. It’s material design text input and it has validate method that will help us for validate this text field.

    • RaisedButton Widget :: It’s simple material design button and has click method that we will help us to execute another action.

    In our demo we will use GlobalKey for access Form and Scaffold Widgets and its property. For more information click on GlobalKey I already attached link on that.





    Example:


    import 'package:flutter/material.dart';
    
    void main() => runApp(new FormValidation());
    
    class FormValidation extends StatelessWidget {
     @override
       Widget build(BuildContext context) {
         return new MaterialApp(
           title: "Form validation",
           home: LoginScreen(),
         );
       }
    }
    
    class LoginScreen extends StatefulWidget {
    @override
     State<StatefulWidget> createState() {
       // TODO: implement createState
       return LoginScreenState();
     }
    }
    
    class LoginScreenState extends State <LoginScreen> {
     final _formKey = GlobalKey<FormState>();
     final _scaffoldKey = GlobalKey<ScaffoldState>();
    
     String _email;
     String _password;
    
     @override
       Widget build(BuildContext context) {
         // TODO: implement build
         return new Scaffold(
           key: _scaffoldKey,
           appBar: new AppBar(
             title: new Text("Login")
           ),
           body: new Container(
             padding: const EdgeInsets.all(20.0),
             child: formSetup(context)
           ),
         );
       }
    
       Widget formSetup(BuildContext context){
         return new Form(
               key: _formKey,
               child: new Column(
                 children: <Widget>[
                   new TextFormField(
                     decoration: InputDecoration(
                       hintText: "aa@bb.com",
                       labelText: "Email"                   
                     ),
                     keyboardType: TextInputType.emailAddress,
                     validator: (val){
                         if (val.length == 0)
                           return "Please enter email";                     
                         else if (!val.contains("@"))
                           return "Please enter valid email";                     
                         else
                           return null; 
                       },
                       onSaved: (val)=>_email=val,
                   ),
                   new TextFormField(
                     decoration: InputDecoration(
                       hintText: "Password",
                       labelText: "Password"                   
                     ),      
                     obscureText: true,          
                     validator: (val){
                         if (val.length == 0)
                           return "Please enter password";                     
                         else if (val.length <= 5)
                           return "Your password should be more then 6 char long";                     
                         else
                           return null; 
                       },
                       onSaved: (val)=>_password=val,
                   ),
                   new Padding(
                     padding: const EdgeInsets.only(top: 20.0),
                   ),
                   new RaisedButton(
                     child: new Text("Submit"),
                     onPressed: (){
                       if (_formKey.currentState.validate()) {
                         _formKey.currentState.save();
                         _scaffoldKey.currentState.showSnackBar(new SnackBar(
                           content: new Text("Your email: $_email and Password: $_password"),
                         ));
                       }
                     },
                     color: Colors.blue,
                     highlightColor: Colors.blueGrey,                 
                   )
                 ],
               ),
             );
       }
    }





    Here in that above demo we are using StatefulWidget and below GlobalKeys


    final _formKey = GlobalKey<FormState>();
    final _scaffoldKey = GlobalKey<ScaffoldState>();

    For access its state and property.

    We have two TextFormFields for input Email and Password. And it has  InputDecoration for decorate text input. The main method is validator method of Text field that will help you for validate form.

    At the last RaisedButton, 


    new RaisedButton(
         child: new Text("Submit"),
             onPressed: (){
                  if (_formKey.currentState.validate()) {
                      _formKey.currentState.save();
                      _scaffoldKey.currentState.showSnackBar(new SnackBar(
                           content: new Text("Your email: $_email and Password: $_password"),
                    ));
                   }
               },
          color: Colors.blue,
          highlightColor: Colors.blueGrey,                 
    )


    It has one method onPressed in that method, we are checking form validation by

    if (_formKey.currentState.validate()) …..

    We can access form current state by using formKey. validation() method return true then Just display toast(showSnackBar). If return false then display string error message that already putted in validation() method of TextForm Field

    That’s It!!


    Hope you guys this is enough for your understanding. If you have any query or question then comment it.




    Repeats value of number of time in List or Array in Flutter?



    As we know in many programming languages like swift and etc. if you want to take array or list that has same value in all the index then we can do by one line of code. Repeat same value for specific time.

    Ex. (In Swift language)
    If In the Array I want to repeat 0 for 5 times then I can do by one line of code like below.
    let fiveZeros = Array(repeating: "0", count: 5)
    print(fiveZeros)
    // Prints "["0", "0", "0", "0", "0"]"

    So I'm looking same for flutter. is there any specific built-in function that will help us to achieve same features?

    Yes in the Flutter you can use "filled factory of List" That will help us to achieve same features.

    Ex.

    final fiveZeros = List.filled(5, 0);print(fiveZeros);  //-> [0, 0, 0, 0, 0]


    If you have any query or question then please give your feedback as comment.