Basic Flutter widgets
Flutter is a popular open-source UI development framework that allows developers to create high-quality mobile applications for iOS and Android devices. With its rich collection of customizable widgets, it provides a great platform to build beautiful, fluid, and responsive mobile apps.
In this article, we will take a closer look at the basic widgets provided by Flutter and how they can be used to build engaging mobile applications.
What are Widgets in Flutter?
In Flutter, everything is a widget. Widgets are the building blocks of a Flutter application, from simple text to complex layouts, everything is represented as a widget. The widgets in Flutter are highly customizable and can be used to create stunning and responsive user interfaces.
There are two types of widgets in Flutter:
- Stateless Widgets — These widgets are immutable and do not change over time. They are used for widgets that have a fixed state, such as a button or a text field.
- Stateful Widgets — These widgets are mutable and can change over time. They are used for widgets that have a dynamic state, such as a checkbox or a slider.
Some Basic Widgets in Flutter
Text Widget
The Text widget is used to display a piece of text on the screen. It can be customized with various properties such as font size, font weight, color, alignment, etc. Here's an example of how to use the Text widget:
import 'package:flutter/material.dart';
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My App',
home: Scaffold(
appBar: AppBar(
title: Text('Text Widget Example'),
),
body: Center(
child: Text(
'Hello, World!',
style: TextStyle(fontSize: 24),
),
),
),
);
}
}You can customize the text further by changing other properties of the TextStyle object, such as fontWeight, color, backgroundColor, letterSpacing, wordSpacing, height, and many more.
Container Widget
The Container widget in Flutter is a convenience widget that combines common painting, positioning, and sizing widgets. It can be used to apply decoration, padding, margins, constraints, alignment, and child widgets to a widget tree.
Here’s an example of a Container widget that displays a red colored box with the text "Hello, world!" at the center:
Container(
width: 200,
height: 200,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(10),
),
child: Center(
child: Text(
'Hello, world!',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
);Row and Column Widgets
Row and Column widgets are used to create linear layouts. Row widget arranges its child widgets in a horizontal line while Column widget arranges its child widgets in a vertical line.
Here’s an example of Row widget that has two Text widgets side by side:
Row(
children: [
Text('Hello'),
Text('World'),
],
)And here’s an example of Column widget that has two Text widgets stacked vertically:
Column(
children: [
Text('Hello'),
Text('World'),
],
)Both Row and Column widgets have similar properties, such as mainAxisAlignment and crossAxisAlignment, which can be used to customize how the child widgets are positioned within the layout. For example, the mainAxisAlignment property can be set to MainAxisAlignment.center to center the child widgets along the main axis (either horizontal or vertical), while the crossAxisAlignment property can be set to CrossAxisAlignment.start to align the child widgets to the start of the cross-axis (either top or left).
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Hello'),
Text('World'),
],
)Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Hello'),
Text('World'),
],
)Both of these examples will center the child widgets along the horizontal axis and align them to the top of the vertical axis.
Image Widget
The Image widget is used to display images. It is a basic widget that can display images from various sources such as local assets, network, memory, and file. The Image widget supports different file formats such as JPEG, PNG, GIF, BMP, and WebP.
Here is an example of displaying an image from the network using the Image widget
import 'package:flutter/material.dart';
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image Widget Example'),
),
body: Center(
child: Image.network(
'https://picsum.photos/250?image=9',
width: 200,
height: 200,
fit: BoxFit.cover,
),
),
);
}
}In the above example, we have used the Image.network constructor to display an image from the network. We have provided the URL of the image as a parameter. We have also provided the width and height properties to set the size of the image, and the fit property to determine how the image should fit into the available space.
Similarly, we can use the Image.asset constructor to display an image from local assets, and the Image.file constructor to display an image from a file.
Note that when displaying images, it is important to consider the size and resolution of the image to ensure good performance and avoid memory issues. It is recommended to use images with an appropriate size and resolution for the target device and to use caching and lazy loading techniques for better performance.
Button Widget
The RaisedButton widget is used to create a button with a raised surface. It is one of the most commonly used widgets for user interaction in Flutter applications.
Here is an example of how to create a RaisedButton widget in Flutter:
RaisedButton(
onPressed: () {
// action to be performed on button press
},
child: Text('Press me'),
)In this example, the RaisedButton widget takes two parameters: onPressed and child. The onPressed parameter is a callback function that is called when the button is pressed. The child parameter is the widget that is displayed inside the button. In this case, the child widget is a Text widget with the text "Press me".
Get Suren’s stories in your inbox
Join Medium for free to get updates from this writer.
You can customize the appearance of the RaisedButton widget by setting properties such as color, textColor, shape, and elevation. For example:
RaisedButton(
onPressed: () {
// action to be performed on button press
},
color: Colors.blue,
textColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0),
),
elevation: 4.0,
child: Text('Press me'),
)In the above example, we set the button to blue, textColor to white, and then shape to a rounded rectangle with a border radius of 8.0. We also set elevation the button to 4.0, which gives it a shadow effect.
TextField Widget
The TextField widget in Flutter provides a text input field for users to enter text. It is one of the most commonly used widgets in Flutter applications. The TextField widget provides a wide range of customization options such as controlling the keyboard type, text capitalization, text input validation, and more.
Here’s an example of a basic TextField widget implementation:
TextField(
decoration: InputDecoration(
labelText: 'Enter your name',
border: OutlineInputBorder(),
),
onChanged: (text) {
print('You entered: $text');
},
)In this example, we have provided a decoration to the TextField widget to give it a label and border. We also provided an onChanged callback function that will be called every time the user enters text into the field.
You can also customize the appearance of the TextField widget using the style property. For example, you can change the font size, color, and other text attributes like this:
TextField(
style: TextStyle(fontSize: 20, color: Colors.blue),
decoration: InputDecoration(
labelText: 'Enter your name',
border: OutlineInputBorder(),
),
onChanged: (text) {
print('You entered: $text');
},
)This will set the font size to 20 and the text color to blue.
You can also use the keyboardType property to set the type of keyboard that should be displayed when the user taps on the field. For example, to show a number pad keyboard, you can do this:
TextField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Enter your age',
border: OutlineInputBorder(),
),
onChanged: (text) {
print('You entered: $text');
},
)This will display a number pad keyboard instead of the default alphabetic keyboard.
Overall, the TextField widget is an essential widget in Flutter applications that allows users to enter text input. It is highly customizable and provides a wide range of options to tailor it to your specific needs.
Checkbox Widget
The Checkbox widget in Flutter is a basic UI element that allows the user to select one or multiple options from a list of choices. It consists of a small box and a label that describes the option. When the user taps on the box, it toggles between checked and unchecked states.
Here’s an example of how to use the Checkbox widget in Flutter:
bool _isChecked = false;
Checkbox(
value: _isChecked,
onChanged: (bool value) {
setState(() {
_isChecked = value;
});
},
title: Text('Option 1'),
),In this example, we have defined a boolean variable _isChecked that stores the current state of the Checkbox. We have also added a title parameter to display a label for the Checkbox.
The value the parameter specifies whether the Checkbox is currently checked or not, and the onChanged the parameter is a callback function that is called when the Checkbox is tapped. In this function, we update the state of the _isChecked variable based on the new value of the Checkbox.
You can add multiple Checkbox widgets to create a list of options for the user to choose from.
Radio Widget
The Radio Widget in Flutter is a material design radio button. It allows the user to select a single option from a list of options. When a user selects a radio button, all other radio buttons in the same group are automatically deselected.
Here is an example of using Radio Widget in Flutter:
import 'package:flutter/material.dart';
class RadioExample extends StatefulWidget {
@override
_RadioExampleState createState() => _RadioExampleState();
}
class _RadioExampleState extends State<RadioExample> {
int _radioValue = 1;
List<String> _radioValues = ['Option 1', 'Option 2', 'Option 3'];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Radio Example'),
),
body: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: _radioValues
.asMap()
.entries
.map((entry) => RadioListTile(
title: Text(entry.value),
value: entry.key,
groupValue: _radioValue,
onChanged: (value) {
setState(() {
_radioValue = value!;
});
},
))
.toList(),
),
),
);
}
}In this example, we are creating a stateful widget named RadioExample. Inside the widget, we are initializing a variable _radioValue to hold the value of the selected radio button. We are also initializing a list of radio values _radioValues.
Then, in the build method, we are displaying the list of radio buttons using the RadioListTile widget. We are using the asMap method to loop through the list and get the index of each value.
For each radio button, we are using the RadioListTile widget and passing the title and value properties. We are also passing the groupValue property as _radioValue and onChanged property to update the _radioValue when the user selects a radio button.
This is just a basic example of using Radio Widget in Flutter. There are many properties available for customization, such as activeColor, tileColor, controlAffinity, and more.
Switch Widget
The Switch widget in Flutter is a Material Design style toggle switch that can be used to turn on or off a particular setting. It has two states: on and off, and can be customized with colors, labels, and other attributes.
Here’s an example of how to use the Switch widget in Flutter:
import 'package:flutter/material.dart';
class MySwitchWidget extends StatefulWidget {
@override
_MySwitchWidgetState createState() => _MySwitchWidgetState();
}
class _MySwitchWidgetState extends State<MySwitchWidget> {
bool _switchValue = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Switch Widget Example'),
),
body: Container(
padding: EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Switch(
value: _switchValue,
onChanged: (value) {
setState(() {
_switchValue = value;
});
},
activeTrackColor: Colors.lightGreenAccent,
activeColor: Colors.green,
inactiveThumbColor: Colors.grey,
inactiveTrackColor: Colors.grey[200],
),
SizedBox(height: 16.0),
Text(
'Switch is ${_switchValue ? 'on' : 'off'}',
style: TextStyle(fontSize: 18.0),
),
],
),
),
);
}
}In this example, we create a stateful widget called MySwitchWidget. We initialize the switch value to false in the widget's state and display a Switch widget with a label that says "Switch is off". When the user toggles the switch, we update the state with the new value of the switch and display a message that says "Switch is on" or "Switch is off" depending on the current value of the switch. We also customize the appearance of the switch by changing the active and inactive colors, and the color of the track and thumb.
Slider Widget
The Slider widget in Flutter is a material design slider which can be used to select a range of values from a given interval. It is typically used for selecting a range of values like brightness, volume, or the position of a media player.
Here is an example of how to use the Slider widget in Flutter:
import 'package:flutter/material.dart';
class SliderExample extends StatefulWidget {
@override
_SliderExampleState createState() => _SliderExampleState();
}
class _SliderExampleState extends State<SliderExample> {
double _currentSliderValue = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Slider Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Slider(
value: _currentSliderValue,
min: 0,
max: 100,
divisions: 10,
label: _currentSliderValue.round().toString(),
onChanged: (double value) {
setState(() {
_currentSliderValue = value;
});
},
),
Text('Value: $_currentSliderValue'),
],
),
),
);
}
}In this example, a Slider widget is created with an value of _currentSliderValue, a minimum value of 0, and a maximum value of 100. It also has 10 divisions and a label that displays the current value of the slider. The onChanged callback is called whenever the user interacts with the slider, and it updates the state of the _currentSliderValue. The current value of the slider is then displayed using a Text widget.
Conclusion
In conclusion, Flutter provides a rich collection of basic widgets that can be used to create beautiful and responsive user interfaces. These widgets are highly customizable and can be used to create complex layouts and interactions. By combining these basic widgets with advanced features like animations, gestures, and state management, developers can create engaging and interactive mobile applications.
more you share… more you learn… stay connected and follow for more!
Good Luck!










