Home Blog Page 5

Flutter AppBar Example | Designs and Actions Dropdown Menu in 2023

0
Flutter AppBar | Designs and Actions Dropdown Menu

Learn how to use the Flutter appbar. You can organize the basic navigation buttons in your app and give it a better structure with Flutter AppBar.

Located at the top of the screen, the app bar is a horizontal bar. This is a key element of the Scaffold widget. The quick action buttons, screen title, and toolbar icons are all included in the app bar.

scaffold() widget is required to add the app bar to your app.

Scaffold(
   appBar: AppBar( //appbar widget on Scaffold
          title:Text("AppBar"), //title aof appbar
          backgroundColor: Colors.redAccent, //background color of appbar
    ),
)

Constructor for the appBar() widget.

AppBar(
   {Key? key,
   Widget? leading,
   bool automaticallyImplyLeading: true,
   Widget? title,
   List? actions,
   Widget? flexibleSpace,
   PreferredSizeWidget? bottom,
   double? elevation,
   Color? shadowColor,
   ShapeBorder? shape,
   Color? backgroundColor,
   Color? foregroundColor,
   Brightness? brightness,
   IconThemeData? iconTheme,
   IconThemeData? actionsIconTheme,
   TextTheme? textTheme,
   bool primary: true,
   bool? centerTitle,
   bool excludeHeaderSemantics: false,
   double? titleSpacing,
   double toolbarOpacity: 1.0,
   double bottomOpacity: 1.0,
   double? toolbarHeight,
   double? leadingWidth,
   bool? backwardsCompatibility,
   TextStyle? toolbarTextStyle,
   TextStyle? titleTextStyle,
   SystemUiOverlayStyle? systemOverlayStyle}
)

Following is a description of this constructor’s characteristics:

People, who read this article also read: Flutter Liquid Swipe Animation

1. automaticallyImplyLeading – bool

A menu icon will be placed at the top of the app bar automatically if you’ve added a drawer to the same scaffold where you’ve placed the Flutter appBar. Similar to this, the back icon will always be visible at the top whenever there is a history of backward routing. Using the automaticallyImplyLeading property, you can regulate how flutter appBar behaves. It has a value of true by default. If you don’t want menu or back icons to be automatically placed at the top, set it to false. 

AppBar(
  automaticallyImplyLeading: false,
)

2. Flutter Appbar actions – List of Widget

This flutter AppBar class parameter must be supplied with a list of widgets. In the app bar’s right side, the widgets will be visible. In most cases, this property has quick action buttons. 

AppBar(
  actions: [
    IconButton(
      icon: Icon(Icons.camera), 
      onPressed: (){
        //code to execute when this button is pressed
      }
    ),

    IconButton(
      icon: Icon(Icons.search), 
      onPressed: (){
        //code to execute when this button is pressed
      }
    ),

    //more widgets to place here
  ],
)
Flutter appbar- Title of App
Title of App

3. bottom – PreferredSizeWidget

You must supply this property with a widget whose height is constant. This property supports CupertinoTabBar, ObstructingPreferredSizeWidget, PreferredSize, and TabBar implementations.

DefaultTabController(
  length: 2, //numbers of tab
  child:Scaffold(
    appBar: AppBar( //appbar widget on Scaffold
      bottom: TabBar(
        tabs: [
            Tab(icon: Icon(Icons.home)),
            Tab(icon: Icon(Icons.send))
            //more tabs here
        ],
      ),
    ), 
  )   
)
Bottom
Bottom

4. Flutter Appbar elevation – double

You must pass a double value that represents the height of the app bar’s elevation in order to use this property to raise the app bar using a shadow.

AppBar(
  elevation: 30.0,
)
Elevation
Elevation

People, who read this article also read: Flutter SDK Installation on Windows, macOS, Linux

5. title – Widget

The leading widget from the left side of the app bar is displayed before this widget. Typically, it is utilized to display the app’s active screen title. You can pass it any widget, but typically the Text() widget is passed to display a text title on the app bar. 

AppBar(
  title:Text("Title of App"),
)
Title
Title

6. backgroundColor – Color

The background color of the flutter appbar can be changed using this property.

AppBar(
  backgroundColor: Colors.redAccent,
)
BackgroundColor
BackgroundColor

7. leading – widget

The widget must be passed into this parameter in order to be displayed on the flutter appbar’s start-left side. The menu icon will automatically show up if a drawer is included in the same scaffold as the app bar. In the event that your app has a back routing history, the back button will appear in the same manner. 

AppBar( //appbar widget on Scaffold
  leading: IconButton( //menu icon button at start left of appbar
    onPressed: (){
         //code to execute when this button is pressed
    },
    icon: Icon(Icons.menu),
  ),
),
Leading Widget
Leading Widget

8. brightness – Brightness

This property is used to configure the app bar’s brightness scheme. Assuming you have chosen a dark background, you will need to adjust the brightness so that the content is displayed in a light color or vice versa. 

AppBar(
  brightness: Brightness.dark,
)

Example Code

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return DefaultTabController( //controller for TabBar
      length: 2, //lenght of tabs in TabBar
      child: MaterialApp(
         home: HomePage(),
      )
    );
  }
}

class HomePage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blue[100],
      appBar: AppBar(
          title:Text("Title of App"), //title of app
          backgroundColor: Colors.redAccent, //background color of app bar
          brightness: Brightness.dark, //redAccent is darker color so set brightness to dark
          elevation: 5.0, //elevation value of appbar
           bottom: TabBar( //tabbar at bottom of appbar
            onTap: (index){
              print("selected tab is $index");
            },
            tabs: [
                Tab(icon: Icon(Icons.home)),
                Tab(icon: Icon(Icons.send))
                //more tabs here
            ],
          ),
          actions: [ //actions widget in appbar
            IconButton(
              icon: Icon(Icons.camera), 
              onPressed: (){
                //code to execute when this button is pressed
              }
            ),

            IconButton(
              icon: Icon(Icons.search), 
              onPressed: (){
                //code to execute when this button is pressed
              }
            ),
            //more widgets to place here
          ], 
        ),

        drawer: Drawer(), //drawer on scaffold, it will create menu icon on appbar
 
        body: Center( //content body on scaffold
           child: Text("AppBar example")
        )
     );
  }
}

The output of example code

Flutter Scaffold Example | Uses, Properties and Importance in 2023

0
Flutter Scaffold

Learn more about the Flutter Scaffold widget, including its uses, characteristics, and value.

The Flutter Scaffold widget serves as the screen’s foundation for a single page. The fundamental functional layout structure of an app is implemented using it. The Scaffold widget makes it simple to add useful widgets to the app, including AppBar, FloatingActionButton, ButtonNavigationBar, Drawer, and many more. 

People, who read this article also read: Flutter SDK Installation on Windows, macOS, Linux

Using Flutter Scaffold, you can quickly build an app and implement fundamental components with very little code. It also lets you add all the material components that give your app its look and feel. 

Scaffold() widget’s constructors include:

Scaffold({
  Key key, 
  PreferredSizeWidget appBar, 
  Widget body, 
  Widget floatingActionButton, 
  FloatingActionButtonLocation floatingActionButtonLocation, 
  FloatingActionButtonAnimator floatingActionButtonAnimator, 
  List persistentFooterButtons, 
  Widget drawer, 
  Widget endDrawer, 
  Widget bottomNavigationBar, 
  Widget bottomSheet, 
  Color backgroundColor, 
  bool resizeToAvoidBottomPadding, 
  bool resizeToAvoidBottomInset, 
  bool primary: true, 
  DragStartBehavior drawerDragStartBehavior: 
  DragStartBehavior.start, 
  bool extendBody: false, 
  bool extendBodyBehindAppBar: false, 
  Color drawerScrimColor, 
  double drawerEdgeDragWidth, 
  bool drawerEnableOpenDragGesture: true, 
  bool endDrawerEnableOpenDragGesture: true
})

The following is a description of the constructors’ properties:

1. backgroundColor – Color

The background color of the Flutter Scaffold screen can be altered using this property.

Scaffold(
    backgroundColor: Colors.blue, //set background color of scaffold to blue
)
Flutter Scaffold- AppBar
AppBar

2. drawer – Widget

It is a navigation panel where various menu items can be placed for navigation. The menu icon will show up on appBar once you add a drawer to Flutter Scaffold.

Scaffold(
  drawer: Drawer( //drawer navigation on scaffold
    child: SafeArea(
     child:Column( //column widget
      children: [
          ListTile(
            leading: Icon(Icons.home),
            title: Text("Home Page"),
            subtitle: Text("Subtitle menu 1"),
          ),
          ListTile(
            leading: Icon(Icons.search),
            title: Text("Search Page"),
            subtitle: Text("Subtitle menu 1"),
          ),

          //put more menu items here
      ],
    ),
   ),
  ),
)
Drawer Widget
Drawer Widget
Drawer Widget
Drawer Widget

3. body – Widget

The primary content asset on Flutter Scaffold is this. It will appear on the screen after you pass the widget.

Scaffold(
  body: Center( //content body on scaffold
       child: Text("Scaffold Widget")
  )
)
Body Widget
Body Widget

4. floatingActionButton – Widget

It is a quick-acting floating button. 

Scaffold(
    floatingActionButton:FloatingActionButton( //Floating action button on Scaffold
        onPressed: (){
            //code to execute on button press
        },
        child: Icon(Icons.send), //icon inside button
    )
)
Floating Action Button
Floating Action Button

5. floatingActionButtonLocation – FloatingActionButtonLocation

This property is used to specify where the floating action button will appear on the screen.

Scaffold(
  floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
)
Floating Action Button Location
Floating Action Button Location

People, who read this article also read: Flutter Liquid Swipe Animation

6. bottomNavigationBar – Widget

The appBar component, which is visible at the bottom of the screen, is comparable to this one. You can specify a widget for the BottomAppBar() or BottomNavigationBar() properties.

Scaffold(
  bottomNavigationBar: BottomNavigationBar( //bottom navigation bar on scaffold
    items: [ //items inside navigation bar
        BottomNavigationBarItem(
          icon: Icon(Icons.add),
          label: "Button 1",
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.search),
          label: "Button 2",
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.camera),
          label: "Button 3",
        ),

        //put more items here
    ],
  ),
)
Bottom Navigation Bar
Bottom Navigation Bar

Additionally, you can use BottomAppBar() to set the notched shape on the bottomNavigationBar.

Scaffold(
  floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
  bottomNavigationBar: BottomAppBar( //bottom navigation bar on scaffold
    shape: CircularNotchedRectangle(), //shape of notch
    notchMargin: 10, //notche margin between floating button and bottom appbar
    child: Row( //children inside bottom appbar
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        IconButton(icon: Icon(Icons.menu), onPressed: () {},),
        IconButton(icon: Icon(Icons.search), onPressed: () {},),
      ],
    ),
  ),
)
Bottom App Bar
Bottom App Bar

7. appBar – PreferredSizeWidget

It appears as a horizontal bar at the top of the screen. One of the key elements of your app is the app bar; without it, your app might appear incomplete. The appBar widget’s own attributes include elevation, title, actions, and others. 

Scaffold(
  appBar: AppBar( 
      title:Text("AppBar"), //title aof appbar
      backgroundColor: Colors.redAccent, //background color of appbar
  ),
)
AppBar
AppBar

A Flutter Scaffold Widget example 

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
       home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
     return Scaffold(
        appBar: AppBar( //appbar widget on Scaffold
          title:Text("AppBar")
        ),
        floatingActionButton:FloatingActionButton( //Floating action button on Scaffold
          onPressed: (){},
          child: Icon(Icons.send),
        ),

        drawer: Drawer(), //drawer on scaffold, open with left menu icon
        endDrawer: Drawer(), //end drawer on scaffold, open with right menu icon

        bottomNavigationBar: BottomNavigationBar( //bottom navigation bar on scaffold
         items: [
             BottomNavigationBarItem(
               icon: Icon(Icons.add),
               label: "Button 1",
             ),
             BottomNavigationBarItem(
               icon: Icon(Icons.search),
               label: "Button 2",
             ),
             BottomNavigationBarItem(
               icon: Icon(Icons.camera),
               label: "Button 3",
             ),
        ],),

        body: Center( //content body on scaffold
           child: Text("Scaffold Widget")
        )
     );
  }
}import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
       home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
     return Scaffold(
        appBar: AppBar( //appbar widget on Scaffold
          title:Text("AppBar")
        ),
        floatingActionButton:FloatingActionButton( //Floating action button on Scaffold
          onPressed: (){},
          child: Icon(Icons.send),
        ),

        drawer: Drawer(), //drawer on scaffold, open with left menu icon
        endDrawer: Drawer(), //end drawer on scaffold, open with right menu icon

        bottomNavigationBar: BottomNavigationBar( //bottom navigation bar on scaffold
         items: [
             BottomNavigationBarItem(
               icon: Icon(Icons.add),
               label: "Button 1",
             ),
             BottomNavigationBarItem(
               icon: Icon(Icons.search),
               label: "Button 2",
             ),
             BottomNavigationBarItem(
               icon: Icon(Icons.camera),
               label: "Button 3",
             ),
        ],),

        body: Center( //content body on scaffold
           child: Text("Scaffold Widget")
        )
     );
  }
}

Output:

Refer to this video for any further queries

Gesturedetector Flutter Example | Flutter Gestures in 2023

0
Gesturedetector Flutter Example | Flutter Gestures

Gesturedetector flutter example are movements and actions performed physically on an app’s screen with the intention of commanding or controlling the app. The capability to communicate with users is crucial. The following are a few gesture examples:

  • Screen lock sliding.
  • Tap the screen of a mobile device.
  • Holding on to the button with your finger.

Introduction

A built-in mechanism for detecting gestures is not present in some widgets, such as the Container and Card widgets. These widgets are encased in the GestureDetector flutter example widget, which is solely used for gesture detection and does not produce any visual effects like a ripple.

The GestureDetector flutter widget functions by identifying gestures for which callbacks have been defined and reacting to the event. The callback receives a null value if the gesture is to be disabled.

The common gestures detected by the GestureDetector widget are listed below, along with the corresponding events and potential applications (all illustrations are credited to Luke Wroblewski’s Touch Gesture Reference Guide):

Scale

Gesturedetector flutter example- Scale
Scale
  1. onScaleUpdate — When the user is not in contact with the screen anymore, onScaleEnd is triggered. nd/or scale
  2. onScaleEnd — triggered once the user has lost contact with the screen Possible application for the scale gesture
  3. onScaleStart — triggered when the screen has made contact with the user, establishing a focal point and an initial scale of 1.0.

Scale gestures have the following uses:

  • Rotation
  • Vertical Drag
  • Zoom in/zoom out

Double Tap

Twice in a short period of time, the user tapped the screen in the same place.

Gesturedetector flutter example- Double Tap
Double Tap
  1. onDoubleTapDown — triggered when a user touches the screen, possibly with a double tap
  2. onDoubleTapCancel — triggered if the event that fired onDoubleTapDown is not a double tap.
  3. onDoubleTap — triggered whenever a user quickly and repeatedly taps the same spot on the screen twice.

People, who read this article also read: Flutter Liquid Swipe Animation

The following examples illustrate possible uses for the double-tap gesture:

  • Long press
  • Like/dislike
  • Resize an image
  • Screen on/off

Long Press

For a considerable amount of time, the user maintained contact with the screen at the same point.

Gesturedetector flutter example- Long Press
Long Press
  1. onLongPressCancel — When the event that fired onLongPressDown is not a long press, the trigger occurs.
  2. onLongPressStart — triggered when the beginning of a long press is discovered
  3. onLongPress — triggered after the detection of a long press
  4. onLongPressEnd — triggered when the conclusion of a long press is discovered
  5. onLongPressDown — triggered when a user touches the screen; this contact may be prolonged
  6. onLongPressMoveUpdate — triggered when a long press has been detected and the user has moved their finger.
  7. onLongPressUp — triggered when the end of a long press is discovered; contact has been released following the long press

The following are some potential uses for the long-press gesture:

  • The user pinched or spread the screen.
  • Move an icon
  • Scale
  • Show more options

Tap

A fingertip of the user made brief contact with the screen.

Gesturedetector flutter example- Tap
Tap
  1. onTapUp — triggered when the user removes their eyes from the screen
  2. onTapDown — triggered when the user makes physical contact with the screen, which could be a tap.
  3. onTapCancel — triggered if the event that fired on TapDown is not a tap
  4. onTap — triggered when a user only fleetingly touches the screen

The following are some potential uses for the tap gesture:

  • Cancel
  • Double-tap
  • Select
  • Submit

Vertical Drag

The user touched the screen and steadily moved their fingertip up and down.

Vertical Drag
Vertical Drag
  1. onVerticalDragStart — the user begins to move vertically after making contact with the screen, which triggers the action.
  2. onVerticalDragDown — it may move vertically when a user touches the screen and is triggered by that touch.
  3. onVerticalDragEnd — It starts when the conclusion of a vertical drag is found.
  4. onVerticalDragCancel — triggered if the event that caused VerticalDragDown to fire is not a vertical drag.
  5. onVerticalDragUpdate — triggered when a contact that has been moving vertically stops and starts again.

The vertical drag gesture may be used for the following purposes:

  • Scroll

Horizontal Drag

A steady horizontal movement was made by the user’s fingertip after making contact with the screen.

Horizontal Drag
Horizontal Drag
  1. onHorizontalDragStart — triggered as soon as the user starts moving horizontally after making contact with the screen.
  2. onHorizontalDragEnd — when a horizontal drag has ended and the end has been detected.
  3. onHorizontalDragCancel — occurs when an event that fired on HorizontalDragDown is not a horizontal drag.
  4. onHorizontalDragDown — when the user touches the screen, a movement may begin that could be horizontal.
  5. onHorizontalDragUpdate — triggered when a horizontally moving contact moves in a horizontal direction once more.

The following are some potential uses for the horizontal drag gesture:

  • Go to a different view by navigating.
  • Delete
  • Archive

This is not an exhaustive list of the gestures that were discovered. For a full list, refer to the official documentation.

Let’s give it a shot!

Starting Up

To use the GestureDetector flutter example widget:

  • Give a callback for the gesture you want to recognize.
  • This app needs to be updated.
  • Wrap the GestureDetector widget around the desired widget.

To demonstrate how the tap, double-tap, long press, and scale gestures work, we will create a straightforward demo app.

Make a fresh Flutter application

Clear the default code from your main.dart file before creating a new Flutter application.

UI update

These four files will be made by us. The folder hierarchy is displayed here.

main.dart

import 'package:flutter/material.dart';
import 'presentation/my_app_widget.dart';
void main() {
  runApp(const MyApp());
}

My_app_widget.dart

import 'package:flutter/material.dart';
import 'home_page.dart';
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Gesture Detector Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home:  const HomePage(),
    );
  }
}

Home_page.dart

import 'package:flutter/material.dart';
import 'widgets/widgets.dart';
class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final height = MediaQuery.of(context).size.height;
    final width = MediaQuery.of(context).size.width;
    return Scaffold(
      body: Padding(
        padding: EdgeInsets.symmetric(
            horizontal: width * 0.1, vertical: height * 0.2),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children:  const [
            MyCardWidget(),
            MyFavoriteIconWidget()
          ],
        ),
      ),
    );
  }
}

My_card_widget.dart

import 'dart:math';
import 'package:flutter/material.dart';
class MyCardWidget extends StatefulWidget {
  const MyCardWidget({
    Key? key,
  }) : super(key: key);
  @override
  State<MyCardWidget> createState() => _MyCardWidgetState();
}
class _MyCardWidgetState extends State<MyCardWidget> {
  @override
  Widget build(BuildContext context) {
    return const Card(
      child: SizedBox(
        height: 300,
        width: 300,
      ),
      color: Colors.yellow,
    );
  }
}

My_favorite_icon_widget.dart

import 'package:flutter/material.dart';
class MyFavoriteIconWidget extends StatefulWidget {
  const MyFavoriteIconWidget({
    Key? key,
  }) : super(key: key);

  @override
  State<MyFavoriteIconWidget> createState() => _MyFavoriteIconWidgetState();
}

class _MyFavoriteIconWidgetState extends State<MyFavoriteIconWidget> {
  @override
  Widget build(BuildContext context) {
    return const Icon(
     Icons.favorite_border,
      size: 40,
    );
  }
}

Your completed app should resemble this:

Output
Output

Let’s handle some gestures now that our user interface is prepared.

Managing the Tap Gesture

Now, in the my_favorite_icon_widget.dart file:

  1. Make the StatefulWidget’s selected flag property available.
  2. isSelected = false in the bool;
  3. Wrap the GestureDetector widget around the Icon widget.
  4. Don’t leave the onTap property’s callback as null.
  5. Depending on the value of the flag property value, alter the icon and icon color.
class _MyFavoriteIconWidgetState extends State<MyFavoriteIconWidget> {
  bool isSelected = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: (){
          setState(() {
            isSelected = !isSelected;
          });
        },
        child:  Icon(
          isSelected ? Icons.favorite: Icons.favorite_border,
          size: 40,
          color: isSelected? Colors.red: Colors.black ,
        ));
  }
}

Managing the Double-Tap Gesture

In the my_card_widget.dart file:

  1. Include a color property.
  2. GestureDetector should be wrapped around the Card widget.
  3. Give the onDoubleTap property a non-null callback.
  4. Based on the value of the color property, alter the color of the card.
class _MyCardWidgetState extends State<MyCardWidget> {
  Color bgColor = Colors.yellow;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onDoubleTap: (){
        setState(() {
          bgColor = Colors.primaries[Random().nextInt(Colors.primaries.length)];
        });
      },
      child:   Card(
        child: const SizedBox(
          height: 300,
          width: 300,
        ),
        color: bgColor,
      ),
    );
  }
}

Managing the Long Press Gesture

In the my_card_widget.dart file:

  1. Give the onLongPress property a non-null callback.
  2. Depending on the makeCircular property, alter the card’s shape.
  3. Add a makeCircular flag property
class _MyCardWidgetState extends State<MyCardWidget> {
  Color bgColor = Colors.yellow;
  bool makeCircular = false;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onLongPress: (){
        setState(() {
          makeCircular = !makeCircular;
        });
      },
      child:   Card(
        shape: makeCircular? const CircleBorder(): const RoundedRectangleBorder(),
        child: const SizedBox(
          height: 300,
          width: 300,
        ),
        color: bgColor,
      ),
    );
  }
}

Managing the Scale Gesture

In the my_card_widget.dart file:

  1. Insert the _scaleFactor property.
  2. Include the _baseFactor property.
  3. Establish an initial scale by providing a non-null callback to the onScaleStart property.
  4. Establish a new scale by providing a non-null callback to the onScaleUpdate property.
  5. Return to the initial scale by providing a non-null callback to the onScaleEnd property.
  6. Transorm.scale widget should encircle the Card widget.
  7. Depending on the _scaleFactor’s value, modify the scale property.
class _MyCardWidgetState extends State<MyCardWidget> {
  Color bgColor = Colors.yellow;
  bool makeCircular = false;
  double _scaleFactor = 0.5;
  double _baseScaleFactor = 0.5;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onScaleStart: (details){
        _baseScaleFactor = _scaleFactor;
      },
      onScaleUpdate: (details){
        setState(() {
          _scaleFactor = _baseScaleFactor * details.scale;
        });
      },
      onScaleEnd: (details){
        // return to initial scale
        _scaleFactor = _baseScaleFactor;
      },
      child:   Transform.scale(
        scale: _scaleFactor,
        child: Card(
          shape: makeCircular? const CircleBorder(): const RoundedRectangleBorde(),
          child: const SizedBox(
            height: 300,
            width: 300,
          ),
        color: bgColor,
      ),
    );
  }
}

The following video demonstrates the gestures used:

Gesture Clarification

What transpires then when two delayed, fleeting touch events take place when we provide the onGestureDown event callback for tapping and double-taping?

Take this as an example:

Illustration
Illustration

Flutter determines which gesture the user intended when two or more gesture events with non-null callbacks are recognized by having each recognizer enter the gesture arena. The winning event in the gesture arena “battles” with the closing events, which are canceled. 

People, who read this article also read: Flutter SDK Installation on Windows, macOS, Linux

The following factors are considered by the gesture arena:

  • The amount of time a user touches a screen
  • How many pixels were moved in each direction
  • What movement is present in the room?
  • A move that signals success

The battle states are as follows:

  • Maybe — possibly the gesture
  • Hold — if it changes in a specific way; in our case, one tap happened, and if the second tap happens within the anticipated time, it might be a double tap. might be the gesture if it develops in a specific way.
  • Yes — announcement of victory
  • Cancel — removed from combat

Consider the following scenario, for instance:

  1. The triggers for onTapDown and onDoubleTapDown
  2. Both gestures are in competition with one another.
  3. The onTap callback is carried out after the tap gesture succeeds.
  4. OnDoubleTapCancel is triggered when the double-tap gesture fails and is canceled.

In this instance, the tap gesture prevailed because:

  1. There was a delay in time between the two taps.
  2. With a tap and a “yes,” victory was declared.
  3. After the double-tap was canceled and there was no other competitor, the tap gesture was the only one left.

Conclusion

We have examined the GestureDetector widget and discovered how it functions. We have mastered its use to incorporate interactivity into our application, and we have put some of the standard gestures—such as tap, long press, double-tap, and scale—into practice. Finally, we considered gesture classification.

Flutter Widgets Examples | List of Widgets with Examples in 2023

0
Flutter Widgets Examples | List of Widgets with Examples

We will discover flutter widgets examples, how to make them, and the various types that the Flutter framework offers in this section. Everything in Flutter is a widget, as we already know.

The app is constructed by nesting widgets inside of one another. It denotes that your app’s root element and every widget below it are both widgets. A widget, for instance, can handle interaction, define design, display something, and more.

The widget tree is simply visualized in the image below.

Widget Tree
Widget Tree

The Flutter widget can be made in the following way:

Class ImageWidget extends StatelessWidget {  
         // Class Stuff  
}  

Flutter is simple to understand if you are familiar with React or Vue.js.

Every time you write code for something in Flutter, it will be contained within a widget. The main goal is to construct the application using flutter widgets examples. With their current configuration and state, it describes how your app view ought to appear. When you change anything in the code, the widget rebuilds its description by comparing the differences between the old and new widgets to figure out which changes are absolutely necessary to render in the app’s user interface.

People, who read this article also read: Flutter Liquid Swipe Animation

Flutter Widgets Examples & Types

We can categorize the Flutter widgets examples into two groups:

  1. Visible (Output and Input)
  2. Invisible (Layout and Control)

Visible widget

The data that the user inputs and outputs is connected to the visible widgets. Among this widget’s crucial varieties are the following:

Text

Text that will be displayed on the screen is stored in a Text widget. Using the textAlign property, we can align the text widget. The style property enables us to customize the text’s font, font weight, font style, letter spacing, color, and many other aspects. The following code snippets show how to use it.

new Text(     
'Hello, Javatpoint!',     
textAlign: TextAlign.center,       
style: new TextStyle(fontWeight: FontWeight.bold),   
)  

Button

You can take action when you click on this widget. Flutter uses different types of buttons, such as a FlatButton and a RaisedButton, as opposed to allowing you to use the Button widget directly. The following code snippets show how to use it.

//FlatButton Example  
new FlatButton(  
  child: Text("Click here"),  
  onPressed: () {  
    // Do something here  
  },  
),  
  
//RaisedButton Example  
new RaisedButton(  
  child: Text("Click here"),  
  elevation: 5.0,  
  onPressed: () {  
    // Do something here  
  },  
),  

The onPressed property in the example above enables us to carry out an action when the button is clicked, and the elevation property is used to alter how prominent the button is.

Image

This widget stores the image, which can be fetched from a variety of places, including the asset folder or a URL. It provides many constructors for loading images, which are given below:

  • network: The network is used to load the images.
  • image: ImageProvider uses this general-purpose image loader.
  • file: From the system folder, it loads images.
  • memory: The image is loaded from memory.
  • asset: From your project asset folder, the image was loaded.

You must first make an assets folder in which to store your images before adding the line listed below to the pubspec.yaml file to add an image to the project.

assets:  
  - assets/  

Add the next line to the dart file now.

Image.asset('assets/computer.png') 

Below is a screenshot of the hello world example’s source code in its entirety.

class MyHomePage extends StatelessWidget {  
  MyHomePage({Key key, this.title}) : super(key: key);  
  // This widget is the home page of your application.  
  final String title;  
  
  @override  
  Widget build(BuildContext context) {  
    return Scaffold(  
      appBar: AppBar(  
        title: Text(this.title),  
      ),  
      body: Center(  
        child: Image.asset('assets/computer.png'),  
      ),  
    );  
  }  
}  

The output that the app produces when it is run is as follows.

Output
Output

Icon

For storing the Icon in the Flutter, this widget serves as a container. More details are provided in the code below.

new Icon(  
  Icons.add,  
  size: 34.0,  
)  

Invisible widget

Widget layout and control are both impacted by invisible widgets. It offers control over how the widgets appear on the screen and behave in real life. Among the crucial varieties of these widgets are:

People, who read this article also read: Flutter SDK Installation on Windows, macOS, Linux

Column

A column widget is a particular kind of widget that aligns all of its children’s widgets vertically. With the help of the mainAxisAlignment and crossAxisAlignment properties, it creates separation between the widgets. The vertical axis serves as the primary axis in these properties, while the horizontal axis serves as the cross axis.

Example

Two widget elements are built vertically in the code snippets below.

new Column(  
  mainAxisAlignment: MainAxisAlignment.center,  
  children: <Widget>[  
    new Text(  
      "VegElement",  
    ),  
    new Text(  
      "Non-vegElement"  
    ),  
  ],  
),  

Row

In contrast to the column widget, which builds a widget vertically, the row widget builds a widget horizontally. The horizontal axis in this case serves as both the main axis and the cross axis.

Example

The code fragments below to create two widget elements horizontally.

new Row(  
  mainAxisAlignment: MainAxisAlignment.spaceEvenly,  
  children: <Widget>[  
    new Text(  
      "VegElement",  
    ),  
    new Text(  
      "Non-vegElement"  
    ),  
  ],  
),  

Center

The center, the child widget that is placed inside of it, uses this widget. Each of the earlier examples includes the center widget.

Example

Center(  
  child: new clumn(  
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,  
    children: <Widget>[  
      new Text(  
        "VegElement",  
      ),  
      new Text(  
        "Non-vegElement"  
      ),  
    ],  
  ),  
),  

Padding

To give them padding in particular directions, this widget wraps other widgets. Additionally, you can add padding in every direction. The example below, which provides padding of 6.0 in all directions for the text widget, helps us to understand it.

Example

Padding(  
  padding: const EdgeInsets.all(6.0),  
  child: new Text(  
    "Element 1",  
  ),  
),  

Scaffold

You can add common material design components like AppBar, Floating Action Buttons, Drawers, etc. using the framework provided by this widget.

Stack

It is a necessary widget that is mostly used to overlap widgets, like a button on a gradient background.

State Management Widget

The two main widget types in Flutter are:

  1. StatelessWidget
  2. StatefulWidget

StatefulWidget

The state of a StatefulWidget is known. The state object and the widget are its two main classes. It is dynamic because the internal data may change over the course of the widget’s lifetime. No build() method exists for this widget. A class that extends the Flutters State Class is returned by the createState() method, which is present. The StatefulWidget includes Checkbox, Radio, Slider, InkWell, Form, and TextField as examples.

Example

class Car extends StatefulWidget {  
  const Car({ Key key, this.title }) : super(key: key);   
  
  @override  
  _CarState createState() => _CarState();  
}  
  
class _CarState extends State<Car> {  
  @override  
  Widget build(BuildContext context) {  
    return Container(  
      color: const Color(0xFEEFE),  
           child: Container(  
            child: Container( //child: Container() )  
        )  
    );  
  }  
}  

StatelessWidget

There is no state information available in the StatelessWidget. Throughout its entire lifespan, it doesn’t change. Text, Row, Column, Container, and other widget types are examples of the StatelessWidget.

Example

class MyStatelessCarWidget extends StatelessWidget {  
  const MyStatelessCarWidget ({ Key key }) : super(key: key);  
  
  @override  
  Widget build(BuildContext context) {  
    return Container(color: const Color(0x0xFEEFE));  
  }  
}  
class MyStatelessCarWidget extends StatelessWidget {  
  const MyStatelessCarWidget ({ Key key }) : super(key: key);  
  
  @override  
  Widget build(BuildContext context) {  
    return Container(color: const Color(0x0xFEEFE));  
  }  
}  

Conclusion

You’ve learned about flutter widgets examples. 

Now, I’d like to hear from you: Do you know how to use the flutter widgets with examples? Did you think it would be this easy? 

Either way, let me know by leaving a quick comment below.

What is The Elevated Button Flutter Widget | Basics of the Widget (2023)

0
Elevated-Button-Flutter-Basics-of-the-Widget

This tutorial demonstrates how to use the Elevated Button flutter widget in Flutter, starting with a basic use case and moving on to button customization.

One of the buttons in Material Design called Elevated Button has the feature that as the user presses it, its elevation rises. The Elevated Button flutter widget can be used to create a Material Design elevated button. As of Flutter 1.22, the widget is accessible.

Properties of Elevated Button Flutter

autofocus: provides a boolean value that corresponds to the button’s initial focus.

clipBehavior: determines whether or not the content is clipped.

focusNode: depicts the widget’s focus node.

ButtonStyle: determines how the button will be styled.

onLongPress: the action to be performed when the user long presses the button.

enabled: returns a boolean value indicating whether or not the button is active.

hashcode: selects the button’s hashcode

Key: Determines how one widget replaces another in the tree.

onFocusChanged: a method that is called when the focus of a button changes.

onHover: an action that is performed when the user hovers over a button.

The Procedures Offered by an Elevated Button

createElement(): Make a StatefulElement to manage the position of the button in the widget tree.

createState(): Generates the mutable state for this widget at a specified location in the tree.

build(BuildContext context): Describes a user interface component.

createElement(): creates a StatelessElement to manage the widget’s position in the tree.

debugDescribeChildren(): This method returns a list of DiagnosticsNode objects that describe the children of this node.

debugFillProperties(): Add additional properties associated with the node.

noSuchMethod(): Called when a non-existent method or property is accessed.

toDiagnosticsNode(): Returns a debug representation of the object used by debugging tools. 

toString(): Returns a string representation of this object.

toStringDeep(): This function returns a string representation of this node and its descendents.

toStringShallow(): Returns a one-line detailed description of the object.

toStringShort(): This widget’s textual description in a short string.

The Issue

When you add an ElevatedButton to your app, it changes the background color of a button to the primarySwatch color. For instance, if you recently created a new app, the ElevatedButton may have a blue background due to the primarySwatch being set to Colors.blue.

child:  ElevatedButton(
          onPressed: () {},
          child: const Text(
            'Elevated Button',
            style: TextStyle(fontSize: 40),
          ),
        ),

Output:

flutter default elevated button

Reminder

The majority of mobile and web applications have buttons that users can press to interact. Elevated buttons can be made in Flutter using the ElevatedButton widget.

RaisedButton is no longer supported and has been replaced by ElevatedButton.

Upgrade to Flutter 1.22.0 or a later version if you want to use ElevatedButton without getting any errors or warnings. Run this command: flutter upgrade to make it simple to do that. To ensure that they are compatible with Flutter 2.8.1 and later, the code snippets in this article were recently updated.

How to Change the Elevated Button Color Flutter

The Elevated button’s background color may need to be changed, but the primarySwatch should remain the same.

Simply set the Elevated Button’s style property from the Elevated Button Color Flutter to change the Elevated Button’s color. To change the primary property’s color, use the static styleFrom() method.

These are the actions:

  1. Place the ElevatedButton widget there.
  2. ElevatedButton is assigned after the style parameter is added inside it. styleFrom().
  3. Add the main parameter and any color to ElevatedButton.styleFrom.
  4. Launch the app.
child:  ElevatedButton(
          onPressed: () {},
          style: ElevatedButton.styleFrom(
            primary: Colors.green, // Background color
          ),
          child: const Text(
            'Elevated Button',
            style: TextStyle(fontSize: 40),
          ),
        )

Output:

elevated button color

Enable/Disable

Simply set the onPressed parameter to null to disable an ElevatedButton. Set the onPressed parameter to a void function to enable an ElevatedButton.

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title:const Text("FLUTTER SERVICE"),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(25),
          child: Column(
            children: [
              // An enabled button
              ElevatedButton(
                child: const Text('Enabled Button'),
                onPressed: () {},
              ),

              // A disabled button
              const ElevatedButton(
                  onPressed: null, child: Text('Disabled Button'))
            ],
          ),
        ),
      ),
    );
  }
}

Output 

elevated button enable disable

Color Modification for the Elevated Button Flutter

You might occasionally want to modify the Elevated Button’s text color. Simply assign the color of your choice to the onPrimary property to accomplish this.

What to do is as follows:

  1. ElevatedButton.styleFrom() is assigned after the style parameter is added inside it.
  2. Add any color to the onPrimary parameter (within ElevatedButton.styleFrom).
  3. Fire up the app!
ElevatedButton(
  onPressed: () {},
  style: ElevatedButton.styleFrom(
    primary: Colors.black, // Background color
    onPrimary: Colors.amber, // Text Color (Foreground color)
  ),
  child: const Text(
    'Elevated Button',
    style: TextStyle(fontSize: 40),
  ),
)

Output 

elevated button style from

How to Change the Elevated Button Flutter Color on hover

The ButtonStyle widget can be used to alter the Elevated button’s hover color. The overlayColor property can be added inside the ButtonStyle widget, and colors can be assigned based on state, such as on press, on hover, and on focused.

Here’s how to go about it:

  1. Incorporate the ElevatedButton widget.
  2. In the ElevatedButton, add the overlayColor parameter and assign the aterialStateProperty. resolveWith().
  3. Verify if the state is hovered, and if it is, run the color of your choice again.
ElevatedButton(
              onPressed: () {},
              style: ButtonStyle(
                overlayColor: MaterialStateProperty.resolveWith<Color?>(
                  (Set<MaterialState> states) {
                    if (states.contains(MaterialState.hovered))
                      return Colors.redAccent; //<-- SEE HERE
                    return null; // Defer to the widget's default.
                  },
                ),
              ),
              child: const Text(
                'Elevated Button 1',
                style: TextStyle(fontSize: 24),
              ),
            ),

How to Change the Elevated Button Flutter Border Color

Here’s how to do it if you want to give the Elevated Button a border and change its color:

  1. BorderSide() should be set and the side property added.
  2. Add the width and color properties inside the BorderSide() function, then choose the right color to use.
 body: Center(
        child:ElevatedButton(
          onPressed: () {},
          style: ElevatedButton.styleFrom(
            primary: Colors.black,
            onPrimary: Colors.amber,
            side: BorderSide(color: Colors.red, width: 5),
          ),
          child: const Text(
            'Elevated Button',
            style: TextStyle(fontSize: 40),
          ),
        )
      ),

Output 

elevated button border color

How to Change the Elevated Button Flutter Color on press

Using the ButtonStyle widget, you can modify the Elevated button’s color on PESS. You can include the overlayColor property inside the ButtonStyle widget and assign the color based on state, such as on press, on hover, and on focused.

Here’s how to go about it:

  1. Place the ElevatedButton widget there.
  2. Add the aterialStateProperty and the overlayColor parameter inside the ElevatedButton. resolveWith().
  3. If the state is pressed, check to see if it is pressed, and then run the color of your choice again.
body: Center(
        child:ElevatedButton(
          onPressed: () {},
          style: ButtonStyle(
            overlayColor: MaterialStateProperty.resolveWith<Color?>(
                  (Set<MaterialState> states) {
                if (states.contains(MaterialState.pressed))
                  return Colors.redAccent; //<-- SEE HERE
                return null; // Defer to the widget's default.
              },
            ),
          ),
          child: const Text(
            'Elevated Button 1',
            style: TextStyle(fontSize: 24),
          ),
        )
      ),

How to Change the Shadow Color of the Elevated Button Flutter

You might also want to alter the shadow color of the Elevated Button if you are designing your app to adhere to your brand guidelines in full. Your button must first be elevated in order to change the shadow’s color.

We’ll examine how to alter the shadow’s color now:

  1. The elevation property should be added inside the Elevated Button, and its value should be 20.
  2. Now add the shadowColor property to the elevated button and set it to the shade of gray you desire for the shadow.
  3. Launch the app.
  body: Center(
        child:ElevatedButton(
          onPressed: () {},
          style: ElevatedButton.styleFrom(
            primary: Colors.black,
            onPrimary: Colors.amber,
            elevation: 20,  // Elevation
            shadowColor: Colors.amber, // Shadow Color
          ),
          child: const Text(
            'Elevated Button',
            style: TextStyle(fontSize: 40),
          ),
        )
      ),

Output 

elevated button shadow color

Elevated Button Color Management at the App Level

It is not permitted to change the color of each Elevated Button in your app. What if the branding of your app is altered? Would you like to spend many hours looking for every button and changing its color? Certainly not, Let’s look at how you can customize the Elevated Button’s theme at the app level. By doing this, every Elevated Button in your app will have the same appearance, and you can change them all at once.

These are the actions:

  1. Go to your main.dart file.
  2. Locate the ThemeData widget inside the MaterialApp.
  3. The elevatedButtonTheme property should be added, and ElevatedButtonThemeData() should be assigned.
  4. As you would for a standard ElevatedButton, add the style property and modify the color.
  5. See where you can place the ElevatedButton widget in your Flutter application.
MaterialApp(
  title: 'Flutter Demo',
  theme: ThemeData(
    primarySwatch: Colors.blue,
    elevatedButtonTheme: ElevatedButtonThemeData(
      style: ElevatedButton.styleFrom(
        primary: Colors.greenAccent, // background (button) color
        onPrimary: Colors.black, // foreground (text) color
      ),
    ),
  ),
  home: ElevatedButtonColorDemo(),
);
@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: ...
      backgroundColor: const Color(0xff6ae792),
    ),
    body: Center(
      child: Column(
        children: [
          SizedBox(
            height: 50,
          ),
          ElevatedButton(
            onPressed: () {},
            child: const Text(
              'Elevated Button 1',
              style: TextStyle(fontSize: 24),
            ),
          ),
          ElevatedButton(
            onPressed: () {},
            child: const Text(
              'Elevated Button 2',
              style: TextStyle(fontSize: 24),
            ),
          ),
          ElevatedButton(
            onPressed: () {},
            child: const Text(
              'Elevated Button 3',
              style: TextStyle(fontSize: 24),
            ),
          )
        ],
      ),
    ),
  );
}

Conclusion

We learned how to change the Elevated Button flutter color in this tutorial. Additionally, using real-world examples, we looked at how to alter the background and text colors as well as the shadow, border, and disabled state colors. In the end, we discovered how to choose colors for all of the Elevated Buttons in our app from a single location.

Would you like to check other interesting Flutter tutorials?

Read More:

Flutter Liquid Swipe Animation – The Best Liquid Swipe Animation

Flutter Stateful Widget Setstate with Parameters | State Management (2023)

0
Flutter Stateful Widget Setstate

This section will cover the idea of the flutter stateful widget setstate with parameters, the order in which states should be executed, and how to manage app states. Everything in Flutter is a widget, and there are two types of widgets based on their states. Two widgets, 

  1. One stateful 
  2. Stateless 

The stateless widget has no states, and once it is created, there is no way to alter or change anything inside of it. But with a stateful widget, we can adjust both the widget’s appearance and its child structure as necessary. To create interactive apps, a flutter stateful widget setstate with parameters is crucial.

Defining State

The widget’s state is a collection of data that is collected during construction and modification while an application is running. The setState() method can be used to update a widget’s state whenever you want to update or modify its structure. The user interface is updated, and the widgets are refreshed by setState() in response to recent state changes. 

To create an interactive app, state management is a crucial step. All user interfaces are created by Flutter based on the declarations and app states that are currently in effect.

Create a Stateful Widget

You must extend the widget build class with “StatefulWidget” as shown below in order to create the stateful widget.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
       home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget{
  @override
  State createState() {
    return _HomePage();
  }
}

class _HomePage extends State{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
       appBar: AppBar( //appbar widget inside Scaffold
         title: Text("Stateful Widget")
       ),

       body: Center(
         child: Text("Stateful Widget"),
       )
    );
  }
}

The HomePage widget in the code above has a child class named _HomePage() that extends the state of its parent class. 

How to update the State and Widgets in the App

You might need to modify the data and user interface (UI) in an interactive and dynamic app depending on the situation. Although widgets are updated using the setState() method, variables’ values, and states may change in the background. See the example below to demonstrate how to update the state and widgets within an application. A floating action button and a centered text with a counter value can be seen in the example code that follows. The counter value will be increased when the floating action button is pressed, and setState() will be used to update the widget’s displayed value.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
       home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget{
  @override
  State createState() {
    return _HomePage();
  }
}

class _HomePage extends State{
  int counter;

  @override
  void initState() { //inital state which is executed only on initial widget build.
    counter = 0;
    super.initState();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
       appBar: AppBar( //appbar widget inside Scaffold
         title: Text("Stateful Widget")
       ),

       floatingActionButton: FloatingActionButton( 
          onPressed: (){
            setState(() { // setState to update the UI
               counter++; //during update to UI, increase counter value
            });
          },
          child: Icon(Icons.add), //add icon on Floating button
       ),

       body: Center(
         child: Text("Counter: $counter"), //display counter value
       )
    );
  }
}

Output: 

Initial Output
Initial Output
Output after increment and setState()
Output after increment and setState()

In-App Execution Order for flutter stateful widget setstate with parameters:

If you’re developing an app, it’s essential to comprehend the code execution flow. To understand the execution flow in Flutter, look at the example code below and its result.

import 'package:flutter/material.dart';

void main() {
   print("1. main method executed.");
   runApp(MyApp()); 
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    print("2. MyApp widget build.");
    return MaterialApp(
       home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget{
  @override
  State createState() {
    print("3. HomePage state build.");
    return _HomePage();
  }
}

class _HomePage extends State{
  int counter;

  @override
  void initState() { //inital state which is executed only on initial widget build.
    print("4. Initial state of _HomePage.");
    counter = 0;
    super.initState();
  }
  
  @override
  Widget build(BuildContext context) {
    print("5. Widget build of _HomePage.");
    return Scaffold(
       appBar: AppBar( //appbar widget inside Scaffold
         title: Text("Stateful Widget")
       ),

       floatingActionButton: FloatingActionButton( 
          onPressed: (){
            print("----button pressed----");
            setState(() { // setState to update the UI
               print("6. setState() after button press.");
               counter++; //during update to UI, increase counter value
            });
          },
          child: Icon(Icons.add), //add icon on Floating button
       ),

       body: Center(
         child: Text("Counter: $counter"), //display counter value
       )
    );
  }
}

Output:

Output
Output

You must make a note of the following two points from the output above.

  1. initState() is executed only one time before the widget build.
  2. Widget build repeats after setState().

People, who read this article also read: Flutter Liquid Swipe Animation

Conclusion

You’ve learned the basics of how to use flutter stateful widget setstate with parameters.

Now, I’d like to hear from you: Do you know how to use the flutter stateful widget setstate with parameters? Did you think it would be this easy? 

Either way, let me know by leaving a quick comment below.

How To Run Flutter App In Android Emulator in 2023?

0
How to run Flutter App in Android Emulator

This article tells about the easiest way to run Flutter App in Android Emulator.

After writing your first Flutter App, it’s time to run it on an emulator or physical device. To set up an emulator or physical device with IDE, follow the steps below.

What Is An Android Emulator? What Are The Steps Required To Run Flutter App In Android Emulator

An emulator is a virtual machine designed to run applications or programs derived from the host system. The use of an Android emulator, which simulates an Android device, allows you to run and test Android applications on your host system without a physical Android device being present. If you are not already familiar with the android studio, running your flutter applications on an emulator can be challenging. To run your Flutter app on an Android emulator, follow the instructions in this article. There are only three easy steps required to run your flutter application on an android emulator:

  1. Installation 
  2. Connection
  3. Running 

Given below is a detailed explanation of these steps one by one.

People, who read this article also read: Flutter Liquid Swipe Animation

Installation of the Emulator 

Open the SDK Manager by selecting the “SDK Manager” option from the More Options tab that is located in the system’s center when you launch Android Studio.

SDK Manager
SDK Manager

After selecting SDK manager, you will be taken to the Android SDK tab, where you can choose Tools. Click “OK” after selecting the “SDK Tools tab” and checking the relevant boxes. 

Command Line Tool for the Android SDK

  1. Tool for the Android SDK Platform
  2. Android emulator
  3. USB Driver for Google 
  4. The installation process for the required components will begin.
Command Line Tool for the Android SDK
Command Line Tool for the Android SDK

When the installation is complete, click the “Finish” button in the bottom right corner of your screen.

SDK platform tools
SDK platform tools

To open the Virtual Device Manager, select the button labeled “Virtual Device Manager” which is located in the middle of the screen next to the SDK manager option.

Android Studio
Android Studio

Create Virtual Device Manager: Select the button labeled “Create Virtual Manager” located precisely in the center of the screen. The hardware selection dialog box will appear.

Creating Virtual Device
Creating Virtual Device

Hardware selection: Choose the kind of Android emulator you want, then move on to the following page. 

Choosing a Device
Choosing a Device

Choose System Image: Decide which system image will be used by your Android emulator, check the settings, and complete the installation. Your virtual machine is now operational. 

Choosing System Image
Choosing System Image

Creating Connection 

Pick a device: Open VS Code, then select the Flutter Device option from the drop-down menu in the bottom right corner of your home screen.

Choosing a API
Choosing a API

Choose Device: When you click on the Flutter Device icon, the command palette will display a list of all the devices that are currently available. Choose the emulation program you just made.

Selecting a Device
Selecting a Device

Process the emulator: The procedure for opening the emulator will begin. Waiting for it to open up might take a few seconds.

Waiting For Connection
Waiting For Connection

Emulator launched: Your Android emulator is now prepared to run Flutter app in android emulator. 

Android Device
Android Device

Running the Device

The “Debug mode” setting must be activated in order to configure a physical device.

Run the following command in the terminal once everything has been configured.

flutter doctor

It will indicate whether any connected or configured devices are running Flutter apps.

Flutter Doctor
Flutter Doctor

Use the following commands to run your flutter app now:

flutter run

The active emulator or actual Android device will run your Flutter app in debug mode when you issue this command. In debug mode, your app will operate slowly.

People, who read this article also read: Flutter SDK Installation on Windows, macOS, Linux

Run your Flutter app in release mode by entering the command below. Your app’s actual performance will be evaluated in release mode.

flutter run --release
Flutter Test Apps
Flutter Test Apps

To see the changes made by your code on the user interface, you can hot + restart or hot + reload while in debug mode. Press “Ctrl + r” to perform a hot restart, or just “r” to perform a hot reload.

These were the 3 easiest ways to run the flutter app in the android emulator.

Check the following for a detailed overview

Write First Application: Getting Started With Flutter Hello World in 2023

0
Write First Application: Getting Started With Flutter Hello World

This is a guide to getting started with Flutter Hello World. You can finish this tutorial if you are familiar with object-oriented programming and fundamental programming ideas like variables, loops, and conditionals. No prior knowledge of Dart, mobile, desktop, or web programming is required.

Everything in Flutter is a widget, and using predefined widgets, one can create custom widgets just like one can create custom data types using int, float, and double. Three widget types can be found in Flutter.

  1. Stateless Widget
  2. Stateful Widget
  3. Inherited Widget

What You Plan To Construct 

You’ll implement a simple app that generates “Hello World”

In this article, we will use Stateless Widget, Stateful Widget, center, material app, and Inherited Widget.

Stateless Widget: In Flutter, stateless widgets are those that cannot be changed. To draw components on the screen, stateless widgets have a method (or function) called build that is called just once. A stateless widget must be created in a new instance in order to be redrawn. 

MaterialApp: This widget is also offered by the Flutter Team and adheres to the Google Material Design Scheme. MaterialApp is a class with a number of named arguments, such as home, where we can pass the widget that will be displayed on an app’s home screen. 

Flutter Documentation has more information about MaterialApp. 

People, who read this article also read: Flutter SDK Installation on Windows, macOS, Linux

Center Widget: The Flutter Team has also predefined the Center widget, which accepts another widget as its child argument. As the name implies, Center Widget will display Widget in its child argument. 

Center(
	child: Widget(
	),
),

Getting Started with Flutter Hello World

Flutter apps can also be built for desktops. Your operating system should be listed under devices in your IDE, such as Windows (desktop), or it may be specified at the command line using flutter devices. 

Text Widget: The Flutter Team has also predefined a text widget that is used to display text. Let’s create a Hello World app with Flutter now.

The package that includes definitions for Stateless Widget, Center, Text, Material App, and many more are being imported at this time. Similar to a C++ program’s #include<iostream> statement.

Build: This method is in charge of painting components on the screen. It accepts a BuildContext argument that specifies which widgets should be painted on the screen first and in what order. 

To create the “Hello World” app, open the main.dart file, remove all default codes, and then follow the instructions below.

import 'package:flutter/material.dart';

void main() {
  // initial default method which is first executed
}

The first method that will automatically run is main(). You must begin writing more code inside of this method.

Make a new class now and add StatelessWidget as an extension.

import 'package:flutter/material.dart';

void main() {
}

class MyApp extends StatelessWidget{
}

The following code will appear when you click the yellow balloon that appears after you click the red line that appears on “MyApp” in VS Code or Android Studio because of a syntax error.

import 'package:flutter/material.dart';

void main() {
   
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    throw UnimplementedError();
  }
}

Put the code below in the main() method.

runApp(MyApp()); 

Create a class for the home page now and extend it with StatelessWidget.

class Home extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
       appBar: AppBar(
         title: Text("Welcome to Flutter")
       ),
       body: Center( 
          child: Text("Hello World"),
       )
    );
  }
}

Put the following code in the widget build of the MyApp class now:

return MaterialApp(
       home: Home(), //home class
 );

Final Code:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
       home: Home(),
    );
  }
}

class Home extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
       appBar: AppBar(
         title: Text("Welcome to Flutter")
       ),
       body: Center( 
          child: Text("Hello World"),
       )
    );
  }
}

This is how you can be getting started with flutter “Hello World” on your first application, on a real mobile device, or on an emulator right away. The final product will resemble the pictures below.

Output

Android App
Android App
iOS App
iOS App

Analysis of the output 

The first line imports the material design library that will be used in this application. Then comes our primary purpose. The execution of the code will begin at this point. 

  • This is essentially our widget tree for getting started with flutter “hello world” app. 
  • The build method, which returns a MaterialApp widget, comes after all of this. 
  • Next, we used MaterialApp’s home property, which holds the Scaffold widget. The entire app screen is contained by the Scaffold widget. 
  • We have made use of the AppBar property, which accepts the AppBar widget as an object. 
  • The AppBar widget then has the title “GFG” displayed. The body is the following item, which is once more a MaterialApp property. 
  • The text widget that says “Hello World” is a child of the Center, which is the body’s object.

A word of advice: Indentation may become distorted when pasting code into your app. The formatting tool listed below can be used to fix this:

  1. VS Code: Right-click and choose “Format Document” in VS Code.
  2. Java IDEA and Android Studio: Reformat the code with dartfmt by right-clicking it. Run the command flutter format in the terminal.

Observations

This example shows how to make a Material app. Material is a visual design language that is widely used on mobile devices and the web. Flutter provides a diverse set of Material widgets. It’s a good idea to include a uses-material-design: true entry in the flutter section of your pubspec.yaml file. This enables you to use more Material features, such as its predefined Icons.

  1. The app extends StatelessWidget, making it a widget in and of itself. Alignment, padding, and layout are all widgets in Flutter.
  2. The Scaffold widget from the Material library includes a default app bar and a body property that holds the home screen widget tree. The widget subtree can be quite complex.
  3. The primary function of a widget is to provide a build() method that describes how to display the widget in terms of other, lower-level widgets.
  4. The body for this example consists of a Center widget containing a Text child widget. The Center widget aligns its widget subtree to the center of the screen.

People, who read this article also read: Flutter Liquid Swipe Animation

Conclusion of Getting Started With Flutter Hello World

You can compile each Flutter app you make for the web as well. Currently, Chrome and the Web server should be listed in your IDE’s devices pull-down menu or at the command line using flutter devices. Chrome launches by default on the Chrome device. To enable you to load the app from any browser, the Web server launches a server that hosts it. Use the Chrome device while developing in order to access DevTools and the web server for testing on different browsers. More details are available in the articles on getting started with flutter hello world on the web.

Check this video for further details about Getting Started With Flutter Hello World:

Best IDE for Flutter | Flutter Development Environment in 2023

0
Best IDE for Flutter

The Best IDE for Flutter is listed below:

  1. Android Studio
  2. IntelliJ IDEA
  3. Visual Studio Code

An Integrated Development Environment (IDE), also known as an editor for program codes and text, is a piece of software that supports software development. 

To write the code for Flutter mobile apps, we can use any editor. After making changes to the code, you must compile it, which can be accomplished using a command prompt or terminal. There are some Editors that support better tools for Flutter app development in order to improve coding and readability. A few key features that you won’t find in a standard text editor include formatting, syntax suggestions, and debugging. The three best IDEs for flutter that are most commonly used for developing apps will be covered in this tutorial.

Android Studio

It is a robust, open-source, free tool that can be used to create native mobile apps or apps using the Flutter framework. It offers the best features for creating mobile apps, including code completion, navigation, syntax highlighting, refactoring, widget editing assistance, debugging, and more. The official Android app development tool from Google is what we know as Android Studio, and it speeds up the creation of high-caliber mobile apps. Still, we can’t really tell if this is the best IDE for flutter development.

Android Studio
Android Studio

Android Studio must first be downloaded and installed in order to begin building apps with it. The necessary SDK and platform plugins for the Android environment will be installed when you run it after installation.

People, who read this article also read: Flutter Liquid Swipe Animation

Navigate to File > Settings > Plugins in Android Studio to add support for Flutter and Dart. Install the “Flutter” and “Dart” plugins after finding them. You are now completely prepared to create your first program. 

Key features of Android Studio

  • Excellent mode for debugging.
  • Simple to understand and use.
  • Large Developer Community.
  • Features that are specific to Flutter.

IntelliJ IDEA

The feature-rich IDE IntelliJ IDEA is maintained and developed by JetBrains and was designed for software development. Code refactoring and sophisticated code navigation are among its many features. With its advanced error-checking features, error-checking is made quicker and simpler.

IntelliJ IDEA
IntelliJ IDEA

Install Visual Studio Code after downloading it from the site’s official page.

Key features of IntelliJ IDEA

  • Intelligent code completion
  • Automatic imports
  • User-friendly.

Visual Studio Code:

Visual Studio Code, also known as the VS Code editor, is a popular IDE for writing various types of code in various languages. It is also widely used for Flutter App development because it is free, lightweight, and simple to use. It includes a Google Dart and Flutter plugin that allows it to integrate the Flutter development environment. Furthermore, it includes features such as code completion, syntax highlighting, debugging, running, real-time error warning, and many more. 

Visual Studio Code
Visual Studio Code

Install Visual Studio Code by downloading it from its official website.

Go to File > Preferences > Extensions to install Flutter plugins in VS Code. Install the “Flutter” and “Dart” extensions. Now that you are prepared, write your first program.

People, who read this article also read: Flutter SDK Installation on Windows, macOS, Linux

Key Features of Visual Studio Code

  • Cross-Platform assistance
  • Portable software.
  • Code sensing, i.e. intelligent.
  • Outstanding tool support

In terms of the best IDE for flutter SDK, it really comes down to personal preference. There can be no clear winner because each person has a different preference for the features they want. However, putting personal preference aside, if someone is new to Flutter and looking for advice, we have a conclusion for you.

Use of Android Studio for your projects is advised if you have a powerful operating system. The Flutter Team suggests it as a good IDE for Flutter.
Visual Studio Code is suggested as a starting point if you use a low-end system. Both of them are efficient editors that can lighten the burden on your computer system.

For further details, see the video below:

Flutter SDK Installation on Windows, macOS, Linux in 2023

0
Flutter SDK Installation on Windows

Flutter SDK Installation on Windows

Start creating apps by installing Flutter on your Windows operating system. You need the following minimum equipment before you can install Flutter on Windows:

Operating SystemsWindows 7 SP1+ (64-bit), x86-64 based
Disk Space1.32 GB (It does not include disk space for IDE/tools)
Windows ToolsWindows PowerShell 5.0, Git for Windows 2.x
IDEAndroid Studio (Official), Visual Studio Code
SDKAndroid SDK, Flutter SDK

Flutter is essentially Google’s portable user interface (UI) toolkit, which can be used to create attractive, natively-built applications for mobile, desktop, and the web from a single codebase.

In the case of Git for Windows, you should ensure that you can execute git commands from the command line or PowerShell.

Having installed all these tools on your Windows OS, it’s time for Flutter SDK installation on Windows. Visit the Flutter SDK’s official site to download and install it.

Flutter SDK Installation Process on Windows:

Follow the below steps to install Flutter on Windows:

  1. Navigate to flutter.dev on your webpage. 
  2. On the top menu bar, select Docs > Get Started > Install > Windows.
Flutter documentation
Flutter Documentation
Flutter SDK installation
Flutter Installation

Git and PowerShell

  1. Once Git has been installed on your Windows computer, restart the system. The next step is the Flutter Software Development Kit (Flutter SDK) installation on Windows. Download the latest version (as of today) by clicking the link below.
Downloading the latest version
Downloading the latest Version
  1. This tool allows us not only to build flutter projects but also to transform them into native mobile applications. The main tool for creating a flutter UI is the Flutter SDK, to put it simply.
  2. Once the zip file has been downloaded, extract the “flutter” folder (drag and drop) to any system path or directory where you have read-write access. Due to permission issues, it is usually preferable to make a new folder in a different directory from the system drive (in my case, the target location is F: > development > flutter).
WinRAR
WinRAR
  1. Right-click the “flutter” folder twice to start over. Open a command prompt window by double-clicking the file named “flutter_console.bat.” It should look something like this:
Command Prompt
Command Prompt
  1. This console is actually a Windows terminal that the developer can use to execute flutter commands. A list of all available flutter commands can be obtained by typing “flutter.”
Windows Terminal
Windows Terminal

Even though having a terminal to run flutter commands and create projects is useful, it would still be better and more convenient to store all of our flutter projects somewhere else on our system for easy access. Let’s continue on our journey!

People, who read this article also read: Flutter Liquid Swipe Animation

Configuring Flutter SDK for the First time

  1. Examine and modify environment variables to gain access to the entire system. On the flutter installation page’s official Docs page, scroll down to “Update your path” for instructions. You can do this by going to Control Panel > System and Security > System > Advanced System Settings > Environment Variables… On your screen, a dialog box with a list of the accessible environment variables appears.
Environment Variables
Environment Variables
  1. Environment variables are global system variables that are present at the root level and help configure different parts of Windows. The flutter tool will now be unlocked for use across all of your system’s PowerShell and Command Prompt instances and added as an environment variable for direct access (rather than being launched via the .bat executable).

Look over the following steps to accomplish this:

  1. Under the list of User Variables, look for the ‘Path’ variable. Create a new variable (‘New…’). If it isn’t already there, create it and set its value to the ‘flutter\bin’ directory.
  2. In order to add a new entry, double-click on a column below the variable labeled “Path.” It should look something like this:
Flutter BIn
Flutter Bin
  1. Copy the directory of the flutter\bin folder in its entirety, then paste it in the path. To finish the setup, click “Ok” twice. Ensure that all open Command Prompt/Windows PowerShell windows have been closed at this point.

Now determine if your flutter framework is accessible from anywhere in the world. To accomplish this, launch any terminal (such as Command Prompt) and type “flutter” to see if you receive the same list of commands as you did earlier from the.bat terminal. If so, your system has been successfully configured to use flutter at the root level. If not, you should think about running the setup again.

Flutter Doctor Command Prompt
Flutter Doctor Command Prompt

Analyzing the Application

The next step is to analyze and determine what is needed and what needs to be installed. Enter “Flutter Doctor” in the Command Prompt terminal to check for any additional requirements.

Flutter Doctor
Flutter Doctor

Here’s what the previous version looked like:

Old Version of Flutter Doctor
Old Version of Flutter Doctor

The flutter doctor check indicates that flutter was successfully installed on our system, but the Android tools and Android Studio are not present. Additionally, we observe that there are no connected devices. In order to run the flutter apps you created, the following step entails installing Android tools on your device.

Installing Android Tools for Flutter SDK installation on Windows

Installing Android emulators and tools on Android devices.

  1. Downloading and installing Android Studio is the first step. To do this, go to the Android Studio official website and select “Download Android Studio.”
Android Studio
Android Studio
  1. You can proceed once you have accepted the license agreements. To initiate the download, click the last download button.
License Agreement
License Agreement

The next step is the Flutter SDK installation on Windows after the download is finished. 

Flutter SDK Installation on Windows

Before continuing, make sure that Android Studio and Android Virtual Device are both selected under “Components.” Running different kinds and sizes of Android emulators to test your flutter project requires the Android Virtual Device, which is a crucial tool. Go ahead and click “Next.”

Flutter Virtual Device
Flutter Virtual Device

Choose the directory you want to install your file in. A different path other than the system drive should be chosen, it is advised. Once done, click on ‘Next‘.

Android Studio Setup
Android Studio Setup

Select “Install” at the end. The installation won’t be finished for a few seconds. You should select the “Launch Android Studio” checkbox. Click on “Finish.”

Wait for Android Studio to start up on your computer. Next > Custom > Next must be selected from the home screen.

Android Studio Setup Wizard
Android Studio Setup Wizard
Android Studio Setup Wizard
Android Studio Setup Wizard

To save time and trouble, it is advised to use the default path for the Java Development Kit location in the following step. The UI appearance you want for Android Studio should be selected in the following step. Click ‘Next‘.

The following action is somewhat significant. Keep in mind to check all the necessary boxes precisely as they are shown below. Those kits that have already been installed can be disregarded, and you can continue. Choose “Next.” You can choose the Android SDK folder you want.

Android Studio Setup Wizard
Android Studio Setup Wizard

Click “Finish” once you’ve finished. All the Android tools required for the execution of your flutter projects will now be installed by Android Studio. Waiting is preferable because this could take some time.

Android Studio Setup Wizard
Android Studio Setup Wizard

We are now prepared to design and develop Flutter projects in Android Studio and execute them on a real or simulated Android device (emulator).

Setting Up an Android Emulator

To build your application, you can use either an Android device or an Android emulator. It depends totally on you.

Visit the official documentation page and follow the detailed instructions for setting up an Android device. By clicking the link, you can download The Google USB Driver and install it. This can also be installed using Android Studio, which you can then use to develop the application by connecting to a real Android device.

Setting up Android Device
Setting up Android Device

Now, setting up the Android device is the only thing left to do. Now that the flutter framework is up and running, you can create gorgeous apps using devices or emulators. Go crazy!

People, who read this article also read: Flutter LayoutBuilder Widget Example Step by Step

Flutter SDK Installation on macOS

You must have the following components on your system in order to install Flutter on macOS.

Operating System macOS (64-bit)
Disk Space2.8 GB (does not include disk space for IDE/tools).
Tools git 2.x
IDEXcode (Official)

To install the Flutter SDK on macOS, follow the steps below:

  1. Visit the official website to download the most recent Flutter SDK installation bundle.
  2. To the desired location, extract the installation bundle. To extract using the terminal, enter the commands listed below. 
cd ~/development
unzip ~/Downloads/flutter_macos_1.22.6-stable.zip
  1. Your path should also include the flutter.
export PATH="$PATH:`pwd`/flutter/bin"
  1. With the help of the flutter doctor command, you can determine whether flutter is set up properly by updating the PATH for the current session. 

The steps below should be followed for permanent PATH configuration:

  1. Change the $HOME/.bashrc or $HOME/.bash_profile file. 
  2. Replace [PATH_TO_FLUTTER_GIT_DIRECTORY] with the location of the folder into which you extracted the Flutter SDK when inserting the line below.
export PATH="$PATH:[PATH_TO_FLUTTER_GIT_DIRECTORY]/flutter/bin"
  1. To automatically refresh the source file, open a new terminal window or run source $HOME/. to refresh the current terminal window. The Flutter SDK is now fully configured, and you can use flutter doctor to view additional configuration reports. 

Flutter SDK installation on Linux

The following minimal requirements must be present on your operating system in order to install Flutter on Linux:

Operating Systems:Linux (64-bit)
Disk Space:600 MB (It does not include disk space for IDE/tools).
Tools:bash
curl
file
git 2.x
mkdir
rm
unzip
which
xz-utils
zip
Shared libraries:libGLU.so.1

On a Linux operating system, snapd is the fastest way to install the Flutter SDK. Follow the official instructions to install snapd on Linux if you haven’t already. 

Run the following command in the terminal once Snapd has been installed.

sudo snap install flutter --classic

Run the following command to determine whether Flutter has been installed after using snapd:

flutter sdk-path

In this way, you can do Flutter SDK installation on Windows, macOS, and Linux. Both the Flutter SDK and the Android SDK are necessary to create an app with Flutter. When you install Android Studio, the Android SDK is also installed.

Check the following Video for Further detailed instructions: