Home Blog Page 4

How To Add And Customize Radio Button in Flutter in 2023?

0
How To Add And Customize Radio Button In Flutter? Everything That You Need

In this article, you will be able to get a basic and intermediate understanding of how to add and customize a radio button in Flutter. So, stay tuned!

Formatting answer choices so that a question’s instructions are implicit to the user is a persistent problem when gathering user data. The issue is resolved by the design of a radio button, a graphical user interface element that displays a predefined list of mutually exclusive answer options.

For mobile applications, radio buttons are a great option because they are frequently brief and simple to scan. The default radio button in Flutter doesn’t keep track of anything. As an alternative, it calls the onChange callback function each time a selection is made.

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

The built-in Flutter method will be used to create a straightforward radio button in this tutorial, after which we’ll create our own Flutter widget to customize the radio button in Flutter. 

Here are the steps to consider understanding this tutorial easily:

  • Your computer has Flutter installed.
  • Basic understanding of Flutter
  • working knowledge of Dart
  • Installed on your computer is either Xcode or Android Studio.
  • A testing tool would be an iOS or Android emulator.
  • VS Code, which is a code editor
  • Let’s get going!

The Beginning

We’ll create a new Flutter project first. Copy and paste the following code after navigating to your work directory:

flutter create radio_button_app

Open your iOS simulator or Android emulator once initialization is finished. Enter the command below to launch the app after finding the stripe_app folder:

cd radio_button_app && flutter run 

Suppose your app installation was successful.Then the radio button in Flutter should resemble the screenshot below:

radio button in Flutter- iOS simulator or Android emulator
iOS simulator or Android emulator

Create A Radio Button In Flutter.

Let’s start off by creating a radio button with Flutter Material Components widgets. The code listed below should be added to the top of the main.dart file to import the package:

import 'package:flutter/material.dart';

Establish A Stateless Widget.

The next step is to create a stateless widget that is immutable and on top of which we can build other applications. Let’s make a stateless widget called MyApp, which will serve as the application’s root widget and contain its scaffolding. To main.dart, add the following code:

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);
  static const String _title = 'Radio buttons';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primaryColor: Colors.black, 
        accentColor: Colors.black,
        ),
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: const Center(
          child: MyStatefulWidget(),
        ),
      ),
    );
  }
}

The runApp function in the code above receives the MyApp widget as a parameter, making it the widget tree’s root:

void main() => runApp(const MyApp());

Nothing is stored in the MyApp widget’s state. We must therefore create a stateful widget and pass it to the root widget as a child in order to build mutable or stateful widgets, such as the radio button:

child: MyStatefulWidget(),

Make A Stateful Widget

Next, let’s develop MyStatefulWidget by including the following code in main.dart:

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key key}) : super(key: key);
  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

MyStatefulWidget is dependent on a private state that is started by the immediately invoked function (IIF) createState. As a result, MyStatefulWidget refers to the private state as _MyStatefulWidgetState.

Let’s insert the following code into our main.dart file to create the private state known as _MyStatefulWidgetState:

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  Pet _pet = Pet.dog;

  @override
  Widget build(BuildContext context) {

    return Column(

      children: <Widget>[
        ListTile(
          title: const Text('Dog'),
          leading: Radio<Pet>(
            fillColor: MaterialStateColor.resolveWith((states) => Colors.green),
            focusColor: MaterialStateColor.resolveWith((states) => Colors.green),
            value: Pet.dog,
            groupValue: _pet,
            onChanged: (Pet value) {
              setState(() {
                _pet = value;
              });
            },
          ),
        ),
        ListTile(
          title: const Text('Cart'),
          leading: Radio<Pet>(
            fillColor: MaterialStateColor.resolveWith((states) => Colors.green),
            value: Pet.cat,
            groupValue: _pet,
            onChanged: (Pet value) {
              setState(() {
                _pet = value;
              });
            },
          ),
        ),
      ],
    );
  }
}

We’ll make a straightforward radio button in this example that asks the user to choose between a cat or a dog. To begin with, we change Pet’s value to Pet.dog, an enum that was declared in the global context of main.dart:

enum Pet { dog, cat }

As long as it is accessible through the global context, you can add the enum value’s code anywhere in main.dart.

The ListTile material class is used to create each radio button, enabling the combination of text, icons, and buttons.

Each selected option’s value is passed to the groupValue, which is kept up to date by MyStatefulWidget. The value of _pet is updated to reflect the option that is currently selected whenever a radio button is selected, updating the button state.

The complete code is provided below for this section:

import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);
  static const String _title = 'Radio buttons';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primaryColor: Colors.black, 
        accentColor: Colors.black,
        ),
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: const Center(
          child: MyStatefulWidget(),
        ),
      ),
    );
  }
}
enum Pet { dog, cat }
/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key key}) : super(key: key);
  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  Pet _pet = Pet.dog;

  @override
  Widget build(BuildContext context) {

    return Column(

      children: <Widget>[
        ListTile(
          title: const Text('Dog'),
          leading: Radio<Pet>(
            value: Pet.dog,
            groupValue: _pet,
            onChanged: (Pet value) {
              setState(() {
                _pet = value;
              });
            },
          ),
        ),
        ListTile(
          title: const Text('Cart'),
          leading: Radio<Pet>(
            value: Pet.cat,
            groupValue: _pet,
            onChanged: (Pet value) {
              setState(() {
                _pet = value;
              });
            },
          ),
        ),
      ],
    );
  }
}

When you launch your application, it ought to resemble the screenshot below:

Radio Button in Flutter
Radio Button in Flutter

How To Design A Radio Button In Flutter

The styling properties activeColor, focusColor, fillColor, and hoverColor allow us to modify the appearance and feel of our finished Flutter radio button.

Let’s update the code between Start copy and End copy in our two ListTile components:

ListTile(
          title: const Text('Dog'),
          leading: Radio<Pet>(
//Start copy
            fillColor: MaterialStateColor.resolveWith((states) => Colors.green),
            focusColor: MaterialStateColor.resolveWith((states) => Colors.green),
// End copy
            value: Pet.dog,
            groupValue: _pet,
            onChanged: (Pet value) {
              setState(() {
                _pet = value;
              });
            },
          ),
        ),

Your app ought to now appear as shown in the following screenshot:

Designing Radio Button in Flutter
Designing Radio Button in Flutter

Modifying A Radio Button In Flutter

Depending on the type of application you’re building, the default radio button—while functional—might be too basic for your requirements. We can now create a custom radio button for more complex use cases since we have learned how to create a radio button in Flutter using the standard Flutter radio widget.

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

Let’s start by making a widget of our own called CustomRadioButton.

int value = 0;
Widget CustomRadioButton(String text, int index){
      return OutlineButton(onPressed: (){
        setState(() {
          value = index;
        });
      },
      child: Text(
        text,
        style: TextStyle(
          color: (value == index) ? Colors.green  : Colors.black,
        ),
      ),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      borderSide: BorderSide(color: (value == index) ? Colors.green  : Colors.black),
      );

As we did with ListStyle in the section before, we use OutlineButton in the code above to create our radio button.

Text and index are the two parameters for the CustomRadioButton widget. The index contains the index number of the radio that is currently selected, while text is the radio’s name.

The CustomRadioButton value will determine the value of the index when a user selects a button, which will cause the Radio buttons to re-render with a new state.

Let’s create a radio button that offers the user the option of choosing between single, married, or other:

import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);
  static const String _title = 'Radio buttons';
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primaryColor: Colors.black,
        accentColor: Colors.black,
      ),
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: const Center(
          child: MyStatefulWidget(),
        ),
      ),
    );
  }
}
/// This is the stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key key}) : super(key: key);
  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
/// This is the private State class that goes with MyStatefulWidget.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  int value = 0;
  Widget CustomRadioButton(String text, int index) {
    return OutlineButton(
      onPressed: () {
        setState(() {
          value = index;
        });
      },
      child: Text(
        text,
        style: TextStyle(
          color: (value == index) ? Colors.green : Colors.black,
        ),
      ),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      borderSide:
          BorderSide(color: (value == index) ? Colors.green : Colors.black),
    );
  }
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        CustomRadioButton("Single", 1),
        CustomRadioButton("Married", 2),
        CustomRadioButton("Other", 3)
      ],
    );
  }
}

As shown in the following screenshot, the output of the code above should appear as follows:

Custom Radio Button in Flutter
Custom Radio Button in Flutter

Conclusion

Because of its efficiency and simplicity, the radio button in Flutter is a common UI component, especially in mobile applications. In this tutorial, we created a straightforward radio button using the built-in widget of the radio button in Flutter and a more intricate radio button using a custom widget. I sincerely hope you liked this tutorial!

How To Change Tab Bar Color Flutter? 6 Easy-To-Do Changes in 2023

0
tab bar color flutter

This article will provide 6 easy-to-do changes to the tab bar color flutter.

One of the most popular widgets in Flutter is TabBar. It can display different categories that your app has to offer. After adding the default TabBar, you might occasionally need to alter its colors, including the background color, the color of the splash and hover effects, the color of the selected and unselected text, and the indicator color. This tutorial will demonstrate how to alter the tab bar color Flutter.

You must include the TabBar on your page before we can continue. Here, the procedures for adding TabBar are listed.

If you learn best by seeing things done, you can quickly see the steps here:

Steps To Change Tab Bar Color Flutter in Background

Create a getter to return the TabBar widget first, then wrap it inside the PreferredSize -> Material widget to change the tab bar’s background color in Flutter. Create a color property inside the Material and choose a color.

The full directions are provided below:

  • Establish a getter that yields the actual TabBar.
  • PreferredSize -> Material widget should be used to enclose the TabBar widget.
  • In the PreferredSize, set the preferredSize parameter to _tabBar. preferredSize.
  • Set the color parameter inside the Material after adding the color.
  • Launch the app.

Example Code

TabBar get _tabBar => TabBar(
      tabs: [
        Tab(icon: Icon(Icons.flight)),
        Tab(icon: Icon(Icons.directions_transit)),
        Tab(icon: Icon(Icons.directions_car)),
      ],
    );
//-------
DefaultTabController(
  length: 3,
  child: Scaffold(
    appBar: AppBar(
      centerTitle: true,
      title: ...
      bottom: PreferredSize(
        preferredSize: _tabBar.preferredSize,
        child: Material(
          color: Colors.green, //<-- SEE HERE
          child: _tabBar,
        ),
      ),
      backgroundColor: const Color(0xff6ae792),
    ),
    body: TabBarView(
      children: [
        Icon(Icons.flight, size: 350),
        Icon(Icons.directions_transit, size: 350),
        Icon(Icons.directions_car, size: 350),
      ],
    ),
  ),
);

Notably, this solution keeps the splash effect that appears when you click the Tab item.

Output

Tab Bar Color Flutter
Tab Bar Color Flutter

How To Change The Color Of The Tab Bar’s Selected/Unselected Text

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

There are two states of the text in the tab bar color flutter. The first is when a tab is selected, and the second is when a tab is not selected. Add the labelColor property to the TabBar widget and set the color to modify the text color for the selected state. Add the unselectedLabelColor parameter, change its colors, and then select the unselected state to change the text color.

Example Code

const TabBar(
  labelColor: Colors.black, //<-- selected text color
  unselectedLabelColor: Colors.white, //<-- Unselected text color
  tabs: [
    Tab(text: 'Flight', icon: Icon(Icons.flight)),
    Tab(text: 'Train', icon: Icon(Icons.directions_transit)),
    Tab(text: 'Car', icon: Icon(Icons.directions_car)),
  ],
);

Output

Change The Color Of The Tab Bar's Selected/Unselected Text
Change The Color Of The Tab Bar’s Selected/Unselected Text

A Different Indicator Color

You might occasionally want to adjust the indicator color to better suit your design. Find the TabBar widget, add the indicatorColor property, and set the indicator’s color to change the color.

Example Code

const TabBar(
  indicatorColor: Colors.black, //<-- SEE HERE
  tabs: [
    Tab(text: 'Flight', icon: Icon(Icons.flight)),
    Tab(text: 'Train', icon: Icon(Icons.directions_transit)),
    Tab(text: 'Car', icon: Icon(Icons.directions_car)),
  ],
)

Output

Different Indicator Color
Different Indicator Color

Change Tab Bar Color Flutter Splash

The color that appears when you press and hold on to the widget is called the splash color. Change the tab bar color Flutter as directed here before enclosing the tab bar widget inside the Theme widget to alter the tab bar splash color. ThemeData().copyWith() method will now be added, and the data property will be used to modify the splash color

Example Code

TabBar get _tabBar => TabBar(
      tabs: [
        Tab(icon: Icon(Icons.flight)),
        Tab(icon: Icon(Icons.directions_transit)),
        Tab(icon: Icon(Icons.directions_car)),
      ],
    );
//-------
DefaultTabController(
  length: 3,
  child: Scaffold(
    appBar: AppBar(
      centerTitle: true,
      title: ...
      bottom: PreferredSize(
        preferredSize: _tabBar.preferredSize,
        child: Material(
          color: Colors.green,
          child: Theme( //<-- SEE HERE
              data: ThemeData().copyWith(splashColor: Colors.redAccent),
              child: _tabBar),
        ),
      ),
      backgroundColor: const Color(0xff6ae792),
    ),
    body: TabBarView(
      children: [
        Icon(Icons.flight, size: 350),
        Icon(Icons.directions_transit, size: 350),
        Icon(Icons.directions_car, size: 350),
      ],
    ),
  ),
);

How To Modify The Tab Bar Hover Color

The color that appears when the mouse pointer hovers over the widget is known as the hover color. Mobile devices can’t see this color. Add the overlayColor property to the TabBar widget and set the color depending on the state, such as on press, on hover, and on focus, to change the tab bar hover color.

Here’s how to go about it:

  1. Try and Add the TabBar widget.
  2. In the TabBar, add the overlayColor parameter and assign the MaterialStateProperty. resolveWith().
  3. Verify if the state hovers, and if it is, run the color of your choice again.

Example Code

TabBar(
  overlayColor: MaterialStateProperty.resolveWith<Color?>(
    (Set<MaterialState> states) {
      if (states.contains(MaterialState.hovered))
        return Colors.amberAccent; //<-- SEE HERE
      return null; 
    },
  ),
  tabs: [
    Tab(icon: Icon(Icons.flight)),
    Tab(icon: Icon(Icons.directions_transit)),
    Tab(icon: Icon(Icons.directions_car)),
  ],
)

Globally altering the tab bar color Flutter

We learned how to modify the tab bar’s page-level color in the previous section. However, there are times when you might want your app’s pages to share a common design language. The tab bar color Flutter may then need to be altered at the app level.

Here’s how to go about it:

  1. Search for the MaterialApp widget.
  2. ThemeData class-assigned parameter should be added inside the MaterialApp. 
  3. Assign the TabBarTheme after adding the tabBarTheme parameter inside the ThemeData.
  4. Add parameters like labelColor, overlayColor, and unselectedLabelColor inside the TabBarTheme.
  5. Set the desired color inside these parameters.

Example Code

MaterialApp(
  title: 'Flutter Demo',
  theme: ThemeData(
    primarySwatch: Colors.blue,
    tabBarTheme: TabBarTheme(labelColor: Colors.black), //<-- SEE HERE
  ),
  home: ChangeTabBarColorDemo(),
);

Conclusion

With the help of real-world examples, we learned how to alter the tab bar color Flutter in this tutorial. First, we looked at how to alter the background, text, and indicator colors. Next, we investigated how to alter the hover color and splash cover. We also examined the code to modify the color at the level of the application.

Would you like to view some additional engaging Flutter tutorials?

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

How To Add Border To Container in Flutter? 5 Easy Tricks in 2023

0
How To Add Border To Container in Flutter? Some Easy Tricks

In this article, we will learn some easy tricks of how to add border to container in Flutter.

There could be a lot of Container widgets added while creating a Flutter app. However, on occasion, you might want to include a container with a border to create a box UI for things like buttons, keys, cards, etc. We’ll discover in this tutorial how to add a border to a container in Flutter.

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

Increase the container’s border

By including the BoxDecoration class in the Container’s decoration property, you can give it a border. This is the first of many ways in order to add border to container in Flutter.

Instructions for adding a border to a container in Flutter:

  1. First, head over to the Container where you want to add a border.
  2. Assign the BoxDecoration class and add the decoration parameter. Put the border parameter inside the BoxDecoration and set it to Border.all().
  3. Launch the app.

What your code should look like is as follows:

Container(
  padding: const EdgeInsets.all(16.0),
  decoration: BoxDecoration(
    border: Border.all(),
  ),
  child: const Text(
    "FlutterService",
    style: TextStyle(fontSize: 34.0),
  ),
)

Border.all() creates a black border on all sides of a container. It is a very special type of constructor.

Output:

Increase the container's border
Increase the container’s border

Here is an example of how the code is translated into the design:

Code in the Design
Code in the Design

Border Width Adding

By default, the width of the border created by the Border.all() constructor is set to 1. To create a unique user interface, you might want to alter the border width and default value.

In order to give the container a wider border:

Adding the width parameter’s value inside the Border is all that is necessary. all constructor.

As for the code:

Container(
  padding: const EdgeInsets.all(16.0),
  decoration: BoxDecoration(
    border: Border.all(
      width: 10,
    ),
  ),
  child: const Text(
    "FlutterService",
    style: TextStyle(fontSize: 34.0),
  ),
)

Output:

Border Width Adding
Border Width Adding

Border Color Modification

Black is added as the default color by the constructor for Border.all. Using the color property in the Border.all constructor, you can change the default color to any other color.

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

How to modify the container’s border color

Include your unique color in the color parameter for the Border.all.

What your code should look like is as follows:

Container(
  padding: const EdgeInsets.all(16.0),
  decoration: BoxDecoration(
    border: Border.all(width: 5, color: Colors.deepPurpleAccent),
  ),
  child: const Text(
    "FlutterService",
    style: TextStyle(fontSize: 34.0),
  ),
)

Output:

Border Color Modification
Border Color Modification

Constructing a Container with Border Radius | How to add Border to Container in Flutter

You might need to add rounded corners to the container’s corners to give the UI a button-like appearance. By giving the container’s border-radius, this can be accomplished.

The steps to adding border radius to a container are as follows:

  1. Visit the Container where you want to add a border radius in step 1.
  2. Adding the decoration parameter and assigning the BoxDecoration class are step two. The borderRadius parameter should be added inside the BoxDecoration and set to BorderRadius.all (Radius.circular(50)).
  3. Run the app in the third step.

Following is an example of good code:

Container(
  padding: const EdgeInsets.all(16.0),
  decoration: BoxDecoration(
    border: Border.all(width: 5, color: Colors.red),
    borderRadius: BorderRadius.all(Radius.circular(50)),
  ), 
  child: const Text(
    "FlutterService",
    style: TextStyle(fontSize: 34.0),
  ),
)

Output:

Container with Border Radius
Container with Border Radius

To Add Border to Container in Flutter on a Few Sides

You might occasionally want to add a border to just a few of the container’s sides, such as the left and right, top and bottom, only the bottom, etc.

How to increase the container’s border-radius

  1. Go to the Container first, and then choose which sides you want to have borders on.
  2. Assign the BoxDecoration class and add the decoration parameter. Add the border parameter to the BoxDecoration and assign the BorderSide class to any of the container’s four sides (left, top, right, and bottom).
  3. Run the app in the third step.

As for the code:

Container(
  padding: const EdgeInsets.all(16.0),
  decoration: BoxDecoration(
    border: Border(
      top: BorderSide(
        color: Color(0xff6ae792),
        width: 3.0,
      ),
      bottom: BorderSide(
        color: Color(0xff6ae792),
        width: 3.0,
      ),
    ),
  ),
  child: const Text(
    "C",
    style: TextStyle(fontSize: 34.0),
  ),
)Container(
  padding: const EdgeInsets.all(16.0),
  decoration: BoxDecoration(
    border: Border(
      top: BorderSide(
        color: Color(0xff6ae792),
        width: 3.0,
      ),
      bottom: BorderSide(
        color: Color(0xff6ae792),
        width: 3.0,
      ),
    ),
  ),
  child: const Text(
    "C",
    style: TextStyle(fontSize: 34.0),
  ),
)

Output:

Add Border to Container in Flutter on a Few Sides
Add Border to Container in Flutter on a Few Sides

The code is as follows, and you can use the same method to adjust the container’s border on all sides:

Container(
  padding: const EdgeInsets.all(16.0),
  decoration: BoxDecoration(
    border: Border(
      left: BorderSide(
        color: Colors.black,
        width: 5.0,
      ),
      right: BorderSide(
        color: Colors.black,
        width: 15.0,
      ),
      top: BorderSide(
        color: Color(0xff6ae792),
        width: 20.0,
      ),
      bottom: BorderSide(
        color: Color(0xff6ae792),
        width: 8.0,
      ),
    ),
  ),
  child: const Text(
    "D",
    style: TextStyle(fontSize: 34.0),
  ),
)

Preview:

Add Border to Container
Add Border to Container

Add Border to Container in Flutter i.e. Dotted Border

Designing a UI with a dotted border may be necessary. For instance, a draggable area with a dotted border can be displayed during a drag-and-drop interaction. Let’s use dotted_border to add a dotted border to the container’s perimeter.

Follow these steps to give the container a dotted border:

  1. Open the pubspec.yaml file in step 1 and include the dotted_border package.
dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  dotted_border: ^2.0.0+1
  1. The second step is to enclose your Container widget inside the DottedBorder widget.
  2. Add the strokeWidth, color, and dashPattern parameters in step 3.
  3. Run your app in step four.

As for the code:

DottedBorder(
  color: Colors.black,
  strokeWidth: 2,
  dashPattern: [
    5,
    5,
  ],
  child: Container(
    padding: const EdgeInsets.all(
        16.0),
    child: const Text(
      "FlutterService",
      style: TextStyle(fontSize: 34.0),
    ),
  ),
)

Output:

Add Border to Container in Flutter i.e. Dotted Border
Add Border to Container in Flutter i.e. Dotted Border

There you go. I appreciate you reading this.

Conclusion

With the help of real-world examples, we learned how to add border to container in Flutter in this tutorial. Additionally, we learned how to alter the container’s border and width and how to add a border radius before seeing how to add a dotted border.

How To Flutter Hide Keyboard Easily? 3 Crazy Steps in 2023

0
flutter hide keyboard

This article enlightens you about how to Flutter hide keyboard.

If you click somewhere at the top of the screen, then it should automatically Flutter hide keyboard because not every device has a back button at the bottom to dismiss the keyboard. 

  • Alternatively, you will learn how to scroll also to the Flutter hide keyboard. 
  • Let’s start by tapping here anywhere on the screen to dismiss our keyboard. This is pretty simple.

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

In Flutter, TextField is a viral widget. A keyboard appears on-screen when you click on the TextField. You must press the back button on an Android device or the done button (located inside the onscreen keyboard) on an iOS device to hide or dismiss the keyboard. However, the issue is that while using the app, some Android phones hide the virtual (on-screen) back button, and iOS doesn’t display the done button when the numeric keyboard is open. We will therefore examine how to do so in Flutter in this article.

Method For Flutter Hide Keyboard

Using the FocusManager.instance.primaryFocus?.unfocus() method inside the GestureDetector’s onTap function, we’ll hide or dismiss the keyboard whenever a user touches anywhere on the screen.

Procedures for Flutter users to close or conceal the on-screen keyboard

  1. Wrap the GestureDetector around your widget as the first step, which should be the scaffold widget. When it comes to identifying different gestures like onTap, onDoubleTap, onLongPress, etc., the GestureDetector is incredibly helpful. 

Code should now appear as follows:

GestureDetector(
  child: Scaffold(
    appBar: AppBar(
      title: const Text('Close Keyboard Demo'),
    ),
    body: ...,
  ),
);
  1. The onTap callback should be added so that we can identify single-touch events on the screen.

Here is the most recent code:

GestureDetector(
  onTap: () {},
  child: Scaffold(
    appBar: AppBar(
      title: const Text('Close Keyboard Demo'),
      backgroundColor: Color(0xff6ae792),
    ),
    body: ...
  ),
);
  1. Last but not least, include the FocusManager.instance.primaryFocus?.unfocus() method to turn off the keyboard.

The Code:

GestureDetector(
  onTap: () {
    FocusManager.instance.primaryFocus?.unfocus();
  },
  child: Scaffold(
    appBar: AppBar(
      title: const Text('Close Keyboard Demo'),
      backgroundColor: Color(0xff6ae792),
    ),
    body: ...
  ),
);

If any TextField is currently in Focus, the FocusManager.instance.primaryFocus?.unfocus() function first verifies that it is. The on-screen keyboard is closed if TextField has the focus. If it doesn’t, it returns the focus to TextField.

The keyboard is discarded in the following manner:

flutter hide keyboard- Keyboard
Keyboard

Here’s the Complete code of the flutter hide keyboard:

import 'package:flutter/material.dart';
void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.amber,
      ),
      home: CloseKeyboardDemo(),
    );
  }
}
class CloseKeyboardDemo extends StatelessWidget {
  const CloseKeyboardDemo({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusManager.instance.primaryFocus?.unfocus();
      },
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Close Keyboard Demo'),
        ),
        body: Container(
          child: Column(
            children: [
              Container(
                padding: EdgeInsets.all(16),
                child: TextField(
                  //keyboardType: TextInputType.phone,
                  decoration: InputDecoration(
                      border: OutlineInputBorder(), labelText: 'Enter value'),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

Conclusion

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

We learned step-by-step instructions on how to flutter hide keyboard in this tutorial. With a tap anywhere on the screen, the GestureDetector will enclose the entire screen and switch the focus away from the TextField.

Are there any additional engaging Flutter tutorials you’d like to check out? Take a look at more tutorials here!

Floatingactionbutton Flutter | A Detailed Overview in 2023

0
FloatingActionButton flutter

FloatingActionButton Flutter is particularly significant due to its special characteristics and usage guidelines. Flutter provides a variety of button types in accordance with the Material Design Guidelines for a range of use cases.

We’ll introduce you to these guidelines in this tutorial and walk you through using and personalizing FloatingActionButton flutter widget.

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

What does FloatingActionButton flutter do?

Every element in Flutter is referred to as a widget, and FloatingActionButton flutter widget is no different. This widget, as its name implies, floats above other widgets on the screen.

The FloatingActionButton flutter widget typically has a circular shape and is positioned in the bottom-right corner of the screen. To further create the illusion of floating, it has an elevation. The best part is that each of these attributes can be changed.

Here is an illustration of a typical FloatingActionButton Flutter widget:

FloatingActionButton flutter- Floating Action Button
Floating Action Button

Use the floatingActionButton Flutter property of Scaffold in Flutter to use the floating action button:

Scaffold(
  floatingActionButton: FloatingActionButton(),
),

As a result, FAB will be added to the screen in its standard location:

Floating Action Button
Floating Action Button

Additionally, you can use FloatingActionButton.extended() to create an extended FAB:

Scaffold(
  floatingActionButton: FloatingActionButton(
    label: Text('Action'),
  ),
),
Default FAB
Default FAB

On the screen, we can see a default FAB.

Floatingactionbutton Flutter Rules And Principles

Let’s make sure we comprehend the guidelines and ideas to bear in mind when using FAB before we delve further and investigate the customization options. It’s crucial to follow these guidelines to keep your app in line with Material Design.

First action

In the UI, FAB is prominently displayed. Therefore, it should carry out the main function on the screen.

The selected action on the screen ought to be the most crucial and frequently used one. For instance, the main function of Twitter’s feed page is to compose tweets:

Twitter
Twitter

Minor operations like volume control, text copying, and drawer opening shouldn’t be done with FAB. Widgets that are hidden or discretely positioned in the UI can always be used to perform these actions.

Constructive Action

You must only use FAB for positive purposes; refrain from using it for negative ones. Constructive actions include things like adding something to your shopping cart, sharing a photo, and sending an email. Archiving, deleting, going to the previous page, and other destructive operations are examples.

Context is Key

The icon and action on the floating action button need to make sense together and be appropriate for the context of the screen.

Using the Twitter app as an example once more, the icon makes it obvious what the button does, which is to create a new tweet.

How could this be executed incorrectly? 

For instance, opening a profile page would obviously not be the most crucial action in the context of the screen if the button were set to open one.

Symbol and Label

If the FAB widget does anything other than display its icon by default, it somewhat defeats the purpose of using it.

This rule is reversed in the case of extended FAB, though. With an extended FAB, you can choose to show just the label or both the icon and label. In contrast, it’s forbidden to have an extended floating action button display nothing but the icon.

Customizing FloatingActionButton Flutter Widget

Let’s explore the customization possibilities available with FloatingActionButton Flutter widget now that you are aware of the key concepts and recommended procedures for developing a floating action button.

Colors

You can change the FloatingActionButton’s color. FAB’s background should be red as in this example:

FloatingActionButton(
	backgroundColor: Colors.red,
),
Red Icon
Red Icon

In the foregroundColor, a child’s color can be changed using the Color property; in this case, the icon’s color. Make it pink instead:

FloatingActionButton(
	foregroundColor: Colors.pink,
),
Foreground Color Pink
Foreground Color Pink

When you tap on the FAB, an animation begins in which a color spreads across the entire button area from the tapped position. This is called the splash color.

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

Constructor for the FloatingActionButton() Flutter Widget.

const FloatingActionButton(

    {Key? key,
    Widget? child,
    String? tooltip,
    Color? foregroundColor,
    Color? backgroundColor,
    Color? focusColor,
    Color? hoverColor,
    Color? splashColor,
    Object? heroTag: const _DefaultHeroTag(),
    double? elevation,
    double? focusElevation,
    double? hoverElevation,
    double? highlightElevation,
    double? disabledElevation,
    required VoidCallback? onPressed,
    MouseCursor? mouseCursor,
    bool mini: false,
    ShapeBorder? shape,
    Clip clipBehavior: Clip.none,
    FocusNode? focusNode,
    bool autofocus: false,
    MaterialTapTargetSize? materialTapTargetSize,
    bool isExtended: false}
) 

Below are listed the characteristics of this constructor:

1. child – Widget

Using this property, a widget can be added below it in the tree. You can put Icons or text to represent the purpose of this button.

FloatingActionButton( 
    child: Icon(Icons.add), //child widget inside this button
)

2. tooltip – String

With the help of this property, the user can see a brief badge message. 

FloatingActionButton( 
     tooltip: "Press to open link",
)

3. backgroundColor – Color

FloatingActionButton( 
    backgroundColor: Colors.redAccent,
)

Change the background color of the button by passing a color value to this property.
4. foregroundColor – Color

The icon and font color that are located beneath this button widget tree can be changed using this property.

FloatingActionButton( 
    foregroundColor: Colors.white,
)

5. elevation – double

Change the height of the elevation using this property; the more value you pass, the more shadow will be cast on the button.

FloatingActionButton( 
    elevation: 5.0
)

6. splashColor – Color

The button’s splash color can be modified using this property. You can tap the button to see the splash.

FloatingActionButton( 
     splashColor: Colors.blueAccent,
)

7. onPressed – VoidCallback

This property is used to give the button its desired function. The button will be pressed, which will cause the code block inside this function to run.

FloatingActionButton( 
    onPressed: (){
       //task to execute when this button is pressed
    },
)

The Floating action button’s position can be changed:

Using the Scaffold() widget’s floatingActionButtonLocation property, you can move the floating action button’s position on the screen.

Scaffold(
    floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat
)

Flutter App Example

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(
        floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
        floatingActionButton: FloatingActionButton( 
          backgroundColor: Colors.redAccent,
          foregroundColor: Colors.white,
          elevation: 5.0,
          tooltip: "Press to open link",
          child: Icon(Icons.add), //child widget inside this button
          splashColor: Colors.blueAccent,
          onPressed: (){
            print("Button is pressed.");
            //task to execute when this button is pressed
          },
        ),
        backgroundColor: Colors.blue[100], //background color of scaffold
        appBar: AppBar(
            title:Text("Floating Action Button"), //title of app
            backgroundColor: Colors.redAccent, //background color of app bar
        ),
  
        body: Center( //content body on scaffold
            child: Text("Floating Action Button Example"),
        )
     );
  }
}

Output:

Conclusion

After finishing this tutorial, you ought to know:

  1. The definition of FloatingActionButton Flutter widget and how to use it in a Flutter application
  2. When using FAB, remember the following guidelines and ideas:
  3. FAB customization techniques
  4. Adding a hero animation to FAB: How-to’s

With this knowledge, I hope you’ll be able to apply FAB to your Flutter applications and enhance their aesthetic appeal and usability. I appreciate you reading!

Refer to the following video for further details:

[Solved] Android sdkmanager Command Not Found Error in Flutter in 2023

0
android sdk tools

If you face an issue with the ” android sdkmanager command not found error” in flutter then you are in the right place. In this article, we will solve this error “sdkmanager command not found”. The error may look like this:

Android sdkmanager not found. Update to the latest Android SDK and ensure that the cmdline-tools are installed to resolve this.

This kind of error you may be found in Windows OS or MAC Os or Linux OS. It doesn’t matter from which OS version you face this issue. We will solve this issue for all OS.

This issue happens for the missing Android SDK Tools and Android SDK Command-line Tools on SDK manager. In that case, if you don’t have the Android SDK then you have to install it.

How to Solve Android sdkmanager Command Not Found Error in Flutter

Open SDK Manager in Android Studio:

At first open the SDK manager on Android Studio by following images:

android sdk manager

Click the three dots > SDK Manager.

Or if you already open the android studio project then:

sdk manager tools

Install Android SDK Tools and Android SDK Command-line Tools:

Now you have open the Android studio. Now uncheck the option named Hide Obsolete Packages. Then go to Tools > SDK Manager > SDK Tools tab. Now install Android SDK Tools and Android SDK Command-line Tools.

sdkmanager command not found

Now, it’s time to check the command “flutter doctor –android-licenses” in your terminal to check if the error still occur or not. If you still face the issue sdkmanager command not found flutter then go to this path: C:\Users\user_name\AppData\Local\Android\Sdk\cmdline-tools and check if it has latest file.

latest android sdk

If you have more than the latest file like latest-2 or like this then delete the latest file and rename latest-2 to latest. When android download multiple SDK or new SDK then it automatically creates the name latest-2 or like this. So if you want to delete the old file then you have to delete the old latest file and rename the current latest 2 to latest.

In this way, we can solve the android sdkmanager command not found error.

Read More:

How To Run Flutter App In Android Emulator?

[Solved] Flutter is not recognized as an internal and external command in 2023

0
flutter doctor

If you face an issue like flutter is not recognized as an internal and external command then this article is for you. In this article, we are going to show how to fix the flutter is not recognized as an internal or external command error in Windows OS. The error looks like the below on Powershell:

flutter : The term 'flutter' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

If you are not able to install flutter correctly in your OS then you may face this kind of error. We can solve this issue by following methods.

Flutter is not recognized as an internal and external command Solution

Methods1: Find out the Location of Flutter SDK

You have to locate the flutter SDK folder in your files. If you don’t have the flutter SDK on your local computer then you can download flutter SDK from the official website. Our SDK location at:  C:\Users\username\flutter. Now you have to edit the Environment path variable and add new path with “bin/”. Like this:  C:\Users\username\flutter\bin

flutter location

2. Go to My Computer Properties > Advance System Setting > Environment Variables

Go to this path and edit the path variable. Now add a new path of your Flutter SDK with “bin\” folder. Like this: C:\Users\rony\flutter\bin.

flutter bin path

Now save the changes and restart your terminal. Then open the command box and write below :

flutter doctor

Now you will see the output of the result:

Flutter is not recognized as an internal and external command

This is how you can solve the Flutter is not recognized as an internal and external command. If you have any questions regarding Flutter is not recognized as an internal and external command on Windows OS then you can comment below.

Read More:

How to Make a Flutter Quiz App

App Drawer Flutter in 2023 | Drawer Widget Made Easy!

0
App Drawer Flutter | Drawer Widget Made Easy!

The app drawer flutter widget is used to give users access to the various locations and features that your application offers. On the top of the scaffold, three horizontal, parallel lines serve as its representation. The flutter app’s link to various routes is navigated by a horizontal movement that starts at the edge of the scaffold.

You must import the material component package, which is “package: flutter/material.dart,” in order to use the app drawer.

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

The three sections of the navigating App Drawer Flutter are the header, body, and footer. The concept revolves around having a navigator with a few items as the drawer’s children that will be guided to various locations upon being tapped. Normally, ListView contains all of a Drawer widget’s children, and at first, only the DrawerHeader, which expands horizontally when clicked, is visible in the user interface.

Constructors

Syntax

Drawer({Key key, double elevation: 16.0, Widget child, String semanticLabel}) 

App Drawer Flutter Properties

  • semanticLabel: When the drawer is opened and closed, accessibility frameworks will announce screen transitions using the semantic label of the dialogue.
  • child: Those tree widgets are below this one.
  • key: Specifies how a widget in the tree can swap places with another widget.
  • runtimeType: A picture of the object’s runtime type.
  • elevation: The z-coordinate that should be used to position this drawer in relation to its parent.
  • hashCode: The object’s hash code.

Important Function

build(BuildContext context) → Widget: 

The widget-rendered portion of the user interface is specified by this method. When the Drawer widget is added to the tree in a specific BuildContext and when the Drawer widget’s dependencies change, this method is called.

Implementation

@override
Widget build(BuildContext context) {
  assert(debugCheckHasMaterialLocalizations(context));
  String? label = semanticLabel;
  switch (Theme.of(context).platform) {
    case TargetPlatform.iOS:
    case TargetPlatform.macOS:
      break;
    case TargetPlatform.android:
    case TargetPlatform.fuchsia:
    case TargetPlatform.linux:
    case TargetPlatform.windows:
      label = semanticLabel ?? MaterialLocalizations.of(context).drawerLabel;
  }
  return Semantics(
    scopesRoute: true,
    namesRoute: true,
    explicitChildNodes: true,
    label: label,
    child: ConstrainedBox(
      constraints: const BoxConstraints.expand(width: _kWidth),
      child: Material(
        elevation: elevation,
        child: child,
      ),
    ),
  );
}

Why App Drawer Flutter?

Drawers come in very handy for balancing multiple mobile application functionalities at once and are very simple to implement. Especially in the case of a complex application with many screens, creating a drawer greatly simplifies and manages to visit various locations in your app.

The process of performing tasks and switching between screens is simple. 

Steps to Create an App Drawer Flutter

There are 4 quick steps to setting up a drawer

1. Make a flutter project: 

Go to the location where you want to create your project by opening the terminal and navigating there. Your flutter project is created when you use the command “flutter create project_name”. 

 flutter create file_name 

2. Create a scaffold widget: 

Your stateless/stateful widget should return a scaffold widget inside the MyApp Class. Implementing the fundamental visual layout structure of the flutter app is made possible by a scaffold widget. 

 Scaffold(
drawer:  
);

3. Add an App Drawer Flutter inside the scaffold:  

Choose a Drawer with a ListView as its child for the scaffold’s drawer property, or you can add a Container with a ListView as its child. There are desired items in various ListViews that needed to be displayed inside the drawer.

drawer: Drawer(
//...
),);

4. Add a closing functionality: 

The app drawer flutter has a closing functionality. It is implemented using Navigator when the user wants to do so after tapping on a particular item. A Navigator State can be used for this. 

Navigator.of(context).pop();

Various Styles Of Navigation App Drawer Flutter

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

Three categories can be found in an app drawer:

  1. Modal Navigation App Drawer Flutter: These drawers only let the user interact with the drawer and prevent user interaction with the rest of the screen.
  2. Standard Navigation App Drawer Flutter: These enable simultaneous user interaction with the content of the screen and the drawer.
  3. Bottom Navigation App Drawer Flutter: These resemble modal navigation drawers, with the exception that they are oriented toward the screen’s lower third.

Example

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.lightBlue,
      ),
      home: const MyHomePage(title: 'Flutter Service'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Future<bool> _onPop() async {
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: _onPop,
        child: Scaffold(
          appBar: AppBar(
            centerTitle: true,
            title: Text(widget.title),
          ),
          body: const Center(
              child: Text(
            'Drawer Invisible.',
            style: TextStyle(fontSize: 20.0),
          )),
          drawer: Drawer(
            child: ListView(
              padding: const EdgeInsets.all(0),
              children: [
                const DrawerHeader(
                  decoration: BoxDecoration(
                    color: Colors.green,
                  ), //BoxDecoration
                  child: UserAccountsDrawerHeader(
                    decoration: BoxDecoration(color: Colors.green),
                    accountName: Text(
                      "Flutter Service",
                      style: TextStyle(fontSize: 18),
                    ),
                    accountEmail: Text("flutterserviceapp@gmail.com"),
                    currentAccountPictureSize: Size.square(50),
                    currentAccountPicture: CircleAvatar(
                      backgroundColor: Color.fromARGB(255, 165, 255, 137),
                      child: Text(
                        "F",
                        style: TextStyle(fontSize: 30.0, color: Colors.blue),
                      ), //Text
                    ), //circleAvatar
                  ), //UserAccountDrawerHeader
                ), //DrawerHeader
                ListTile(
                  leading: const Icon(Icons.person),
                  title: const Text(' Profile '),
                  onTap: () {
                    Navigator.pop(context);
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.book),
                  title: const Text(' Course '),
                  onTap: () {
                    Navigator.pop(context);
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.workspace_premium),
                  title: const Text(' Premium '),
                  onTap: () {
                    Navigator.pop(context);
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.video_label),
                  title: const Text(' Videos '),
                  onTap: () {
                    Navigator.pop(context);
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.edit),
                  title: const Text(' Edit '),
                  onTap: () {
                    Navigator.pop(context);
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.logout),
                  title: const Text('LogOut'),
                  onTap: () {
                    Navigator.pop(context);
                  },
                ),
              ],
            ),
          ), //Deawer      ),
        ));
  }
}

Output:

flutter drawer

Check the Following video for a detailed overview

[Solved] How to Solve the Flutter PackageManager has been Deprecated in 2023

0
Flutter PackageManager has been Deprecated

I have got an error: “Flutter PackageManager has been Deprecated“. After upgrading the compileSdkVersion 33 and targetSdkVersion 33, flutter get an error.

Flutter PackageManager has been Deprecated

Launching lib/main.dart on Redmi Note 9 Pro in debug mode...
/home/aman/snap/flutter/common/flutter/.pub-cache/hosted/pub.dartlang.org/permission_handler-8.3.0/android/src/main/java/com/baseflow/permissionhandler/ServiceManager.java:75: warning: [deprecation] queryIntentActivities(Intent,int) in PackageManager has been deprecated
            List<ResolveInfo> callAppsList = pm.queryIntentActivities(callIntent, 0);
                                               ^
error: warnings found and -Werror specified
/home/aman/snap/flutter/common/flutter/.pub-cache/hosted/pub.dartlang.org/permission_handler-8.3.0/android/src/main/java/com/baseflow/permissionhandler/PermissionUtils.java:317: warning: [deprecation] getPackageInfo(String,int) in PackageManager has been deprecated
                    .getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS);
                    ^
1 error
2 warnings

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':permission_handler:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1m 5s
Running Gradle task 'assembleDebug'...                             66.7s
Exception: Gradle task assembleDebug failed with exit code 1

This means that the permission handler is using a deprecated package. If you use the flutter 3.0 + and the latest version of compileSdkVersion 33 and targetSdkVersion 33, you may face this error. In this case, you have to change the permission handler in pubspec.yaml to any

Pubspec.yaml

permission_handler: any

This is how you can solve this Flutter PackageManager has been Deprecated issues.

Read More:

Flutter AppBar Example

Flutter Navigation and Routing Example | Best Practices in 2023

0
Flutter Navigation and Routing Example | Best Practices

We’ll discuss the declarative approach for Flutter navigation and routing example used in Flutter 2.0 and the imperative approach used in Flutter 1.0 in this tutorial.

A well-liked toolkit for creating cross-platform applications is Flutter. It works with all popular operating systems, including Android, iOS, and the web.

Whatever the application, navigation is crucial. It offers a consistent abstraction over the navigation APIs made available by different platforms. The imperative and declarative navigation APIs that Flutter offers are two different types.

Imperative navigation (Flutter 1.0)

The navigation method used in Flutter 1.0 was imperative.

Flutter navigation and routing are accomplished by popping widgets from the top of a stack of widgets that are stacked on top of one another.

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

Flutter Navigator class

All the navigation features in a Flutter app are provided by the Navigator class.

Navigator offers tools for changing the stack by pushing to it or popping from it. To navigate to a fresher page, use the Navigator.push method, and to return from the current page, use the Navigator.pop method.

A simple flutter navigation and routing example of pop and push is as follows: BuildContext and a PageBuilder are the first and second arguments, respectively, for the push method. This example makes use of MaterialPageRoute, which offers the transition animation and manages route changes:

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    title: 'My App',
    home: Main(),
  ));
}

class Main extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Main Route'),
      ),
      body: Center(
        child:RaisedButton(
          child: Text('Open route'),
          onPressed: () {
// pushing SecondRoute
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => SecondRoute()),
            );
          },
        ),
      ),
    );
  }
}

Only BuildContext is required by the pop method, which also modifies the current route.

class SecondRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Second Route"),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
// Removing SecondRoute
            Navigator.pop(context);
          },
          child: Text('Go back!'),
        ),
      ),
    );
  }
}

Additional methods offered by Navigator, such as *pushReplacement*, make arguments in a manner akin to push. Navigation back to the previous route will not be possible because it will replace the current one.

For instance, you might want to use *pushReplacement* to stop the user from returning to the login screen after a successful login.

Named routes

Named Routes let you change the path by using strings rather than providing component classes, allowing you to reuse code in the process.

The definition of a named route on MaterialApp is a map. You can use these routes from anywhere in the application.

Defining routes

The route is a map with string values for builders when it is passed to a MaterialApp’s routes property.

void main() {
  runApp(MaterialApp(
    title: 'My App',
    home: Main(),
// Routes defined here
    routes: {
      "second":(context)=>SecondRoute()
    },
  ));
}

Using named routes

To switch to a new route, pushNamed is used rather than push. Similarly, pushReplacement is replaced with *pushReplacementNamed*. All routes use the same pop technique.

class Main extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Main Route'),
      ),
      body: Center(
        child:RaisedButton(
          child: Text('Open route'),
          onPressed: () {
            Navigator.pushReplacementNamed(context, "second");
          },
        ),
      ),
    );
  }
}

Declarative navigation (Flutter 2.0)

Because Flutter 2.0 supports a declarative approach, the navigation has been improved. Due to the fact that pages change when states change, routing is now dependent on the state.

Improved web navigation support is another feature of Flutter 2.0.

The Flutter team publicly shared the following diagram to announce Flutter Navigation 2.0 and Router, which does a great job of illustrating the flow:

Flutter navigation and routing example- illustration
illustration

Flutter Navigator

Navigator shows the final page from a list of pages. By adding or deleting pages from the list’s end, you can alter the pages of the document.

The following example shows how to use the Navigator class with the updated Flutter Navigation and routing example by using page-based navigation.

This class controls the state of the page called _page. The setState call modifies this _page for navigation purposes:

class _App extends State {
// Creating state for pages
  List<Page> _pages=[];

The Navigator class receives the _page as a parameter. In accordance with the value of _page, Navigator will modify the current page.

When OS-based navigation is used, such as on Android by pressing the back button, onPopPage is called.

@override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Navigator(
        onPopPage: (route,result){
// check if route removed
          if(route.didPop(result)){
// remove the last page
            _pages.removeLast();
            return true;
          }
          return false;
        },
        pages: _pages,
      ),
    );
  }
}

By including a page in the initState lifecycle method, the first page can be set:

 @override
  void initState() {
    super.initState();
// setting intial page
    _pages=[_buildMain()];
  }

Using the MaterialPage widget, you can create a new material page. A child and a key are required by MaterialPage. The Navigator uses the key to differentiate between pages and detect page changes.

A new page is added to the _page state upon clicking the button. The widget is rebuilt when setState is called, and the navigator automatically takes care of the page change.

// This function creates a Page using MaterialPage  
Page _buildMain(){
    return MaterialPage(child: Scaffold(
      body: Center(
        child: ElevatedButton(
          child: Text("click"),
          onPressed: (){
// When clicked add a new Page to _page list
            _pages.add(_buildSecondPage());
// call setState to trigger rebuild for Widget
            setState(() {
// create a copy of array
              _pages=_pages.toList();
            });
          },
        ),
      ),
// This helps Navigator to distigush between different pages
    ),key: ValueKey("home"));
  }

Similar to _buildMain, this page is created, but instead of adding a new page, it removes an existing one and initiates a rebuild.

// This function perform same task as _buildMain  
Page _buildSecondPage(){
    return MaterialPage(child: Scaffold(
      body: Center(
        child: ElevatedButton(
          child: Text("back"),
          onPressed: (){
// This will take back to main
// remove the last page
            _pages.removeLast();
// call setState to trigger a rebuild
            setState(() {
// creating a copy of list
              _pages=_pages.toList();
            });
          },
        ),
      ),
    ),key: ValueKey("second"));
  }

The _pages list is only one of the states that can be used for navigation; other states are also available. Here’s one more flutter navigation and routing example:

class _App extends State {
  String _selected="main";

  Page _buildMain(){
    return MaterialPage(child: Scaffold(
      appBar: AppBar(),
      body: Center(
        child: ElevatedButton(
          child: Text("click"),
          onPressed: (){
            setState(() {
// add a new page
              _selected="second";
            });
          },
        ),
      ),
    ),key: ValueKey("home"));
  }

  Page _buildSecondPage(){
    return MaterialPage(child: Scaffold(
      appBar: AppBar(),
      body: Center(
        child: ElevatedButton(
          child: Text("back"),
          onPressed: (){
            setState(() {
// change back state to main
             _selected="main";
            });
          },
        ),
      ),
    ),key: ValueKey("second"));
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Navigator(
        onPopPage: (route,result){
          if(route.didPop(result)){
            _selected="main";
            return true;
          }
          return false;
        },
        pages: [
           _buildMain(),
// only show select if state has second selected
          if (_selected=="second") _buildSecondPage()
        ],
      ),
    );
  }
}

Using RouterDelegate

A fundamental widget used by a Router is RouterDelegate. It reacts to the engine’s route push and route pop intentions. In order to have more control over navigation, new navigation allows for the creation of RouterDelegate.

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

By adding PopNavigatorRouterDelegateMixin and ChangeNotifier mixins to the RouterDelegateAppRouteState> class, a RouterDelegate is produced.

The current path is followed by _selected. This is comparable to the state that was used in the first flutter navigation and routing example.

class AppRouter extends RouterDelegate<AppRouteState> with PopNavigatorRouterDelegateMixin,ChangeNotifier {
  String _selected="main";

The router uses this to update the URL in the address bar and to obtain the most recent router status.

// get correct state of router  
@override
  AppRouteState get currentConfiguration => AppRouteState(_selected);

In order to support older navigation, the navigation key is used.

// This for older navigation support. 
 final _navigation= GlobalKey<NavigatorState>();
  @override
  GlobalKey<NavigatorState> get navigatorKey => _navigation;

To start a rebuild, notifyListeners is used instead of setState. To alter the route, _selected is changed.

  Page _buildMain(){
    return MaterialPage(child: Scaffold(
      appBar: AppBar(),
      body: Center(
        child: ElevatedButton(
          child: Text("click"),
          onPressed: (){
            _selected="second";
// notify route changes
           notifyListeners();
          },
        ),
      ),
    ),key: ValueKey("home"));
  }

_buildMain and this are comparable

  Page _buildSecondPage(){
    return MaterialPage(child: Scaffold(
      appBar: AppBar(),
      body: Center(
        child: ElevatedButton(
          child: Text("back"),
          onPressed: (){
              _selected="main";
// notify route changes
          notifyListeners();
          },
        ),
      ),
    ),key: ValueKey("second"));
  }

In order to lay out other pages, the build function returns the Navigator widget. Building off of the previous function, this function is comparable. Rebuild is started using notifyListeners rather than setState

 @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Navigator(
        key: _navigation,
        onPopPage: (route,result){
          if(!route.didPop(result)){
            return false;
          }
          _selected="main";
// notify route changes
          notifyListeners();
          return true;

        },
        pages: [
          _buildMain(),
// if Route is second show SecondPage
          if (_selected=="second") _buildSecondPage()
        ],
      ),
    );
  }

To alter the route, this function makes use of data passed by the router. When the engine passes the route push or pop intent, this function is called to modify the route. A different class, which we’ll discuss later, parses the data passed here.

  @override
  Future<void> setNewRoutePath(configuration) async {
// update page based on 
    _selected=configuration.selected;
  }
}

RouteInformationParser

The configuration is received by setNewRoutePath from the router. RouteInformationParser examines this configuration for syntax.

A class should extend RouteInformationParser to represent the parsing state passed by the OS, engine, etc. The return value from currentConfiguration is transformed into RouteInformation by restoreRouteInformation.

The router state is provided to setNewRoutePath by parseRouteInformation as input.

class AppRouteInformationParser extends RouteInformationParser<AppRouteState>{
  // This converts route state to route information.
  @override
  RouteInformation restoreRouteInformation(configuration) {
    if(configuration.selected=="main") {
      return RouteInformation(location:"/main");
    } else {
      return RouteInformation(location: "/second");
    }

  }

// This converts route info to router state
  @override
  Future<AppRouteState> parseRouteInformation(RouteInformation routeInformation)async{
    var url=Uri.parse(routeInformation.location);
    print(url.path);
    if (url.path == "/") return AppRouteState("main");
    return AppRouteState(url.path.replaceAll("/", ""));
  }

}

Putting it all together

Currently, MaterialApp has a constructor with a new name that implements a router that accepts the arguments Delegate and InformationParser.

class _App extends State {
  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(routeInformationParser: AppRouteInformationParser(), routerDelegate: AppRouter());
  }
}

Conclusion

We showed you how to implement navigation in a Flutter app using both the imperative approach used in Flutter 1.0 and the new declarative navigation introduced with Flutter 2.0 in this tutorial on Flutter navigation and routing example.

Both types of navigation may be appropriate depending on the specifics of your Flutter project, but a silver bullet is not one of them. Always go with the strategy that best meets your requirements, even if that necessitates combining the two.

I suggest taking a look at the Fluro and Voyager packages to get acquainted with navigation in Flutter.