Multiline TextField in Flutter

The TextField widget in Flutter offers a practical method of obtaining user input. It accepts single-line input by default.

However, you can use the maxLines property to create a multiline TextField in situations where you need to collect many lines of information.

We will look at several elements of generating and using multiline TextFields in Flutter in this tutorial.

Creating a Multiline TextField

To create a multiline TextField, you need to set the maxLines property to a value greater than 1. This tells Flutter to allow for multiple lines of text input. Here’s an example of how you can create a multiline TextField:

TextField(
  maxLines: null, // Set to null or any positive integer
  decoration: InputDecoration(
    hintText: 'Enter your text',
    labelText: 'Multiline TextField',
  ),
)

In the code snippet above, we set maxLines to null, which allows the TextField to dynamically adjust its height to accommodate multiple lines of text. Alternatively, you can specify a positive integer to limit the number of visible lines.

Controlling the Number of Lines

If you want to limit the number of visible lines in the multiline TextField, you can set a specific value for maxLines. For example, if you want to limit the TextField to three visible lines, you can set maxLines to 3. Here’s an example:

TextField(
  maxLines: 4, // Set to a positive integer
  decoration: InputDecoration(
    hintText: 'Enter your Main Text',
    labelText: 'Limited Lines TextField',
  ),
)

By specifying a value for maxLines, the TextField will display a scrollable text area when the content exceeds the specified number of lines.

Handling Line Breaks and New Lines

By default, the multiline TextField allows users to insert line breaks and create new lines by pressing the Enter or Return key on the keyboard. Flutter treats these line breaks as regular text and includes them in the value of the TextField.

To control the behavior of line breaks and new lines, you can use the textInputAction and keyboardType properties.

For example, you can configure the TextField to dismiss the keyboard instead of inserting a line break:

TextField(
  maxLines: null,
  textInputAction: TextInputAction.done,
  keyboardType: TextInputType.multiline,
  decoration: InputDecoration(
    hintText: 'Enter your text',
    labelText: 'Multiline TextField',
  ),
)

In the example above, we set textInputAction to TextInputAction.done, which displays a “Done” button on the keyboard. Tapping this button will dismiss the keyboard instead of inserting a line break.

Conclusion

Flutter’s TextField widget has strong user input-capture capabilities, including support for multiline text input. You can construct multiline TextFields to collect longer text entries by setting the maxLines attribute to accommodate multiple lines.

In this post, we looked at how to build multiline TextFields, manage line breaks and new lines, and decide how many lines are visible. By utilising these functionalities, you may create forms and input fields for your Flutter applications that can handle different text input requirements.

When choosing the best configuration for multiline TextFields, keep in mind the context and goal of your application. Test out several options to make sure the experience is simple and easy to use.

Related Posts

Clearing a TextField in Flutter

The DropdownButton Widget in Flutter

Card Widget in Flutter

TextField Widget in Flutter

TextButton Widget in Flutter

Creating a Snackbar in Flutter

Clearing a TextField in Flutter

A TextField widget is frequently used in Flutter to collect user input. You might occasionally need to provide consumers the option to clear the text field and start over.

This article will examine various methods for clearing a TextField in Flutter.

There are some method of clear textfield value.

Method 1: Using TextEditingController

Using the TextEditingController class is one approach to delete all the contents of a TextField. This class enables programmatic manipulation of the TextField’s text value.

Here’s an Example of how a TextEditingController may be used to clear a TextField:

Create a TextEditingController instance:

TextEditingController _controller = TextEditingController();

Assign the controller to the TextField

TextField(
  controller: _controller,
  // Other properties...
)

To clear the text field, call the clear() method on the controller:

_controller.clear();

Method 2: Setting the TextField Value to an Empty String

Setting a TextField’s value to an empty string is another way to clear it. A controller is not required for this procedure. How to do it is as follows:

Assign a value to the TextField using the controller or initialValue property:

TextField(
  controller: _controller,
  // OR
  initialValue: 'Initial value',
  // Other properties...
)

To clear the text field, update the value to an empty string:

_controller.text = '';
// OR
_controller = TextEditingController(text: '');

Method 3: Using a GlobalKey

Alternatively, you can use a GlobalKey to clear a TextField. This approach requires you to provide a GlobalKey to the TextField widget. Here’s how you can do it:

Create a GlobalKey instance:

GlobalKey<FormFieldState> _formKey = GlobalKey<FormFieldState>();

Assign the key to the TextField:

TextField(
  key: _formKey,
  // Other properties...
)

To clear the text field, call the reset() method on the key’s current state:

_formKey.currentState?.reset();

Conclusion

In Flutter, a TextField can be cleared in a variety of ways. To clear the text field’s state, use a GlobalKey, a TextEditingController, or set the value to an empty string. Pick the approach that best satisfies your requirements, then incorporate it into your Flutter application.

This post looked at three methods for clearing a TextField in Flutter. You can quickly incorporate text field clearing capability in your Flutter apps by following the step-by-step instructions. By giving people a simple mechanism to restart their input, you can improve the user experience.

When determining which approach to adopt, don’t forget to take the context and requirements of your particular use case into account. Utilise Flutter’s versatility to construct logical and user-friendly applications by experimenting with various methods.

Related Posts

The DropdownButton Widget in Flutter

Card Widget in Flutter

TextField Widget in Flutter

TextButton Widget in Flutter

Creating a Snackbar in Flutter

StartActivityForResult in Flutter

The DropdownButton Widget in Flutter

The DropdownButton widget in Flutter provides a convenient and interactive way to select an item from a list of options.

It displays a dropdown menu with selectable items and allows users to make a single selection. In this article, we will explore the key features and usage of the DropdownButton widget in Flutter.

Basic Usage

Make sure Flutter is installed before starting a new Flutter project and using the DropdownButton widget. Afterward, import the DropdownButton widget from the material.dart package. Here is an illustration of how to import the package:

import 'package:flutter/material.dart';

The widget in your widget tree called DropdownButton. Here is a simple Example:

String _selectedItem = 'Option 1';

DropdownButton<String>(
  value: _selectedItem,
  onChanged: (String? newValue) {
    setState(() {
      _selectedItem = newValue!;
    });
  },
  items: <String>['Option 1', 'Option 2', 'Option 3', 'Option 4']
      .map<DropdownMenuItem<String>>((String value) {
    return DropdownMenuItem<String>(
      value: value,
      child: Text(value),
    );
  }).toList(),
)

Customization Options

The DropdownButton widget offers several properties that allow you to customize its appearance and behavior. Let’s explore some of the commonly used properties:

value
The value property represents the currently selected item. It should be set to a value from the provided list of items. You can update the selected item by modifying this property in response to user interactions.

onChanged
The onChanged property is a callback function that is triggered when the user selects a new item from the dropdown menu. You can perform actions or update the UI based on the user’s selection inside this callback.

items
The items property accepts a list of DropdownMenuItem widgets, which define the options available in the dropdown menu. Each DropdownMenuItem contains a value and a child widget. The value represents the value of the item, and the child widget represents the visual representation of the item in the dropdown menu.

hint
The hint property allows you to provide a hint or placeholder text that is displayed when no item is selected. It is typically used to provide context or instructions to the user.

disabledHint
The disabledHint property specifies a hint that is displayed when the dropdown button is disabled. It is useful when you want to show a different hint text when the dropdown is disabled.

Additional Customization

The DropdownButton widget provides more customization options such as icon, iconDisabledColor, iconEnabledColor, isDense, and more. These properties allow you to customize the appearance and behavior of the dropdown button to fit your specific design requirements.

Here are the simple example of Dropdown Widget in Flutter Application. You can implement the basic things of that.

Example: Creating a Simple Dropdown Menu

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class DropdownDisplay extends StatefulWidget {
  @override
  DropdownDisplayState createState() => DropdownDisplayState();
}

class DropdownDisplayState extends State<DropdownDisplay> {
  String _selectedLanguage = 'Java';
  List<String> lst_LanguageName = [
    'Java',
    'Python',
    'JavaScript',
    'C++',
    'Ruby'
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Simple Dropdown Demo'),
          automaticallyImplyLeading: false,
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'Select your favorite programming language:',
                style: TextStyle(fontSize: 15.0),
              ),
              SizedBox(height: 30.0),
              DropdownButton<String>(
                value: _selectedLanguage,
                onChanged: (String? newValue) {
                  setState(() {
                    _selectedLanguage = newValue!;
                  });
                },
                items: lst_LanguageName
                    .map<DropdownMenuItem<String>>((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(value),
                  );
                }).toList(),
              ),
              SizedBox(height: 30.0),
              Text(
                'Selected Language:-   $_selectedLanguage',
                style: TextStyle(fontSize: 15.0),
              ),
            ],
          ),
        ));
  }
}

Conclusion

The DropdownButton widget in Flutter is a powerful tool for providing user-friendly selection options in your applications. With its customizable properties and intuitive interface, you can create dropdown menus that enhance the user experience.

Related Posts

Card Widget in Flutter

TextField Widget in Flutter

TextButton Widget in Flutter

Creating a Snackbar in Flutter

StartActivityForResult in Flutter

Custom Tabbar in Flutter

Card Widget in Flutter

The Flutter Card widget is a flexible and popular container that offers a straightforward method of displaying information in a beautiful way.

The Card widget is an effective tool for building gorgeous UIs because to its built-in Material Design and adjustable characteristics.

We will examine the main characteristics and application of the Card widget in Flutter in this article.

Basic Usage

Make sure Flutter is set up and that you have a fresh Flutter project created before you begin utilising the Card widget.

Next, import the ‘Card widget’ package from the material.dart package. Here is an illustration of how to import the package:

import 'package:flutter/material.dart';

Next, you can use the Card widget in your widget tree. Here’s a basic example:

Card(
  child: ListTile(
    leading: Icon(Icons.person),
    title: Text('John Doe'),
    subtitle: Text('Software Developer'),
    trailing: Icon(Icons.more_vert),
  ),
)

In the code snippet above, we created a Card widget with a child ListTile.

The ListTile provides a convenient way to structure the content within the Card. In this example, we included an icon, title, subtitle, and a trailing icon within the ListTile.

Customization Options

The Card widget offers several properties that allow you to customize its appearance and behavior. Let’s explore some of the commonly used properties:

elevation
The elevation property determines the depth of the Card by adding a shadow effect. Higher elevation values create a more pronounced shadow. You can adjust the elevation according to your design needs.

shape
The shape property allows you to define the shape of the Card. By default, the Card has a rectangular shape, but you can specify other shapes such as rounded rectangles or circles using BorderRadius or CircleBorder.

color
The color property enables you to set the background color of the Card. You can choose a color from the available material design colors or use a custom color that suits your design.

margin and padding
The margin property controls the space around the Card, while the padding property defines the space between the Card’s content and its edges. You can adjust these properties to achieve the desired spacing and alignment in your layout.

Complex Content
The Card widget can contain complex content beyond a simple ListTile. You can add various other widgets, such as images, buttons, or custom layouts, to create rich and interactive cards. The Card serves as a container that can hold any widget you want to display.

Conclusion

Flutter’s Card widget is a flexible container that provides a quick method to convey information in a visually appealing way. You can design aesthetically pleasing UIs and present complex content using a card structure thanks to its adjustable characteristics.

In this post, we looked at the Card widget’s fundamental use and talked about some of its often used attributes. To further enhance and customise your Card designs in Flutter, there are numerous other choices accessible. Create stunning and useful user interfaces by experimenting with various widget attributes and combining the Card widget with other Flutter elements.

Related Posts

TextField Widget in Flutter

TextButton Widget in Flutter

Creating a Snackbar in Flutter

StartActivityForResult in Flutter

Custom Tabbar in Flutter

Bottom Tab Bar in Flutter

TextField Widget in Flutter

Users can enter text using the TextField widget, which is a core input widget in Flutter.

It is appropriate for a variety of use scenarios because to the flexible collection of characteristics and customization options it offers.

We will examine the main characteristics and attributes of the TextField widget in Flutter in this tutorial.

You must integrate the TextField widget into your Flutter project before you can use it.

Make sure the essential dependencies are installed first. Import the content after that.

Understanding the Properties of TextField in Flutter

1. controller

The controller property of the TextField widget allows you to associate a TextEditingController with the text field. This controller gives you access to the entered text, as well as the ability to modify it programmatically.

2. decoration

The decoration property is used to customize the visual appearance of the text field. It accepts an instance of InputDecoration that allows you to set properties such as the label text, hint text, prefix or suffix icons, border, and more.

3. onChanged

The onChanged callback is triggered whenever the user modifies the text field. It provides the current value of the text field as an argument, allowing you to perform actions based on the user’s input, such as updating UI elements or making API calls.

4. maxLines

The maxLines property specifies the maximum number of lines that the text field can display. Setting it to null allows the user to enter multiple lines of text, creating a multi-line text field.

5. keyboardType

The keyboardType property determines the type of keyboard that is displayed to the user when they focus on the text field. There are various options available, including numeric keyboards, email keyboards, URL keyboards, and more.

6. textCapitalization

The textCapitalization property defines how the entered text should be capitalized. It offers options such as TextCapitalization.none (no capitalization), TextCapitalization.words (capitalize the first letter of each word), TextCapitalization.sentences (capitalize the first letter of each sentence), and TextCapitalization.characters (capitalize every character).

7. style

The style property allows you to specify the text style for the entered text. You can customize properties such as the font size, font weight, color, and more.

8. autofocus

The autofocus property determines whether the text field should automatically receive focus when the widget is first displayed. Setting it to true ensures that the text field is ready for input without requiring an additional tap.

9. obscureText

The obscureText property is used for password fields or any other scenario where you want to hide the entered text. When set to true, the entered text is masked, usually with asterisks or dots.

10. textAlign

The textAlign property defines the alignment of the entered text within the text field. It accepts values such as TextAlign.left, TextAlign.right, TextAlign.center, and TextAlign.justify.

11. maxLength

The maxLength property specifies the maximum number of characters allowed in the text field. You can use this property to enforce a character limit for user input.

12. buildCounter

The buildCounter property allows you to customize the display of the character counter, which indicates the current length of the entered text and the maximum allowed length. You can provide a custom function that returns a widget to define the counter’s appearance.

TextField widget is part of the dart package. Here is an illustration of how to import the package:

import 'package:flutter/material.dart';

Next, you can use the TextField widget in your widget tree. Here’s a basic example:

TextField(
  decoration: InputDecoration(
    labelText: 'Enter your Number',
  ),
)

We constructed a TextField with a straightforward decoration that contains a label text in the aforementioned code snippet.

The user is given a visual signal regarding the text field’s purpose thanks to this.

Controller and Retrieving Input

A TextEditingController can be used to retrieve the user’s input that was entered into the TextField.

You can read the text that has been typed or programmatically alter it using this controller. Here’s an illustration of how a controller is used:

TextEditingController _textEditingController = TextEditingController();

TextField(
  controller: _textEditingController,
  decoration: InputDecoration(
    labelText: 'Enter your Number',
  ),
)

We built a TextEditingController with the number _textEditingController and applied it to the TextField’s controller property in the code above.

By using _textEditingController.text, you may get at the text that was typed.

Handling User Input

The onChanged callback, which is offered by the TextField widget, is triggered anytime the user makes changes to the text field.

You can take actions based on the user’s input with this callback. Here’s an illustration:

TextField(
  onChanged: (value) {
    print('User input: $value');
  },
  decoration: InputDecoration(
    labelText: 'Enter your name',
  ),
)

The onChanged callback, which prints the entered text anytime the user edits the text field, is included in the code excerpt above.

You can use your own logic to update UI components or access APIs in place of the print statement.

Related Posts

TextButton Widget in Flutter

Creating a Snackbar in Flutter

StartActivityForResult in Flutter

Custom Tabbar in Flutter

Bottom Tab Bar in Flutter

Tabbar with image in flutter

TextButton Widget in Flutter

A TextButton widget is nothing more than a text label visible on a Material widget with no elevation.

It has no apparent borders by default and fills with a backdrop colour when touched.

FlatButton is no longer supported and should not be used in new projects; TextButton is the successor for this once-famous widget.

Note: TextButton requires Flutter 1.22.0 or newer to function properly without displaying obtrusive errors or warnings. The examples in this post have recently been modified to function properly with Flutter 3.3.10+.

TextButton Syntax

TextButton({
  Key? key, 
  required VoidCallback? onPressed, 
  VoidCallback? onLongPress, 
  ValueChanged<bool>? onHover, 
  ValueChanged<bool>? onFocusChange, 
  ButtonStyle? style, 
  FocusNode? focusNode, 
  bool autofocus = false, 
  Clip clipBehavior = Clip.none, 
  MaterialStatesController? statesController, 
  required Widget child
})

Simple Textbutton Implementation Example :

TextButton(
    onPressed: () {},
    child: const Text('Normal Button'),
),

Textbutton with Icon Example

TextButton.icon(
    icon: const Icon(Icons.browse_gallery),
    label: const Text('Go To Gallery'),
    onPressed: () {},
)

Disable a TextButton Example

A non-responsive button is one that has been disabled. Simply set onPressed and onLongPress to null (onLongPress is null by default) to make a text button inactive.

Column(
        children: [
          const TextButton(
            onPressed: null, // For Disable Button you can set null
            child: Text('Check Disabled Button'),
          ),
          TextButton(
            onPressed: () {}, // For Enable Button 
            child: const Text('Check Enabled Button'),
          ),
          TextButton.icon(
              onPressed: null, // For Disable Button you can set null
              icon: const Icon(Icons.cancel),
              label: const Text('Check Disabled Icon Button')),
          TextButton.icon(
              onPressed: () {}, // For Enable Button 
              icon: const Icon(Icons.pause),
              label: const Text('Check Enabled Icon Button'))
        ],
),

Style a TextButton Syntax

styleFrom({
  Color? foregroundColor, 
  Color? backgroundColor, 
  Color? disabledForegroundColor, 
  Color? disabledBackgroundColor, 
  Color? shadowColor, 
  Color? surfaceTintColor, 
  double? elevation, 
  TextStyle? textStyle, 
  EdgeInsetsGeometry? padding, 
  Size? minimumSize, 
  Size? fixedSize, 
  Size? maximumSize, 
  BorderSide? side, 
  OutlinedBorder? shape, 
  MouseCursor? enabledMouseCursor, 
  MouseCursor? disabledMouseCursor, 
  VisualDensity? visualDensity, 
  MaterialTapTargetSize? tapTargetSize, 
  Duration? animationDuration, 
  bool? enableFeedback, 
  AlignmentGeometry? alignment, 
  InteractiveInkFeatureFactory? splashFactory, 
  Color? primary, 
  Color? onSurface
})

In the following example, an italic font button with an amber backdrop is created:

TextButton(
            onPressed: () {},
            style: TextButton.styleFrom(
                foregroundColor: Colors.green,
                backgroundColor: Colors.blue,
                textStyle:
                    const TextStyle(fontSize: 24, fontStyle: FontStyle.bold)),
            child: const Text(
              'Main Button',
            ),
),

By utilising the fixedSize option in the following manner, you can size a TextButton precisely as you desire:

TextButton(
        style: TextButton.styleFrom(
            fixedSize: const Size(250, 100),
            backgroundColor: Colors.blue,
            foregroundColor: Colors.black,
            textStyle: const TextStyle(fontSize: 25)),
        onPressed: () {},
        child: const Text('Click'),
)

By changing its properties, you can alter the TextButton’s appearance. You may add an icon or alter the text style or colour of the button, for instance. Feel free to play around with various parameters to get the desired appearance and behaviour.

Related Posts

Creating a Snackbar in Flutter

StartActivityForResult in Flutter

Custom Tabbar in Flutter

Bottom Tab Bar in Flutter

Tabbar with image in flutter

Progress Bars Example in Flutter

Creating a Snackbar in Flutter

Flutter’s Snackbar widget lets you show a pop-up notification that users may close from within your application.

It is employed to display to users whether specific activities occur in our programmes.

For instance, if the user login process fails for some reason, we can use the snackbar to tell the user to try again. It appears on the screen and has additional functions like the ability to reverse a previously executed action.

Snackbar briefly displays the educational message before it automatically disappears at the end of the allotted time. The ideal onscreen duration for a snackbar is 5 to 10 seconds. It is offered in the flutter libraries’ material package.

You must import “package:flutter/material.dart” to use a snackbar. Syntax of the snackbar is given below.

SnackBar({Key key, 
@required Widget content, 
Color backgroundColor, 
double elevation, 
EdgeInsetsGeometry margin, 
EdgeInsetsGeometry padding, 
double width, 
ShapeBorder shape, 
SnackBarBehavior behavior, 
SnackBarAction action, 
Duration duration: _snackBarDisplayDuration, 
Animation<double> animation, 
VoidCallback onVisible})

Here are the properties descriptions

  • action: Action to perform based on snackbar.
  • animation: Entry and the exit animation of snackbar.
  • backgroundcolor: Snackbar background color
  • behavior: Behavior and location of snackbar.
  • content: Content of snackbar.
  • duration: The amount of time snackbar should be displayed.
  • elevation: Elevates the snackbar by increasing shadow.
  • margin: Space around snackbar.
  • onVisible: Called the first time that the snackbar is visible within a scaffold.
  • padding: space around content inside snackbar.
  • shape: Shape of snackbar.
  • width: Width of snackbar.

Here is the basic example of the snackbar given below.

class SnackbarDisplay extends StatefulWidget {
  @override
  SnackbarDisplayState createState() => SnackbarDisplayState();
}

class SnackbarDisplayState extends State<SnackbarDisplay> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Snackbar Demo'),
          automaticallyImplyLeading: false,
        ),
        body: Center(
            child: Column(
          children: [
            Container(
              padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
              margin: EdgeInsets.fromLTRB(5, 5, 5, 0),
              child: TextButton(
                style: TextButton.styleFrom(
                  shadowColor: Colors.black,
                  textStyle: TextStyle(fontSize: 20),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  backgroundColor: Colors.black45,
                ),
                onPressed: () async {
                  final snackBar = SnackBar(
                    content: Text('This is a snackbar'),
                  );
                  ScaffoldMessenger.of(context).showSnackBar(snackBar);
                },
                child: Text(
                  "Show Snackbar",
                  style: TextStyle(color: Colors.white, fontSize: 12),
                ),
              ),
            ),
          ],
        )));
  }
}

The snackbar is also customizable. Similar to changing a colour or adding a button, you may alter the snackbar’s duration. In order for you to customise it to meet your needs.

final snackBar = SnackBar(
  content: Text('This is a customize snackbar'),
  backgroundColor: Colors.blue,
  duration: Duration(seconds: 3),
  action: SnackBarAction(
    label: 'Dismiss',
    onPressed: () {
      // Perform action when the action button is pressed
    },
  ),
);

That code can be added to the onPressed method.

Your Flutter application’s snackbar has been successfully established. Snackbars are a fantastic method to give users momentary feedback or notifications. To improve the user experience, feel free to test out various customizations.

Recall that snackbars are merely one of the numerous UI elements offered by Flutter. For Flutter to help you create incredible applications, keep exploring and experimenting!

Related Posts

StartActivityForResult in Flutter

Custom Tabbar in Flutter

Bottom Tab Bar in Flutter

Tabbar with image in flutter

Simple Tabbar in Flutter

Progress Bars Example in Flutter

StartActivityForResult in Flutter

The startActivityForResult function, which enables you to launch a new activity and receive a result back in the original activity, is one of the helpful tools in Android programming.

Although there isn’t a direct Flutter equivalent to this technique, we can accomplish a comparable feature by utilising callbacks and navigation in Flutter. We’ll look at how to use Flutter to construct a similar pattern in this article.

We can using callback functionality in Flutter applications.

Create one file StartActivityResultDetails.dart. Put below code of that.

class StartActivityResultDetails extends StatefulWidget {
  @override
  StartActivityDisplayState createState() => StartActivityDisplayState();
}

class StartActivityDisplayState extends State<StartActivityResultDetails> {
  Map str_Callback = {"Title": "Welcome India"};

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('First Page'),
          automaticallyImplyLeading: false,
        ),
        body: Center(
            child: Column(
          children: [
            Container(
              padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
              margin: EdgeInsets.fromLTRB(5, 5, 5, 0),
              child: TextButton(
                style: TextButton.styleFrom(
                  shadowColor: Colors.black,
                  textStyle: TextStyle(fontSize: 20),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  backgroundColor: Colors.black45,
                ),
                onPressed: () async {
                  Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => CallBackResultDetails()))
                      .then((detailsCallback) {
                    setState(() {
                      str_Callback = detailsCallback;
                    });
                  });
                },
                child: Text(
                  "Click Here For Next Screen",
                  style: TextStyle(color: Colors.white, fontSize: 12),
                ),
              ),
            ),
            Container(
              padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
              margin: EdgeInsets.fromLTRB(5, 5, 5, 0),
              child: Text(
                "Result of Next Screen Display Here -- " +
                    str_Callback['Title'],
                style: TextStyle(color: Colors.black, fontSize: 12),
              ),
            ),
          ],
        )));
  }
}

Now Create second part of that code.

Create CallBackResultDetails.dart File for callback function.

class CallBackResultDetails extends StatefulWidget {
  @override
  CallBackDisplayState createState() => CallBackDisplayState();
}

class CallBackDisplayState extends State<CallBackResultDetails> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('CallBack Functions'),
          automaticallyImplyLeading: false,
        ),
        body: Center(
            child: Column(
          children: [
            Container(
              padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
              margin: EdgeInsets.fromLTRB(5, 5, 5, 0),
              child: TextButton(
                style: TextButton.styleFrom(
                  shadowColor: Colors.black,
                  textStyle: TextStyle(fontSize: 20),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                  backgroundColor: Colors.black45,
                ),
                onPressed: () async {
                  Navigator.of(context).pop({"Title": "Great Nice from you."}); // When you want to send JSON Then this will be help
                  // Navigator.of(context).pop(true); // When you want to send Boolean Then this will be help
                },
                child: Text(
                  "Click Here For Next Screen",
                  style: TextStyle(color: Colors.white, fontSize: 12),
                ),
              ),
            ),
          ],
        )));
  }
}

If you want to send JSON part then this will be help

Navigator.of(context).pop({"Title": "Great Nice from you."}); // When you want to send JSON Then this will be help

If you want to send boolean value then this will be help.

Navigator.of(context).pop(true); // When you want to send Boolean Then this will be help

Despite the lack of a direct equivalent to startActivityForResult in Flutter, we can nevertheless achieve a similar level of functionality by combining callbacks and navigation.

By following the instructions in this article, you may use Flutter to move to a different screen and have the result returned to the original widget.

Your Flutter applications can communicate between screens thanks to this pattern’s increased flexibility.

With this method, you can easily manage the results and construct your own startActivityForResult in Flutter. Coding is fun!

Related Posts

Custom Tabbar in Flutter

Bottom Tab Bar in Flutter

Tabbar with image in flutter

Simple Tabbar in Flutter

Progress Bars Example in Flutter

Custom Tab Bar in Flutter

This post will discuss custom tab bars and show you how to make tab bars inside of tab bars. Making a tab bar is extremely simple; all you need to do is return the default controller, specify the length, and build the tab bar. You can also refer this article of Work with Tabs.

While Flutter comes with a default TabBar widget, there may be times when you want to design or programme an own tab bar. This tutorial will show you how to design a unique tab bar in Flutter.

However, in this post, we’ll look at how to make a tab bar, customise it to suit your needs, and add a subtab bar to it.

The tabbar is one of the most popular widgets in the flutter app, and most businesses favour using it in their software.

Open the lib/main.dart file and replace its contents with the following code:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Custom Tab Bar',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MainCustomTab(),
    );
  }
}

In this code, we’ve created a basic MyApp widget that sets up the Flutter app’s structure. The MainCustomTab widget is set as the home screen.

Implementing the Custom Tab Bar

Create a new file called main_custom_tab.dart in the lib directory and add the following code:

import 'package:flutter/material.dart';

class MainCustomTab extends StatefulWidget {
  @override
  State<MainCustomTab> createState() => _MyCustomState();
}

class _MyCustomState extends State<MainCustomTab> {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: Text("Custom Tab Bar"),
          automaticallyImplyLeading: false,
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5),
                  color: Colors.green,
                ),
                child: TabBar(
                  indicator: BoxDecoration(
                    color: Colors.green[800],
                    borderRadius: BorderRadius.circular(5),
                  ),
                  labelColor: Colors.black,
                  tabs: [
                    Tab(
                      child: Text("Tab 1"),
                      icon: Icon(
                        Icons.abc_sharp,
                        color: Colors.black,
                      ),
                    ),
                    Tab(
                      child: Text("Tab 2"),
                      icon: Icon(
                        Icons.ac_unit_sharp,
                        color: Colors.black,
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                child: TabBarView(children: [
                  MyTabOne(),
                  MyTabTwo(),
                ]),
              )
            ],
          ),
        ),
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Center(
        child: Text(
      "This is Tab One",
      style: TextStyle(fontSize: 20),
    ));
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      margin: EdgeInsets.fromLTRB(0, 50, 0, 0),
      child: Column(
        children: [
          Center(
              child: Text(
            "This is Tab Two",
            style: TextStyle(fontSize: 20),
          )),
          Container(
            padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
            margin: EdgeInsets.fromLTRB(5, 5, 5, 0),
            child: TextButton(
              style: TextButton.styleFrom(
                shadowColor: Colors.black,
                textStyle: TextStyle(fontSize: 20),
                primary: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10.0),
                ),
                backgroundColor: Colors.grey,
              ),
              onPressed: () async {
                print("Click Here");
              },
              child: Text(
                "Click Here",
                style: TextStyle(color: Colors.white, fontSize: 12),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

I’ve written all of my code in this file, but you could make a separate file for that.

Output:

In this article, we learnt how to use the TabBar and TabBarView widgets to build a custom tab bar in Flutter.

We looked into altering the tab bar’s visual style and showed various content on each tab. Feel free to play around with various layouts and improve the usability of your personalised tab bar.

Related Posts

Bottom Tab Bar in Flutter

Tabbar with image in flutter

Simple Tabbar in Flutter

Progress Bars Example in Flutter

Bottom Tab Bar in Flutter

For navigating between various UIs, the BottomNavigationBar has gained popularity in recent years.

Since the majority of apps now use this widget to switch between screens, many developers use bottom navigation.

Flutter’s bottom navigation bar can include a variety of things, including text labels, icons, or both.

It enables easy switching between an app’s top-level views for the user. It is preferable to use a side navigation bar while utilising a larger screen.

In Flutter applications, the scaffold widget is typically set in conjunction with the bottom navigation bar. To set the bottom navigation bar, use the Scaffold widget’s Scaffold.bottomNavigationBar parameter.

It should be noted that adding the BottomNavigationBar alone will not cause the navigation elements to appear. For Items properties that take a list of BottomNavigationItems widgets, the BottomNavigationItems property must be set.

BottomNavigationBar Widget properties

BottomNavigationBarItem({  
    @required this.icon,  
    this.title,  
    Widget activeIcon,  
    this.backgroundColor,  
  })

Creating the Bottom Tab Bar Example Given below:

Open the lib/main.dart file in your project directory and replace the code with the following:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class TabbarDisplay extends StatefulWidget {
  @override
  TabbarDisplayState createState() =&gt; TabbarDisplayState();
}

class TabbarDisplayState extends State&lt;TabbarDisplay&gt; {
  int _currentIndex = 0;
  final List&lt;Widget&gt; _tabs = [
    Tab1(),
    Tab2(),
    Tab3(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Bottom Tab Bar Example'),
        automaticallyImplyLeading: false,
      ),
      body: _tabs[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Tab 1',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.search),
            label: 'Tab 2',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person),
            label: 'Tab 3',
          ),
        ],
      ),
    );
  }
}

class Tab1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text('Tab 1 Content'),
    );
  }
}

class Tab2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text('Tab 2 Content'),
    );
  }
}

class Tab3 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text('Tab 3 Content'),
    );
  }
}

Explaination of that code

The root widget of the Flutter app created in this code is a MaterialApp. To control the status of the bottom tab bar, we construct a MyHomePage widget that extends StatefulWidget inside of it.

Users can switch between tabs by using the BottomNavigationBar widget, which is added to the Scaffold’s bottomNavigationBar property. Using BottomNavigationBarItem, we create three tabs, each with a label and an icon.

The currently chosen tab is tracked by the BottomNavigationBar’s currentIndex attribute. The state is updated and the current tab is modified by the onTap callback.

Each tab’s content is represented by a different widget (Tab1, Tab2, Tab3). For each tab, you can swap out these widgets with your own original content.

Output :

Related Posts

Tabbar with image in flutter

Simple Tabbar in Flutter

Progress Bars Example in Flutter

Creating a Splash Screen in Flutter

Remove DEBUG Banner in the Flutter app

Rounded Corners Image in Flutter