Experiment 1: Installation and Introduction To Dart 1 (A) : Install Flutter and Dart SDK Download Flutter SDK
Experiment 1: Installation and Introduction To Dart 1 (A) : Install Flutter and Dart SDK Download Flutter SDK
o Choose the appropriate version for your operating system (Windows, macOS, Linux).
2. Install Flutter
3. Check Installation
o flutter doctor
o Follow the recommendations from flutter doctor to set up your development
environment.
o dart --version
5. Set up an Editor
Code Example:
void main() {
// 1. Variables
// 3. Loop
print("Counting to 5:");
print(i);
return a + b;
o dart main.dart
4. Output:
o Counting to 5:
o 1
o 2
o 3
o 4
o 5
Text widget:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp()); // MyApp function is running
}
// Defining a function
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Text Widget Example"),
),
body: Center(
child: Text(
'hello',
style: TextStyle(
fontSize: 24.0,
fontWeight: FontWeight.bold,
color: Colors.blue,
),
),
), // Center
),
);
}
}
container widget
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends
StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) { return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Container example"),
),
body: Container( height: 200,
width: double.infinity,
//color: Colors.purple,
alignment: Alignment.center,
// margin: const EdgeInsets.all(20),
padding: const EdgeInsets.all(30), decoration: BoxDecoration(
border: Border.all(color: Colors.black, width: 3),
),
child: const Text("other: Hello! i am inside a container!\nme:Then come outside you idiot!",
style: TextStyle(fontSize: 20)),
),
),
);
}
}
image widget
import 'package:flutter/material.dart';
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Image Example"),
),
body: Center(
child: Container(
width: 300,
height: 300,
decoration: BoxDecoration(
border: Border.all(color: Colors.blue, width: 3),
borderRadius: BorderRadius.circular(10),
),
child: Image.network(
'https://th.bing.com/th/id/OIP.vvUEuhKleSz_PSDuowlMRQHaF7?w=600&h=480&rs=1&pid=ImgDetM
ain', // Replace with your image URL
fit: BoxFit.cover, // Adjust how the image fits the container
),
),
),
),
);
}
}
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
margin: EdgeInsets.all(12.0),
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8), color: Colors.yellowAccent),
child: Text(
"I am jayasree",
style: TextStyle(color: Colors.redAccent, fontSize: 25),
),
),
Container(
margin: EdgeInsets.all(15.0),
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8), color: Colors.blueGrey),
child: Text(
"227Z1A6705",
style: TextStyle(color: Colors.black, fontSize: 25),
),
),
Container(
margin: EdgeInsets.all(12.0),
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8), color: Colors.brown),
child: Text(
"Data Science",
style: TextStyle(color: Colors.yellowAccent, fontSize: 25),
),
)
]),
);
}
}
Color box:
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('GeeksforGeeks'),
backgroundColor: Colors.greenAccent[400],
),
body: Center(
child: SizedBox(
width: 300,
height: 300,
child: Center(
child: Stack(
alignment: Alignment.topRight, // Changed the entry point
children: <Widget>[
Container(
width: 300,
height: 300,
color: Colors.red,
), // Outer Container
Container(
width: 250,
height: 250,
color: Colors.black,
), // Middle Container
Container(
width: 200,
height: 200,
color: Colors.purple,
), // Inner Container
Container(
width: 160,
height: 160,
color: Colors.yellow,
),
],
), // Stack
), // Center
), // SizedBox
), // Center
), // Scaffold
)); // MaterialApp
}
Objective: Learn how to create a UI that adjusts its layout dynamically to accommodate different
device sizes.
Code Example:
import 'package:flutter/material.dart';
@override
home: ResponsiveUI(),
);
@override
return Scaffold(
appBar: AppBar(
),
body: Center(
child: Container(
height: 200,
color: Colors.blue,
alignment: Alignment.center,
child: Text(
textAlign: TextAlign.center,
),
),
),
);
}
Step-by-Step Procedure for Responsive UI:
2. Replace Code
o Test the app on different screen sizes using the emulator or a physical device.
4. Output:
o For larger screens (like tablets or desktops), the text will change to "Tablet or
Desktop View."
Objective: Use media queries to create breakpoints that adjust UI components based on screen size.
Code Example:
import 'package:flutter/material.dart';
@override
return MaterialApp(
home: MediaQueryExample(),
);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
),
body: Center(
? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
],
: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(width: 10),
],
),
),
);
2. Replace Code
o Test the app on different screen sizes using emulators or physical devices.
4. Output:
o On smaller screens, a column with a mobile icon and text will be displayed.
o On larger screens, a row with a desktop icon and text will be displayed.
Objective: Learn to navigate between two screens using Flutter's Navigator class.
Code Example:
import 'package:flutter/material.dart';
@override
return MaterialApp(
home: FirstScreen(),
);
@override
return Scaffold(
appBar: AppBar(
),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.push(
context,
);
},
),
),
);
@override
return Scaffold(
appBar: AppBar(
),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
),
);
2. Edit main.dart
4. Output:
Objective: Set up navigation using named routes for better scalability and maintainability.
Code Example:
import 'package:flutter/material.dart';
@override
return MaterialApp(
initialRoute: '/',
routes: {
},
);
@override
return Scaffold(
appBar: AppBar(
),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.pushNamed(context, '/second');
},
),
),
);
@override
return Scaffold(
appBar: AppBar(
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
),
),
);
2. Edit main.dart
4. Output:
Objective: Understand the differences between Stateful and Stateless widgets by implementing
both.
@override
return MaterialApp(
home: StatelessExample(),
);
@override
return Scaffold(
appBar: AppBar(
),
body: Center(
),
);
import 'package:flutter/material.dart';
@override
return MaterialApp(
home: StatefulExample(),
);
@override
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
@override
return Scaffold(
appBar: AppBar(
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("You have pressed the button this many times:", style: TextStyle(fontSize: 16)),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
child: Icon(Icons.add),
),
);
Step-by-Step Procedure:
o Observe how Stateless widgets remain static while Stateful widgets allow updates to
the UI.
3. Output:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
// Define the Counter class that extends ChangeNotifier
int _count = 0;
void increment() {
_count++;
void main() {
runApp(
ChangeNotifierProvider(
child: MyApp(),
),
);
@override
return MaterialApp(
home: CounterScreen(),
);
return Scaffold(
appBar: AppBar(
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Count:',
),
SizedBox(height: 10),
Text(
'${Provider.of<Counter>(context).count}',
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
},
child: Icon(Icons.add),
),
);
}
Steps to Run
bash
Copy code
flutter run
3. Observe the counter value increment each time you press the button.
Here’s the 6th experiment with all-in-one code demonstrating creating custom widgets and applying
styles with themes.
Custom widgets are reusable UI components that encapsulate design and logic.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
@override
return ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(context).primaryColor, // Use theme color (updated)
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
onPressed: onPressed,
child: Text(
text,
style: TextStyle(
fontSize: 18,
color: Colors.white,
),
),
);
// Main App
@override
return MaterialApp(
theme: ThemeData(
textTheme: TextTheme(
),
),
home: HomeScreen(),
);
@override
return Scaffold(
appBar: AppBar(
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
),
SizedBox(height: 20),
CustomButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
);
},
),
],
),
),
);
How to Run
2. Run:
3. flutter run
Output
Experiment 7: Design a Form with Input Fields and Implement Form Validation
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
@override
return MaterialApp(
home: Scaffold(
appBar: AppBar(
),
body: Padding(
child: FormExample(),
),
),
);
@override
return null;
}
} else if (!RegExp(r'^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]+').hasMatch(value)) {
return null;
void _submitForm() {
if (_formKey.currentState!.validate()) {
} else {
@override
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
controller: _nameController,
validator: _validateName,
),
SizedBox(height: 16),
TextFormField(
controller: _emailController,
validator: _validateEmail,
),
SizedBox(height: 16),
// Submit Button
ElevatedButton(
onPressed: _submitForm,
child: Text('Submit'),
),
],
),
);
Explanation:
1. Form Setup:
2. Input Fields:
o We have two input fields: one for Name and one for Email.
o These fields are controlled using TextEditingController, which allows access to the
input values.
3. Form Validation:
o TextFormField's validator is used to define custom validation logic for each field:
4. Submit Logic:
o The _submitForm() function checks if the form is valid using validate(). If all fields are
valid, a success message (SnackBar) is displayed. Otherwise, an error message is
shown.
5. Styling:
o Padding is applied around the form to make it look neat and centered.
How to Run:
3. flutter run
Expected Behavior:
When you fill out the form and submit it, the input will be validated.
If any input field is empty or incorrect (like an invalid email), an error message will appear.
Output:
You will see a form with two fields: Name and Email, and a submit button. If the user enters invalid
data, it will display an error message. Upon successful submission, a confirmation message will be
shown.
Code:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
@override
return MaterialApp(
debugShowCheckedModeBanner: false,
home: AnimatedIconDemo(),
);
@override
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
);
}
@override
void dispose() {
super.dispose();
void _toggleIcon() {
setState(() {
});
@override
return Scaffold(
appBar: AppBar(
),
body: Center(
child: IconButton(
icon: AnimatedIcon(
),
),
),
);
}
1. AnimationController:
o Controls the animation. In this case, it animates the transition between play and
pause icons.
o The duration defines how long it will take to complete the animation (set to 1 second
here).
2. AnimatedIcon:
3. IconButton:
o The IconButton widget is used to detect user interaction. When the button is
pressed, the _toggleIcon function is called to toggle the animation state.
4. Toggle Logic:
o isPlaying is used to determine whether the animation should play or reverse. When
isPlaying is true, the animation plays forward (to show "pause"); otherwise, it
reverses (to show "play").
Expected Output:
When you run this code, you will see a large "play" icon initially.
o The icon animates from "play" to "pause" or vice versa, depending on the current
state.
The button will toggle between the two icons as long as you keep tapping on it.
Visual Output:
1. Initially, you will see a "Play" icon in the center of the screen.
The icon size is set to 100 and animates between the two states.
How to Run It:
4. flutter run
You should see the icon changing smoothly between "play" and "pause" when clicked, demonstrating
an animated icon in action.
Aim:
The aim of this experiment is to demonstrate how to fetch data from a REST API (in this case,
JSONPlaceholder) using Flutter, parse the JSON response, and display the data (posts) in a ListView
widget.
pubspec.yaml Dependency:
Ensure that the http package is added in your pubspec.yaml file to allow HTTP requests.
dependencies:
flutter:
sdk: flutter
http: ^0.13.3
post.dart Model:
This file contains the Post class, which is used to parse JSON into Flutter objects.
class Post {
return Post(
id: json['id'],
title: json['title'],
body: json['body'],
);
main.dart Implementation:
This is the main file where the Flutter app makes the HTTP request and displays the data.
import 'dart:convert';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
@override
return MaterialApp(
home: PostsScreen(),
);
@override
_PostsScreenState createState() => _PostsScreenState();
@override
void initState() {
super.initState();
if (response.statusCode == 200) {
// Parse the JSON response and convert it into a list of Post objects
} else {
@override
return Scaffold(
body: FutureBuilder<List<Post>>(
future: _posts,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
} else if (snapshot.hasError) {
} else {
return ListView.builder(
itemCount: snapshot.data!.length,
return ListTile(
subtitle: Text(post.body),
);
},
);
},
),
);
Install Dependencies:
Ensure the http package is added to your pubspec.yaml file, and then run:
Expected Output:
Initial Screen: When the app starts, it will display a loading indicator while fetching the data
from the API.
After Data Fetch: Once the data is fetched successfully from the API, the screen will display a
list of posts, each with a title and body text. The list will be scrollable, and if the user taps on
a list item, the ListTile widget will show the title and body of each post.
Error Handling: If the request fails (e.g., no internet connection), it will display an error
message saying: Error: Failed to load posts. If no posts are found (or data is empty), it will
display No data found.