flutter
flutter
1)
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My App',
home: Scaffold(
appBar: AppBar(
title: Text('My App'),
),
body: Center(
child: Text('Hello, World!'),
),
),
);
}
}
EXPLAIN:
In this example, the main() function is defined, which calls the runApp()
function and passes an instance of the MyApp widget to it. The MyApp widget is a
StatelessWidget that defines the app's UI.
The main.dart file can also contain other code, such as:
Importing packages and libraries
Defining constants and variables
Setting up app-wide configurations
Initializing services and plugins
However, it's generally recommended to keep the main.dart file simple and
focused on setting up the app's environment, and to move more complex logic to
separate files and widgets.
Here's a breakdown of the main files and folders in a Flutter project:
lib folder: This folder contains the app's Dart code, including the main.dart
file.
main.dart file: This file is the entry point of the app, and it's where the app
starts executing when it's launched.
pubspec.yaml file: This file contains metadata about the app, such as its name,
description, and dependencies.
android and ios folders: These folders contain platform-specific code and
configurations for Android and iOS etc.
2)
Text Widget in Flutter
The Text widget in Flutter is used to display text on the screen. It is one of
the most basic and widely used widgets in Flutter.
Basic Usage
Here is an example of how to use the Text widget:
Text('Hello, World!')
This will display the text "Hello, World!" on the screen.
Properties
The Text widget has several properties that can be used to customize its
appearance and behavior. Some of the most common properties include:
text: The text to be displayed.
style: The style of the text, including font, size, color, and more.
textAlign: The alignment of the text, such as left, right, or center.
maxLines: The maximum number of lines of text to display.
overflow: What to do when the text overflows the available space.
Text Style:
The style property of the Text widget is used to customize the appearance of the
text. You can use the TextStyle class to create a custom text style.
Here is an example:
Text(
'Hello, World!',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.blue,
),
)
This will display the text "Hello, World!" in a bold, blue font with a size of
24.
Text Alignment:
The textAlign property of the Text widget is used to align the text. You can use
the TextAlign enum to specify the alignment.
Here is an example:
Text(
'Hello, World!',
textAlign: TextAlign.center,
)
This will center the text horizontally.
Text Overflow:
The overflow property of the Text widget is used to specify what to do when the
text overflows the available space. You can use the TextOverflow enum to specify
the behavior.
Here is an example:
Text(
'This is a very long piece of text that will overflow the available space.',
maxLines: 1,
overflow: TextOverflow.ellipsis,
)
This will display the text on a single line, and use an ellipsis to indicate
that the text has been truncated.
Rich Text:
The Text widget also supports rich text, which allows you to display text with
multiple styles. You can use the RichText widget to create rich text.
Here is an example:
RichText(
text: TextSpan(
children: [
TextSpan(
text: 'Hello, ',
style: TextStyle(fontSize: 24),
),
TextSpan(
text: 'World!',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
],
),
)
This will display the text "Hello, World!" with the word "World!" in bold.
3)
DIFFERENCE B/W STATEFUL AND STATELESS WIDGET:
Stateful vs Stateless Widgets in Flutter
In Flutter, widgets can be either stateful or stateless. The main difference
between the two is how they handle state changes.
Stateless Widgets:
Stateless widgets are immutable, meaning their properties cannot be changed once
they are created. They are useful when the widget's properties do not need to
change during the app's lifetime.
Here is an example of a stateless widget:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Text('Hello, World!');
}
}
In this example, the MyApp widget is a stateless widget that displays the text
"Hello, World!". The text cannot be changed once the widget is created.
Stateful Widgets:
Stateful widgets, on the other hand, are mutable, meaning their properties can
be changed during the app's lifetime. They are useful when the widget's
properties need to change in response to user interactions or other events.
Here is an example of a stateful widget:
class CounterApp extends StatefulWidget {
@override
_CounterAppState createState() => _CounterAppState();
}
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Counter App'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
In this example, the CounterApp widget is a stateful widget that displays a
counter that increments when the user presses a button. The _counter variable is
used to store the current count, and the setState method is used to update the
count when the button is pressed.
Here are the key differences between stateful and stateless widgets:
Immutability: Stateless widgets are immutable, while stateful widgets are
mutable.
State: Stateless widgets do not have a state, while stateful widgets have a
state that can be changed.
Rebuild: Stateless widgets are not rebuilt when their properties change, while
stateful widgets are rebuilt when their state changes.
Use cases: Stateless widgets are useful for displaying static content, while
stateful widgets are useful for displaying dynamic content that changes in
response to user interactions or other events.
4)
Container widget
The Container widget is used to contain and style other widgets. It can have
padding, margins, borders, and a background color.
Container(
padding: EdgeInsets.all(16.0),
margin: EdgeInsets.all(10.0),
decoration: BoxDecoration(
border: Border.all(color: Colors.black),
borderRadius: BorderRadius.circular(8.0),
color: Colors.lightBlue,
),
child: Text(
'This is a container',
style: TextStyle(fontSize: 18, color: Colors.white),
),
)
5)
Row and column widgets
The Row and Column widgets are used for creating flexible layouts in a
horizontal and vertical direction, respectively.
Row example
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Text('Item 1'),
Text('Item 2'),
Text('Item 3'),
],
)
Column example
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Item 1'),
Text('Item 2'),
Text('Item 3'),
],
)
6)
Building layouts in Flutter
Building layouts in Flutter involves nesting widgets inside each other. Letâs
create a simple layout for a mobile application that includes a header, a main
content area with some text and images, and a footer.
Example: Simple mobile layout:
Here's an example of how to create a basic mobile layout using Column, Row,
Container, and Text widgets.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
7)
Styling elements in Flutter
Styling in Flutter is done through properties provided by each widget. You can
set colors, padding, margins, borders, text styles, and more.
Text styling
The Text widget can be styled using the style property, which accepts a
TextStyle object.
Text(
'Styled Text',
style: TextStyle(
fontSize: 30,
color: Colors.purple,
fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic,
),
)
Container styling
The Container widget can be styled using various properties such as padding,
margin, decoration, and more.
Container(
padding: EdgeInsets.all(20.0),
margin: EdgeInsets.all(10.0),
decoration: BoxDecoration(
color: Colors.teal,
borderRadius: BorderRadius.circular(10.0),
border: Border.all(color: Colors.black, width: 2),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 5,
blurRadius: 7,
offset: Offset(0, 3),
),
],
),
child: Text(
'Styled Container',
style: TextStyle(color: Colors.white, fontSize: 16),
),
)
8)
image widget in flutter
Image Widget in Flutter
The Image widget in Flutter is a built-in widget that displays an image. It can
be used to load and display images from various sources, such as assets, files,
and networks.
Types of Images
There are several types of images that can be displayed using the Image widget:
Asset Image: Loaded from the app's asset bundle.
File Image: Loaded from a file on the device's file system.
Network Image: Loaded from a URL.
Memory Image: Loaded from a byte array in memory.Basic Usage
Here is a basic example of how to use the Image widget to display an asset
image:
Image(
image: AssetImage('assets/my_image.png'),
)
In this example, assets/my_image.png is the path to the image asset.
Properties
The Image widget has several properties that can be used to customize its
behavior:
image: The image to be displayed.
fit: How the image should be fitted within the widget's bounds.
alignment: The alignment of the image within the widget's bounds.
repeat: Whether the image should be repeated to fill the widget's bounds.
Example with Properties
Here is an example of how to use the Image widget with some of its properties:
Image(
image: AssetImage('assets/my_image.png'),
fit: BoxFit.cover,
alignment: Alignment.center,
repeat: ImageRepeat.noRepeat,
)
In this example, the image is fitted to cover the entire widget, centered within
the bounds, and not repeated.
12)
SizedBox Widget in Flutter
The SizedBox widget in Flutter is a built-in widget that defines a rectangular
area of a given size. It is a simple widget that can be used to add space
between widgets, set the size of a widget, or constrain the size of a child
widget.
Basic Usage
Here is a basic example of how to use the SizedBox widget:
SizedBox(
width: 100,
height: 50,
)
In this example, the SizedBox widget has a width of 100 pixels and a height of
50 pixels.
Properties
The SizedBox widget has several properties that can be used to customize its
behavior:
width: The width of the SizedBox widget.
height: The height of the SizedBox widget.
child: The child widget to be contained within the SizedBox widget.
Example with Child:
Here is an example of how to use the SizedBox widget with a child widget:
SizedBox(
width: 100,
height: 50,
child: Text('Hello, World!'),
)
In this example, the Text widget is contained within the SizedBox widget, which
has a width of 100 pixels and a height of 50 pixels.
Use Cases
The SizedBox widget can be used in various scenarios, such as:
Adding space between widgets: By using a SizedBox widget with a specific width
or height, you can add space between widgets.
Setting the size of a widget: By wrapping a widget with a SizedBox widget, you
can set its size explicitly.
Constraining the size of a child widget: By using a SizedBox widget as a parent,
you can constrain the size of a child widget.
13)
Navigation in Flutter
Navigation in Flutter refers to the process of moving between different screens
or routes within an app. Flutter provides a built-in navigation system that
allows you to navigate between routes using the Navigator class.
Types of Navigation
There are two types of navigation in Flutter:
Push Navigation: This type of navigation involves pushing a new route onto the
navigation stack, which allows the user to navigate back to the previous route.
Pop Navigation: This type of navigation involves popping the current route from
the navigation stack, which returns the user to the previous route.
Navigator Class
Navigator Class
The Navigator class is used to manage the navigation stack. It provides several
methods for navigating between routes, including:
push: Pushes a new route onto the navigation stack.
pop: Pops the current route from the navigation stack.
pushNamed: Pushes a new route onto the navigation stack using a named route.
popUntil: Pops routes from the navigation stack until a predicate is satisfied.
MaterialPageRoute
The MaterialPageRoute class is a type of route that provides a material design
transition when navigating between routes. It is commonly used for push
navigation.
Basic Navigation Example
Here is a basic example of how to use the Navigator class to navigate between
routes:
MaterialApp(
title: 'Navigation Demo',
home: HomeScreen(),
routes: {
'/home': (context) => HomeScreen(),
'/details': (context) => DetailsScreen(),
},
)
14)
SingleChildScrollView in Flutter
The SingleChildScrollView widget in Flutter is a scrollable widget that can
contain a single child widget. It is a simple and efficient way to add scrolling
functionality to a widget, especially when the child widget's size is unknown or
dynamic.
Basic Usage
Here is a basic example of how to use the SingleChildScrollView widget:
SingleChildScrollView(
child: Container(
height: 2000, // large height to demonstrate scrolling
color: Colors.red,
),
)
In this example, the SingleChildScrollView widget contains a Container widget
with a large height, which allows the user to scroll vertically.
Properties
The SingleChildScrollView widget has several properties that can be used to
customize its behavior:
child: The child widget to be contained within the SingleChildScrollView widget.
scrollDirection: The direction of the scroll (either Axis.vertical or
Axis.horizontal).
reverse: Whether the scroll direction is reversed (default is false).
primary: Whether the scroll view is primary (default is true).
Example with Scroll Direction
Here is an example of how to use the SingleChildScrollView widget with a
horizontal scroll direction:
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
Container(width: 100, color: Colors.red),
Container(width: 100, color: Colors.green),
Container(width: 100, color: Colors.blue),
],
),
)
In this example, the SingleChildScrollView widget contains a Row widget with
three child Container widgets, which allows the user to scroll horizontally.
Use Cases
The SingleChildScrollView widget can be used in various scenarios, such as:
Displaying a large amount of content that doesn't fit on the screen.
Creating a scrolling list or grid of widgets.
Adding scrolling functionality to a widget with a dynamic size.
Comparison with ListView
The SingleChildScrollView widget is similar to the ListView widget, but it has
some key differences:
SingleChildScrollView can contain a single child widget, while ListView can
contain multiple child widgets.
SingleChildScrollView is more efficient when the child widget's size is unknown
or dynamic, while ListView is more efficient when the child widgets have a fixed
size.
15)
ListView in Flutter
The ListView widget in Flutter is a scrollable widget that displays a list of
children widgets in a vertical or horizontal direction. It is a powerful and
flexible widget that can be used to create a wide range of list-based user
interfaces.
Basic Usage
Here is a basic example of how to use the ListView widget:
ListView(
children: [
ListTile(title: Text('Item 1')),
ListTile(title: Text('Item 2')),
ListTile(title: Text('Item 3')),
],
)
In this example, the ListView widget contains a list of three ListTile widgets,
which are displayed in a vertical direction.
Properties
The ListView widget has several properties that can be used to customize its
behavior:
children: The list of child widgets to be displayed in the ListView.
scrollDirection: The direction of the scroll (either Axis.vertical or
Axis.horizontal).
reverse: Whether the scroll direction is reversed (default is false).
primary: Whether the scroll view is primary (default is true).
shrinkWrap: Whether the ListView should shrink wrap its content (default is
false).
physics: The scroll physics to be used (e.g. BouncingScrollPhysics or
ClampingScrollPhysics).
Types of ListView
There are two types of ListView widgets:
ListView: A basic ListView widget that displays a list of children widgets.
ListView.builder: A ListView widget that uses a builder function to create the
children widgets on demand.
ListView.builder
The ListView.builder widget is a more efficient way to create a ListView when
the number of children widgets is large or unknown. It uses a builder function
to create the children widgets only when they are needed, which can improve
performance and reduce memory usage.
Here is an example of how to use the ListView.builder widget:
ListView.builder(
itemCount: 100,
itemBuilder: (context, index) {
return ListTile(title: Text('Item $index'));
},
)
In this example, the ListView.builder widget creates a list of 100 ListTile
widgets using a builder function.
Use Cases
The ListView widget can be used in various scenarios, such as:
Displaying a list of items, such as a list of contacts or a list of products.
Creating a scrolling list of widgets, such as a list of cards or a list of
images.
Implementing a infinite scrolling list, such as a social media feed or a news
feed.
Comparison with SingleChildScrollView
The ListView widget is similar to the SingleChildScrollView widget, but it has
some key differences:
ListView can contain multiple child widgets, while SingleChildScrollView can
contain only a single child widget.
ListView is more efficient when the number of children widgets is large or
unknown, while SingleChildScrollView is more efficient when the child widget's
size is unknown or dynamic.
16)
TextField in Flutter
The TextField widget in Flutter is a basic text input field that allows users to
enter and edit text. It is a fundamental widget in Flutter that is used in a
wide range of applications, from simple forms to complex data entry systems.
Basic Usage
Here is a basic example of how to use the TextField widget:
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter your name',
),
)
In this example, the TextField widget is created with a basic decoration that
includes a border and a label.
Properties
The TextField widget has several properties that can be used to customize its
behavior:
controller: The text editing controller that manages the text input.
decoration: The decoration to be used for the text field, such as a border or a
label.
maxLines: The maximum number of lines to be displayed in the text field.
maxLength: The maximum number of characters to be entered in the text field.
obscureText: Whether the text input should be obscured, such as for password
entry.
autofocus: Whether the text field should be focused automatically when the
widget is created.
Types of TextField
There are several types of TextField widgets:
TextField: A basic text field that allows users to enter and edit text.
TextFormField: A TextField widget that is wrapped in a Form widget, which allows
for validation and submission of the form.
EditableText: A low-level text editing widget that provides more control over
the text input.
Use Cases
The TextField widget can be used in various scenarios, such as:
Creating a simple form with text input fields.
Building a complex data entry system with multiple text fields.
Implementing a search bar or a filter input field.
Common Use Cases for TextField
Login and Registration Forms: TextField is used to create username and password
input fields.
Search Bars: TextField is used to create a search input field that allows users
to search for specific data.
Forms and Surveys: TextField is used to create text input fields for forms and
surveys.
17)
DialogBox in Flutter
The Dialog widget in Flutter is a material design dialog box that can be used to
display important information or to prompt the user for input. It is a modal
window that appears on top of the current screen, and it can be used to provide
additional information, confirm an action, or prompt the user for input.
Basic Usage
Here is a basic example of how to use the Dialog widget:
showDialog(
context: context,
builder: (BuildContext context) {
return Dialog(
child: Container(
height: 200,
child: Center(
child: Text('This is a dialog box'),
),
),
);
},
);
In this example, the showDialog function is used to display a Dialog widget with
a simple text message.
Properties
The Dialog widget has several properties that can be used to customize its
behavior:
child: The widget to be displayed inside the dialog box.
barrierDismissible: Whether the dialog box can be dismissed by tapping outside
the dialog box (default is true).
shape: The shape of the dialog box (default is a rounded rectangle).
elevation: The elevation of the dialog box (default is 24.0).
Types of Dialog
There are several types of Dialog widgets:
AlertDialog: A dialog box with a title, content, and actions.
SimpleDialog: A dialog box with a title and a list of options.
Dialog: A basic dialog box with a child widget.
AlertDialog
The AlertDialog widget is a more advanced dialog box that can be used to display
a title, content, and actions. Here is an example:
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Alert Dialog'),
content: Text('This is an alert dialog'),
actions: [
FlatButton(
child: Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
In this example, the AlertDialog widget is used to display a title, content, and
an OK button.
Use Cases
The Dialog widget can be used in various scenarios, such as:
Displaying important information or warnings to the user.
Prompting the user for input or confirmation.
Providing additional information or details about a specific topic.
18)
ListTile Widget in Flutter
The ListTile widget in Flutter is a single fixed-height row that typically
contains some text as well as a leading or trailing icon. It's commonly used in
ListViews to display a list of items.
Here's a basic example of how to use a ListTile widget:
ListTile(
leading: Icon(Icons.arrow_right),
title: Text('ListTile Title'),
subtitle: Text('ListTile Subtitle'),
trailing: Icon(Icons.arrow_left),
);
In this example, the ListTile has a leading icon, a title, a subtitle, and a
trailing icon.
Here are some of the key properties of the ListTile widget:
leading: The widget to display before the title.
title: The primary content of the list tile.
subtitle: The secondary content of the list tile.
trailing: The widget to display after the title.
dense: Whether the list tile is part of a vertically dense list.
enabled: Whether the list tile is enabled or not.
selected: Whether the list tile is selected or not.
onTap: The callback that is called when the list tile is tapped.
You can customize the appearance of the ListTile by using these properties.
19)
Listview in flutter
Overview of ListView
Definition: ListView is a scrollable list of widgets arranged linearly, either
vertically or horizontally.
Purpose: It is used to display a large number of items efficiently, allowing
users to scroll through them.
Types of ListView
ListView
Basic constructor that takes a list of widgets.
Suitable for a small number of items.
Example:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
2)ListView.builder
Efficient for large lists as it only builds the visible items.
Uses an itemBuilder callback to create items on demand.
Example:
ListView.builder(
itemCount: 100,
itemBuilder: (context, index) {
return ListTile(title: Text('Item $index'));
},
);
3) ListView.separated
Similar to ListView.builder, but allows for a separator widget between items.
Useful for adding visual dividers.
Example
ListView.separated(
itemCount: 100,
itemBuilder: (context, index) {
return ListTile(title: Text('Item $index'));
},
separatorBuilder: (context, index) => Divider(),
);
4) ListView.custom
Provides more control over how children are built using a SliverChildDelegate.
Useful for complex scenarios where you need custom behavior.
Example
ListView.custom(
childrenDelegate: SliverChildBuilderDelegate(
(context, index) => ListTile(title: Text('Item $index')),
childCount: 100,
),
);
20)
BottomNavigationBar in flutter
The BottomNavigationBar in Flutter is a widget that allows users to navigate
between different views or pages within an app. It is typically placed at the
bottom of the screen and provides a convenient way to switch between top-level
views.
Key Features of BottomNavigationBar
Navigation: It helps users switch between different sections of an app quickly.
Icons and Labels: Each item can have an icon and a label, making it easier for
users to understand the purpose of each tab.
State Management: It can be combined with state management solutions to maintain
the state of the currently selected tab.
Basic Structure
The BottomNavigationBar is usually used within a Scaffold widget in Flutter.
Hereâs a basic example of how to implement a BottomNavigationBar.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Bottom Navigation Bar Example'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: 'Search',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Profile',
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.blue,
onTap: _onItemTapped,
),
);
}
}
Explanation of the Example
Example Implementation
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dropdown Example'),
),
body: Center(
child: DropdownButton<String>(
hint: Text('Select an option'), // Placeholder text
value: _selectedValue, // Currently selected value
onChanged: (String? newValue) {
setState(() {
_selectedValue = newValue; // Update the selected value
});
},
items: _items.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
),
);
}
}
Explanation of the Example
Stateful Widget: The DropdownExample is a StatefulWidget because the selected
value can change based on user interaction.
Selected Value: The _selectedValue variable holds the currently selected item
from the dropdown.
DropdownButton:
hint: A placeholder text that appears when no item is selected.
value: The current selected value.
onChanged: A callback function that is called when the user selects a new value.
It updates the state with the new selected value.
items: A list of DropdownMenuItem widgets generated from the _items list.
Customization Options
DropdownButtonFormField: If you want to use a dropdown in a form, consider using
DropdownButtonFormField, which integrates with form validation.
Style Customization:
You can customize the appearance of the dropdown items by using properties like
style, icon, and underline.
Disabled State: You can disable the dropdown by setting onChanged to null.
Example with DropdownButtonFormField
Here's how you can use DropdownButtonFormField for better integration with
forms:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Dropdown Form Example'),
),
body: Center(
child: DropdownButtonFormField<String>(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Select an option',
),
value: _selectedValue,
onChanged: (String? newValue) {
setState(() {
_selectedValue = newValue;
});
},
items: _items.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
),
22)
TabBar without appbar in flutter
Creating a TabBar without an AppBar in Flutter is possible and can be useful for
various layouts. You can place the TabBar directly within a Column or another
widget, and manage the tab selection using a TabController.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
@override
void initState() {
super.initState();
_tabController = TabController(length: 3, vsync: this);
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
// TabBar without AppBar
Container(
color: Colors.blue,
child: TabBar(
controller: _tabController,
tabs: [
Tab(text: 'Tab 1'),
Tab(text: 'Tab 2'),
Tab(text: 'Tab 3'),
],
indicatorColor: Colors.white,
labelColor: Colors.white,
unselectedLabelColor: Colors.white70,
),
),
// TabBarView
Expanded(
child: TabBarView(
controller: _tabController,
children: [
Center(child: Text('Content for Tab 1')),
Center(child: Text('Content for Tab 2')),
Center(child: Text('Content for Tab 3')),
],
),
),
],
),
);
}
}
Explanation of the Example
Stateful Widget: We create a StatefulWidget called TabBarWithoutAppBar to manage
the state of the TabController.
TabController:
We create a TabController in the initState method, specifying the number of tabs
(length: 3) and using this as the vsync parameter to ensure proper animation.
We dispose of the TabController in the dispose method to free up resources.
TabBar:
The TabBar is placed inside a Container with a background color for better
visibility.
We set the controller to the _tabController and define the tabs.
TabBarView:
The TabBarView is placed inside an Expanded widget to take up the remaining
space below the TabBar.
Each tab displays centered text, but you can replace this with any widget.
Customization Options
Styles: You can customize the TabBar by changing properties like indicatorColor,
labelColor, and unselectedLabelColor.
Icons: You can use icons in the tabs by replacing the Tab widget with Tab(icon:
Icon(Icons.your_icon)).
Scrollable Tabs: If you have many tabs, you can make the TabBar scrollable by
using isScrollable: true.
23)
Bottum sheet in flutter
In Flutter, a bottom sheet is a sliding panel that comes up from the bottom of
the screen. It can be used to display additional content or options without
navigating away from the current screen. Flutter provides two types of bottom
sheets:
Modal Bottom Sheet: A bottom sheet that blocks interaction with the rest of the
app until it's dismissed.
Persistent Bottom Sheet: A bottom sheet that remains visible and allows
interaction with the rest of the app.
Example of Modal Bottom Sheet
Here's how to implement a modal bottom sheet in Flutter:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Modal Bottom Sheet Example'),
),
body: Center(
child: ElevatedButton(
onPressed: () => _showModalBottomSheet(context),
child: Text('Show Modal Bottom Sheet'),
),
),
);
}
}
Explanation of Modal Bottom Sheet Example
HomeScreen Widget: This is the main screen of the app, containing a button to
show the modal bottom sheet.
Bottom Sheet Content: Inside the bottom sheet, we have a Container with a
specified height and a Column containing ListTile widgets. Each ListTile
represents an option that the user can select.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Persistent Bottom Sheet Example'),
),
body: Center(
child: ElevatedButton(
onPressed: () => _showPersistentBottomSheet(context),
child: Text('Show Persistent Bottom Sheet'),
),
),
);
}
}
Explanation of Persistent Bottom Sheet Example
Persistent Bottom Sheet: The showBottomSheet function is used to create a
persistent bottom sheet. Unlike the modal bottom sheet, this one does not block
interaction with the rest of the app.
Bottom Sheet Content: The content of the bottom sheet is defined in the builder
function. In this case, it contains a Container with a height of 200 and a blue
background, along with a Text widget and a button.
24)
Gridview in flutter
In Flutter, a GridView is a widget that displays its children in a grid layout.
It can be used to create a grid of items that can scroll vertically or
horizontally. There are several constructors for GridView, but the most commonly
used ones are:
GridView.count: Creates a grid with a fixed number of tiles in the cross axis.
GridView.builder: Creates a grid that is built on demand, which is useful for
large datasets.
GridView.custom: Allows for more complex grid layouts by using a custom
delegate.
Example of GridView.count
Here's a simple example of using GridView.count to create a grid layout:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('GridView Example'),
),
body: GridView.count(
crossAxisCount: 2, // Number of columns
children: List.generate(items.length, (index) {
return Card(
color: Colors.blueAccent,
child: Center(
child: Text(
items[index],
style: TextStyle(color: Colors.white, fontSize: 20),
),
),
);
}),
),
);
}
}
Explanation of the Example
GridView.count: This constructor creates a grid with a fixed number of columns
specified by crossAxisCount. In this example, we have set it to 2.
Card Widget: Each grid item is wrapped in a Card widget for a nice visual
effect. The Center widget is used to center the text within the card.
Example of GridView.builder
Using GridView.builder is more efficient for larger datasets, as it creates
items on demand:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('GridView Builder Example'),
),
body: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3, // Number of columns
crossAxisSpacing: 4.0, // Space between columns
mainAxisSpacing: 4.0, // Space between rows
),
itemCount: items.length,
itemBuilder: (context, index) {
return Card(
color: Colors.greenAccent,
child: Center(
child: Text(
items[index],
style: TextStyle(color: Colors.white, fontSize: 20),
),
),
);
},
),
);
}
}
Explanation of the GridView.builder Example
GridView.builder: This constructor is used for creating a grid that builds its
items on demand. It is more memory efficient for larger datasets.
itemBuilder: This function is called to build each item in the grid. It receives
the BuildContext and the current index, allowing you to create the grid items
dynamically.
Customizing GridView
You can customize the appearance and behavior of the GridView in various ways:
Cross Axis and Main Axis Spacing: Use crossAxisSpacing and mainAxisSpacing in
the SliverGridDelegate to define spacing between grid items.
Aspect Ratio: You can control the aspect ratio of the grid items using
SliverGridDelegateWithFixedCrossAxisCount with the childAspectRatio property.
25)
spleshscreen in flutter
A splash screen is typically the first screen that appears when a mobile
application is launched. It is used to display branding, logos, or a loading
animation while the app is initializing. In Flutter, you can create a splash
screen using various methods. Below are two common approaches:
Using a Simple Stateless Widget: This method involves creating a splash screen
using a StatelessWidget and navigating to the main app after a delay.
import 'package:flutter/material.dart';
import 'dart:async';
void main() {
runApp(MyApp());
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset('assets/logo.png', height: 100), // Your logo here
SizedBox(height: 20),
CircularProgressIndicator(), // Loading indicator
],
),
),
);
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home Screen'),
),
body: Center(
child: Text('Welcome to the Home Screen!'),
),
);
}
}
Explanation of the Example
SplashScreen Widget: This is a StatefulWidget that displays a logo and a loading
indicator.
Assets: Make sure to add your logo image to the assets folder and update your
pubspec.yaml file to include the asset.
yaml
dependencies:
flutter:
sdk: flutter
splashscreen: ^1.3.5
Step 2: Implement Splash Screen
Here's how to use the splashscreen package:
import 'package:flutter/material.dart';
import 'package:splashscreen/splashscreen.dart';
void main() {
runApp(MyApp());
}
Setting Up shared_preferences
Add Dependency: First, you need to add the shared_preferences package to your
pubspec.yaml file:
yaml
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.0.11 # Check for the latest version
Import the Package: In your Dart file, import the package:
Copy code
import 'package:shared_preferences/shared_preferences.dart';
Example: Using Shared Preferences
Hereâs a simple example demonstrating how to use shared_preferences to save
and retrieve user preferences (like a username).
void main() {
runApp(MyApp());
}
@override
void initState() {
super.initState();
_loadUsername();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Shared Preferences Example'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField(
controller: _controller,
decoration: InputDecoration(labelText: 'Enter your username'),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _saveUsername,
child: Text('Save Username'),
),
SizedBox(height: 20),
Text(
'Saved Username: $_username',
style: TextStyle(fontSize: 20),
),
],
),
),
);
}
}
Explanation of the Example
TextEditingController: We use a TextEditingController to read the text input
from the user.
_saveUsername(): This method saves the username entered by the user into
SharedPreferences. After saving, it calls _loadUsername() to update the
displayed username.
UI: The user interface consists of a TextField for input, a button to save the
username, and a Text widget to display the saved username.
Important Notes
Asynchronous Operations: Both getInstance(), getString(), and setString()
methods are asynchronous, so they return a Future. You should use await to wait
for the operations to complete.
27)
In Flutter, sqflite is a popular package used to manage SQLite databases. It
provides a simple way to store structured data locally on the device. This is
particularly useful for applications that require persistent data storage and
complex queries.
Setting Up sqflite
Add Dependencies: First, add the sqflite and path packages to your pubspec.yaml
file:
yaml
dependencies:
flutter:
sdk: flutter
sqflite: ^2.0.0+4 # Check for the latest version
path: ^1.8.0 # For handling file paths
Import the Packages: In your Dart file, import the necessary packages:
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
Example: Using sqflite
Hereâs a simple example demonstrating how to use sqflite to create a database,
insert data, retrieve data, and delete data.
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
void main() {
runApp(MyApp());
}
@override
void initState() {
super.initState();
_initializeDatabase();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('SQLite Example'),
),
body: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: _items.length,
itemBuilder: (context, index) {
final item = _items[index];
return ListTile(
title: Text(item['name']),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () => _deleteItem(item['id']),
),
);
},
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Expanded(
child: TextField(
onSubmitted: (value) {
if (value.isNotEmpty) {
_addItem(value);
}
},
decoration: InputDecoration(labelText: 'Enter item name'),
),
),
IconButton(
icon: Icon(Icons.add),
onPressed: () {
// Add item logic can also be placed here
},
),
],
),
),
],
),
);
}
@override
void dispose() {
_database?.close();
super.dispose();
}
}
Explanation of the Example
Database Initialization:
In the _initializeDatabase method, we get the path to the database and open it.
If the database does not exist, it will create one and execute the SQL command
to create a table named items.
Loading Items:
The _loadItems method retrieves all items from the items table and updates the
state.
Adding Items:
The _addItem method inserts a new item into the database and refreshes the list
of items.
Deleting Items:
The _deleteItem method deletes an item from the database based on its ID.
28)
State management in Flutter is a crucial aspect of developing responsive and
interactive applications. Flutter provides several ways to manage state, each
with its own advantages and use cases. Below, I'll outline some of the most
common state management approaches in Flutter:
1. setState()
Use Case: Simple state management for small applications or widgets.
Example:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Counter')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Counter: $_counter'),
ElevatedButton(
onPressed: _incrementCounter,
child: Text('Increment'),
),
],
),
),
);
}
}
2. InheritedWidget
Use Case: Sharing state across multiple widgets without passing data down the
widget tree.
Example:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
CounterProvider({required this.child});
@override
_CounterProviderState createState() => _CounterProviderState();
}
void increment() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return _InheritedCounter(
data: this,
child: widget.child,
);
}
}
@override
bool updateShouldNotify(_InheritedCounter oldWidget) {
return true;
}
}
return Scaffold(
appBar: AppBar(title: Text('Inherited Widget Counter')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Counter: ${counterProvider._counter}'),
ElevatedButton(
onPressed: counterProvider.increment,
child: Text('Increment'),
),
],
),
),
);
}
}
3. Provider
Use Case: A more advanced and flexible way to manage state, suitable for medium
to large applications.
Example:
yaml
dependencies:
provider: ^6.0.0 # Check for the latest version
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => Counter(),
child: MyApp(),
),
);
}
void increment() {
_count++;
notifyListeners();
}
}
return Scaffold(
appBar : AppBar(title: Text('Provider Counter')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Counter: ${counter.count}'),
ElevatedButton(
onPressed: counter.increment,
child: Text('Increment'),
),
],
),
),
);
}
}
4. Bloc
Use Case: A more complex and scalable state management solution, suitable for
large applications.
Description: The bloc package is a more advanced state management solution that
uses a unidirectional data flow. It is ideal for large applications with complex
business logic.
Example:
yaml
dependencies:
flutter_bloc: ^8.0.1 # Check for the latest version
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
void main() {
runApp(MyApp());
}
return Scaffold(
appBar: AppBar(title: Text('Bloc Counter')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Counter: ${counterBloc.state}'),
ElevatedButton(
onPressed: () => counterBloc.add(IncrementCounter()),
child: Text('Increment'),
),
],
),
),
);
}
}
5. MobX
Use Case: A reactive state management solution, suitable for applications with
complex business logic.
Description: The mobx package is a reactive state management solution that uses
observables and actions to manage state.
Example:
yaml
dependencies:
mobx: ^2.0.6 # Check for the latest version
flutter_mobx: ^2.0.0 # Check for the latest version
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:mobx/mobx.dart';
void main() {
runApp(MyApp());
}
@action
void increment() {
_count++;
}
return Scaffold(
appBar: AppBar(title: Text('MobX Counter')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Observer(
builder: (context) => Text('Counter: ${counter.count}'),
),
ElevatedButton(
onPressed: counter.increment,
child: Text('Increment'),
),
],
),
),
);
}
}
6. Getx
Use Case: A lightweight and simple state management solution, suitable for small
to medium applications.
Example:
yaml
dependencies:
get: ^4.6.1 # Check for the latest version
import 'package:flutter/material.dart';
import 'package:get/get.dart';
void main() {
runApp(MyApp());
}
void increment() {
_count++;
}
}
return Scaffold(
appBar: AppBar(title: Text('Getx Counter')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Obx(
() => Text('Counter: ${counterController.count}'),
),
ElevatedButton(
onPressed: counterController.increment,
child: Text('Increment'),
),
],
),
),
);
}
}
These are some of the most common state management approaches in Flutter. Each
has its own strengths and weaknesses, and the choice of which one to use depends
on the specific requirements of your application.
29)
packages in flutter
In Flutter, packages are reusable pieces of code that can be added to your
project to extend its functionality. They can range from simple utility
functions to complex libraries that provide a wide array of features, such as
state management, networking, database access, and more. The Flutter ecosystem
has a rich collection of packages available through the pub.dev package
repository.
How to Use Packages in Flutter
Add the Dependency: Open your pubspec.yaml file and add the package under the
dependencies section. For example, to use the http package for making HTTP
requests:
yaml
dependencies:
flutter:
sdk: flutter
http: ^0.14.0 # Check for the latest version on pub.dev
Install the Package: Run the following command in your terminal to install the
package:
bash
dart
1. Networking
http: A powerful package for making HTTP requests.
yaml
dependencies:
http: ^0.14.0
dio: A robust HTTP client for Dart, offering powerful features like
interceptors, global configuration, and more.
yaml
dependencies:
dio: ^5.0.0
2. State Management
provider: A popular package for state management based on InheritedWidgets.
yaml
dependencies:
provider: ^6.0.0
bloc: A package for implementing the BLoC (Business Logic Component) pattern.
yaml
dependencies:
flutter_bloc: ^8.0.0
get: A lightweight and powerful state management solution.
yaml
dependencies:
get: ^4.6.0
3. Database
sqflite: A SQLite plugin for Flutter, allowing local database storage.
yaml
dependencies:
sqflite: ^2.0.0+4
path: ^1.8.0
hive: A lightweight and fast NoSQL database for Flutter and Dart.
yaml
dependencies:
hive: ^2.0.0
hive_flutter: ^1.0.0
4. User Interface
flutter_svg: A package for rendering SVG images in Flutter.
yaml
dependencies:
flutter_svg: ^0.22.0
cached_network_image: A package for downloading and caching images from the web.
dependencies:
cached_network_image: ^3.2.0
flutter_bloc: A package that integrates the BLoC pattern with Flutter, allowing
for easier state management.
dependencies:
flutter_bloc: ^8.0.0
5. Authentication
firebase_auth: A package for Firebase authentication, supporting email/password,
Google, Facebook, and more.
dependencies:
firebase_auth: ^3.0.0
google_sign_in: A package for integrating Google Sign-In into your Flutter app.
dependencies:
google_sign_in: ^5.2.0
6. Miscellaneous
intl: A package for internationalization and localization.
yaml
dependencies:
intl: ^0.17.0
url_launcher: A package for launching URLs in the mobile platform.
yaml
dependencies:
url_launcher: ^6.0.0
flutter_local_notifications: A package for displaying local notifications in
Flutter apps.
yaml
dependencies:
flutter_local_notifications: ^9.0.0
Finding Packages
To find more packages, you can visit pub.dev, where you can search for packages
by category, popularity, or functionality. Each package page provides
documentation, installation instructions, and examples.
Conclusion
Using packages in Flutter can significantly speed up your development process
and enable you to leverage existing solutions for common problems. When choosing
packages, consider their popularity, maintenance status, and community support
to ensure you are using reliable and well-supported libraries.
30)
API in flutter
dart
const String baseUrl = 'https://api.example.com';
2. Define Endpoints
Next, define the specific endpoints youâll be interacting with. Store them in
the same constants file for consistency.
dart
const String getDataEndpoint = '/data';
const String postDataEndpoint = '/data';
const String putDataEndpoint = '/data/{id}';
const String deleteDataEndpoint = '/data/{id}';
3. Make API Calls
Use these constants when making API calls to ensure youâre hitting the correct
endpoints.
class Data {
final String id;
final String name;
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
}
This code fetches data from an API and parses it into a list of Data objects.
1. GET
The GET method retrieves data from a specified resource. It's like reading from
a bookâyou donât change anything; you just read it.
Example in Flutter:
dart
Future<void> createData(Map<String, dynamic> data) async {
final response = await http.post(
Uri.parse('https://api.example.com/data'),
headers: {"Content-Type": "application/json"},
body: json.encode(data),
);
if (response.statusCode == 201) {
print('Data created');
} else {
throw Exception('Failed to create data');
}
}
3. PUT
The PUT method updates a resource. Think of it as editing a specific page in
your diary with new details.
Example in Flutter:
dart
Future<void> updateData(String id, Map<String, dynamic> data) async {
final response = await http.put(
Uri.parse('https://api.example.com/data/$id'),
headers: {"Content-Type": "application/json"},
body: json.encode(data),
);
if (response.statusCode == 200) {
print('Data updated');
} else {
throw Exception('Failed to update data');
}
}
4. DELETE
The DELETE method removes a resource. Itâs like tearing a page out of your
diary.
Example in Flutter:
dart
Future<void> deleteData(String id) async {
final response = await
http.delete(Uri.parse('https://api.example.com/data/$id'));
if (response.statusCode == 200) {
print('Data deleted');
} else {
throw Exception('Failed to delete data');
}
}
31)
Getx in flutter
GetX is a popular package in Flutter that simplifies state management,
dependency injection, and route management. Hereâs a step-by-step explanation:
1. Installation
First, add GetX to your project by including it in your pubspec.yaml file:
yaml
dependencies:
flutter:
sdk: flutter
get: ^4.6.6
Then, run flutter pub get to install the package.
dart
import 'package:get/get.dart';
void increment() {
count++;
}
}
3. Use the Controller in UI
Now, use the controller in your Flutter widget. With GetX, itâs easy to
observe and update the state:
dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'counter_controller.dart';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("GetX Counter Example")),
body: Center(
child: Obx(() => Text(
"Count: ${controller.count}",
style: TextStyle(fontSize: 24),
)),
),
floatingActionButton: FloatingActionButton(
onPressed: controller.increment,
child: Icon(Icons.add),
),
);
}
}
4. Navigation with GetX
GetX provides simple methods for navigating between pages:
dart
// Navigate to a new page
Get.to(() => NewPage());
// Go back
Get.back();
5. Dependency Injection
GetX allows you to manage dependencies easily:
dart
// Lazy loading
final controller = Get.lazyPut(CounterController(), activate: (_) => true);
// Eager loading
final controller = Get.put(CounterController());
6. Other Features
GetX also supports internationalization, theme changes, and more. For example:
dart
// Change theme
Get.changeTheme(ThemeData.dark());
********************************************************************************
************
APIS( CRUD ) through getx
1. Installation
First, add the GetX package to your pubspec.yaml file:
yaml
dependencies:
flutter:
sdk: flutter
get: ^4.6.6
http: ^0.13.3
Run flutter pub get to install the dependencies.
dart
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
// Fetch data
Future<void> fetchData() async {
final response = await http.get(Uri.parse('$baseUrl/data'));
if (response.statusCode == 200) {
dataList.value = json.decode(response.body);
} else {
throw Exception('Failed to load data');
}
}
// Post data
Future<void> postData(Map<String, dynamic> data) async {
final response = await http.post(
Uri.parse('$baseUrl/data'),
headers: {"Content-Type": "application/json"},
body: json.encode(data),
);
if (response.statusCode == 201) {
fetchData();
} else {
throw Exception('Failed to create data');
}
}
// Update data
Future<void> updateData(String id, Map<String, dynamic> data) async {
final response = await http.put(
Uri.parse('$baseUrl/data/$id'),
headers: {"Content-Type": "application/json"},
body: json.encode(data),
);
if (response.statusCode == 200) {
fetchData();
} else {
throw Exception('Failed to update data');
}
}
// Delete data
Future<void> deleteData(String id) async {
final response = await http.delete(Uri.parse('$baseUrl/data/$id'));
if (response.statusCode == 200) {
fetchData();
} else {
throw Exception('Failed to delete data');
}
}
}
3. Integrate Controller with UI
Use the controller in your Flutter widget. This allows you to observe the state
and interact with the API methods.
dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'data_controller.dart';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('GetX API Example')),
body: Obx(() {
if (controller.dataList.isEmpty) {
return Center(child: CircularProgressIndicator());
} else {
return ListView.builder(
itemCount: controller.dataList.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(controller.dataList[index]['name']),
subtitle: Text(controller.dataList[index]['id']),
);
},
);
}
}),
floatingActionButton: FloatingActionButton(
onPressed: () {
// Example data for creating new entry
final newData = {"name": "New Item"};
controller.postData(newData);
},
child: Icon(Icons.add),
),
);
}
}
Deep Dive into Each Method
GET Request
Objective: Retrieve data from the API.
POST Request
Objective: Send data to the API to create a new resource.
Implementation: In postData, you make an HTTP POST request with the data to be
created. On successful creation, call fetchData to refresh the list.
PUT Request
Objective: Update an existing resource with new data.
Implementation: In updateData, you make an HTTP PUT request with the updated
data. On successful update, call fetchData to refresh the list.
DELETE Request
Objective: Remove a resource from the API.