Showing posts with label Widget. Show all posts
Showing posts with label Widget. Show all posts

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




    Different between StatelessWidget and StatefulWidget in the flutter


    As we are beginner for Flutter and many of the developers are getting confused for StatelessWidget and StatefulWidget. Here we are going to clear you what is exact difference between StatelessWidget and StatefulWidget.


    Same like another language Like Swift, Kotlin Etc. you may heard about mutable and immutable property. Same things we can apply here for those widget.
    In the Swift we declare let keyword with static variable and var keyword with dynamic variable.
    So what is mutable and immutable ?
    • Mutable means changeable, you can change property of mutable variable or function at run time. In other world we can say it’s value is dynamic.
    • Immutable mean properly of the variable or function will not be change after set it once. In other world we can say it’s value is Static.
    For StatelessWidget - It’s static, This widget will not be change after run time.


    StatefulWidget - It’s dynamic, This widget will change any time where you want.
    So If any API will call and JSON data are coming and You want it to display on ListView then you must use with StatefulWidget. Any operation if you want to display on run time that will be done by StatefulWidget.
    StatelessWidget - Work with static data. If you render any static list that will not be change any time that you can go with this widget.



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