0% found this document useful (0 votes)
46 views36 pages

Experiment 1: Installation and Introduction To Dart 1 (A) : Install Flutter and Dart SDK Download Flutter SDK

Uploaded by

Vaishnavi Peddi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views36 pages

Experiment 1: Installation and Introduction To Dart 1 (A) : Install Flutter and Dart SDK Download Flutter SDK

Uploaded by

Vaishnavi Peddi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Flutter:

Experiment 1: Installation and Introduction to Dart

1(a): Install Flutter and Dart SDK

1. Download Flutter SDK

o Visit the Flutter official website.

o Choose the appropriate version for your operating system (Windows, macOS, Linux).

2. Install Flutter

o Extract the downloaded zip file.

o Add the extracted directory to your system PATH environment variable.

3. Check Installation

o Open your terminal and run:

o flutter doctor
o Follow the recommendations from flutter doctor to set up your development
environment.

4. Install Dart SDK

o Dart is included with Flutter, so no separate installation is needed. To verify, run:

o dart --version

5. Set up an Editor

o Install Visual Studio Code or Android Studio.

o Add the Flutter and Dart plugins/extensions to the editor.

1(b): Write a Simple Dart Program

Objective: Understand Dart basics like variables, loops, and functions.

Code Example:

// Dart Basics Program

void main() {

// 1. Variables

int num1 = 10;

double num2 = 5.5;

String greeting = "Hello, Flutter!";


// 2. Function

int sum = addNumbers(num1, num2.toInt());

print("$greeting The sum of $num1 and ${num2.toInt()} is $sum.");

// 3. Loop

print("Counting to 5:");

for (int i = 1; i <= 5; i++) {

print(i);

// Function to add two numbers

int addNumbers(int a, int b) {

return a + b;

Step-by-Step Procedure for Dart Program:

1. Create a Dart File

o In VS Code, create a new file named main.dart.

2. Write the Program

o Copy the above code into main.dart.

3. Run the Program

o Open the terminal in VS Code.

o Run the program using:

o dart main.dart

4. Output:

o The terminal will display:

o Hello, Flutter! The sum of 10 and 5 is 15.

o Counting to 5:

o 1
o 2

o 3

o 4

o 5

2. a) Explore various widgets(text,image,container)

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';

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("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
),
),
),
),
);
}
}

b) Implement different layouts structures using row,column and stack widgets

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(home: MyHomePage());
}
}

class MyHomePage extends StatefulWidget {


@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter Row Example"),
//alignment: Alignment.center,

),
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
}

Experiment 3: Designing Responsive UI and Implementing Media Queries

3(a): Design a Responsive UI that Adapts to Different Screen Sizes

Objective: Learn how to create a UI that adjusts its layout dynamically to accommodate different
device sizes.

Code Example:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {


return MaterialApp(

home: ResponsiveUI(),

);

class ResponsiveUI extends StatelessWidget {

@override

Widget build(BuildContext context) {

double screenWidth = MediaQuery.of(context).size.width;

return Scaffold(

appBar: AppBar(

title: Text("Responsive UI"),

),

body: Center(

child: Container(

width: screenWidth * 0.8, // 80% of the screen width

height: 200,

color: Colors.blue,

alignment: Alignment.center,

child: Text(

screenWidth > 600 ? "Tablet or Desktop View" : "Mobile View",

style: TextStyle(fontSize: 20, color: Colors.white),

textAlign: TextAlign.center,

),

),

),

);

}
Step-by-Step Procedure for Responsive UI:

1. Set Up a New Project or Use an Existing One

o Open your Flutter project and navigate to lib/main.dart.

2. Replace Code

o Replace the contents of main.dart with the above code.

3. Run the App

o Test the app on different screen sizes using the emulator or a physical device.

4. Output:

o For smaller screens, the text will show "Mobile View."

o For larger screens (like tablets or desktops), the text will change to "Tablet or
Desktop View."

3(b): Implement Media Queries and Breakpoints for Responsiveness

Objective: Use media queries to create breakpoints that adjust UI components based on screen size.

Code Example:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

home: MediaQueryExample(),

);

class MediaQueryExample extends StatelessWidget {

@override
Widget build(BuildContext context) {

double screenWidth = MediaQuery.of(context).size.width;

return Scaffold(

appBar: AppBar(

title: Text("Media Queries Example"),

),

body: Center(

child: screenWidth < 600

? Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

Icon(Icons.phone_android, size: 50, color: Colors.green),

Text("Small Screen", style: TextStyle(fontSize: 18)),

],

: Row(

mainAxisAlignment: MainAxisAlignment.center,

children: [

Icon(Icons.desktop_mac, size: 50, color: Colors.blue),

SizedBox(width: 10),

Text("Large Screen", style: TextStyle(fontSize: 18)),

],

),

),

);

Step-by-Step Procedure for Media Queries and Breakpoints:

1. Set Up a New Project or Continue Editing


o Use the same project as before or create a new one.

2. Replace Code

o Replace the main.dart contents with the above code.

3. Run the App

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.

Experiment 4: Navigation Between Screens

4(a): Set Up Navigation Between Different Screens Using Navigator

Objective: Learn to navigate between two screens using Flutter's Navigator class.

Code Example:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

home: FirstScreen(),

);

class FirstScreen extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(

title: Text("First Screen"),

),

body: Center(

child: ElevatedButton(

onPressed: () {

Navigator.push(

context,

MaterialPageRoute(builder: (context) => SecondScreen()),

);

},

child: Text("Go to Second Screen"),

),

),

);

class SecondScreen extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text("Second Screen"),

),

body: Center(

child: ElevatedButton(

onPressed: () {

Navigator.pop(context);

},

child: Text("Back to First Screen"),


),

),

);

Step-by-Step Procedure for Simple Navigation:

1. Set Up the Project

o Create a new project or use an existing one.

2. Edit main.dart

o Replace the existing code with the provided example.

3. Run the Application

o Start the app on an emulator or device.

4. Output:

o A button on the first screen navigates to the second screen.

o A button on the second screen navigates back to the first screen.

4(b): Implement Navigation with Named Routes

Objective: Set up navigation using named routes for better scalability and maintainability.

Code Example:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

initialRoute: '/',

routes: {

'/': (context) => FirstScreen(),


'/second': (context) => SecondScreen(),

},

);

class FirstScreen extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text("First Screen"),

),

body: Center(

child: ElevatedButton(

onPressed: () {

Navigator.pushNamed(context, '/second');

},

child: Text("Go to Second Screen"),

),

),

);

class SecondScreen extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text("Second Screen"),


),

body: Center(

child: ElevatedButton(

onPressed: () {

Navigator.pop(context);

},

child: Text("Back to First Screen"),

),

),

);

Step-by-Step Procedure for Named Routes:

1. Set Up the Project

o Use the same project or create a new one.

2. Edit main.dart

o Replace the code with the named routes example.

3. Run the Application

o Test the navigation using the buttons.

4. Output:

o The first screen navigates to the second using named routes.

o The second screen navigates back to the first screen.

Experiment 5: Stateful and Stateless Widgets, State Management

5(a): Learn About Stateful and Stateless Widgets

Objective: Understand the differences between Stateful and Stateless widgets by implementing
both.

Stateless Widget Example:


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

home: StatelessExample(),

);

class StatelessExample extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text("Stateless Widget"),

),

body: Center(

child: Text("This is a Stateless Widget!", style: TextStyle(fontSize: 20)),

),

);

Stateful Widget Example:

import 'package:flutter/material.dart';

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


class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

home: StatefulExample(),

);

class StatefulExample extends StatefulWidget {

@override

_StatefulExampleState createState() => _StatefulExampleState();

class _StatefulExampleState extends State<StatefulExample> {

int _counter = 0;

void _incrementCounter() {

setState(() {

_counter++;

});

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text("Stateful Widget"),

),

body: Center(
child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

Text("You have pressed the button this many times:", style: TextStyle(fontSize: 16)),

Text("$_counter", style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),

],

),

),

floatingActionButton: FloatingActionButton(

onPressed: _incrementCounter,

child: Icon(Icons.add),

),

);

Step-by-Step Procedure:

1. Set Up a New Project

o Replace main.dart with the code for Stateless or Stateful widgets.

2. Run the App

o Observe how Stateless widgets remain static while Stateful widgets allow updates to
the UI.

3. Output:

o Stateless: Displays a static message.

o Stateful: Button click increments a counter and updates the UI.

5(b): Implement State Management Using setState and Provider

import 'package:flutter/material.dart';

import 'package:provider/provider.dart';
// Define the Counter class that extends ChangeNotifier

class Counter with ChangeNotifier {

int _count = 0;

int get count => _count;

void increment() {

_count++;

notifyListeners(); // Notify listeners of state change

void main() {

runApp(

ChangeNotifierProvider(

create: (context) => Counter(),

child: MyApp(),

),

);

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

home: CounterScreen(),

);

class CounterScreen extends StatelessWidget {


@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text("Provider State Management"),

),

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

Text(

'Count:',

style: TextStyle(fontSize: 24),

),

SizedBox(height: 10),

Text(

'${Provider.of<Counter>(context).count}',

style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold),

),

],

),

),

floatingActionButton: FloatingActionButton(

onPressed: () {

Provider.of<Counter>(context, listen: false).increment();

},

child: Icon(Icons.add),

),

);

}
Steps to Run

1. Copy this code into your main.dart file.

2. Open your terminal and 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.

6(a): Create Custom Widgets

Custom widgets are reusable UI components that encapsulate design and logic.

Code Example: Custom Widget and Styling

import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

// Custom Button Widget

class CustomButton extends StatelessWidget {

final String text;

final VoidCallback onPressed;

CustomButton({required this.text, required this.onPressed});

@override

Widget build(BuildContext context) {

return ElevatedButton(

style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(context).primaryColor, // Use theme color (updated)

padding: EdgeInsets.symmetric(horizontal: 20, vertical: 15),

shape: RoundedRectangleBorder(

borderRadius: BorderRadius.circular(12),

),

),

onPressed: onPressed,

child: Text(

text,

style: TextStyle(

fontSize: 18,

color: Colors.white,

),

),

);

// Main App

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

theme: ThemeData(

primaryColor: Colors.deepPurple, // Define a custom theme color

textTheme: TextTheme(

bodyLarge: TextStyle(fontSize: 18, color: Colors.black87), // Updated to 'bodyLarge'

bodyMedium: TextStyle(fontSize: 16, color: Colors.black54), // Updated to 'bodyMedium'

),

),

home: HomeScreen(),
);

class HomeScreen extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text("Custom Widgets & Themes"),

),

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

Text(

"Click the Custom Button",

style: Theme.of(context).textTheme.bodyLarge, // Updated to 'bodyLarge'

),

SizedBox(height: 20),

CustomButton(

text: "Press Me",

onPressed: () {

ScaffoldMessenger.of(context).showSnackBar(

SnackBar(content: Text("Custom Button Pressed!")),

);

},

),

],

),

),
);

How to Run

1. Copy the code into your main.dart file.

2. Run:

3. flutter run

4. Click the custom button and see the interaction.

Output

 A simple UI with a custom-styled button.

 The button displays a snackbar message when clicked.

Experiment 7: Design a Form with Input Fields and Implement Form Validation

In this experiment, we will:

1. Create a form with various input fields.

2. Implement form validation and error handling.

Code Example for Form with Validation

import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

home: Scaffold(
appBar: AppBar(

title: Text('Form Validation Example'),

),

body: Padding(

padding: const EdgeInsets.all(16.0),

child: FormExample(),

),

),

);

class FormExample extends StatefulWidget {

@override

_FormExampleState createState() => _FormExampleState();

class _FormExampleState extends State<FormExample> {

// Create a global key to manage the form state

final _formKey = GlobalKey<FormState>();

// Create controllers for text fields

final TextEditingController _nameController = TextEditingController();

final TextEditingController _emailController = TextEditingController();

// Validation function for name

String? _validateName(String? value) {

if (value == null || value.isEmpty) {

return 'Name is required';

return null;
}

// Validation function for email

String? _validateEmail(String? value) {

if (value == null || value.isEmpty) {

return 'Email is required';

} else if (!RegExp(r'^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]+').hasMatch(value)) {

return 'Enter a valid email address';

return null;

// Submit the form

void _submitForm() {

if (_formKey.currentState!.validate()) {

// If form is valid, show a success message

ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Form Submitted')));

} else {

// If form is not valid, show an error message

ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Form has errors')));

@override

Widget build(BuildContext context) {

return Form(

key: _formKey,

child: Column(

crossAxisAlignment: CrossAxisAlignment.start,

children: [

// Name Text Field


TextFormField(

controller: _nameController,

decoration: InputDecoration(labelText: 'Name'),

validator: _validateName,

),

SizedBox(height: 16),

// Email Text Field

TextFormField(

controller: _emailController,

decoration: InputDecoration(labelText: 'Email'),

validator: _validateEmail,

),

SizedBox(height: 16),

// Submit Button

ElevatedButton(

onPressed: _submitForm,

child: Text('Submit'),

),

],

),

);

Explanation:

1. Form Setup:

o A Form widget is created with a GlobalKey<FormState>, which allows us to manage


the state of the form.

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:

 Name: Requires the field to be non-empty.

 Email: Requires the field to be a valid email format.

o If the form is valid, it proceeds to the submission logic.

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:

1. Copy this code into your main.dart file.

2. Run the app using:

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.

 If everything is correct, a success message (Form Submitted) will be displayed.

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.

Experiment 8: Add Animations to UI Elements using Flutter's Animation Framework

Code:

import 'package:flutter/material.dart';
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

debugShowCheckedModeBanner: false,

home: AnimatedIconDemo(),

);

class AnimatedIconDemo extends StatefulWidget {

@override

_AnimatedIconDemoState createState() => _AnimatedIconDemoState();

class _AnimatedIconDemoState extends State<AnimatedIconDemo> with


SingleTickerProviderStateMixin {

late AnimationController _controller;

bool isPlaying = false;

@override

void initState() {

super.initState();

_controller = AnimationController(

vsync: this,

duration: Duration(seconds: 1), // Duration of the animation (1 second)

);

}
@override

void dispose() {

_controller.dispose(); // Dispose the controller to avoid memory leaks

super.dispose();

void _toggleIcon() {

setState(() {

isPlaying = !isPlaying; // Toggle between play and pause

isPlaying ? _controller.forward() : _controller.reverse(); // Start or reverse animation

});

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text("Animated Icon Demo"),

),

body: Center(

child: IconButton(

iconSize: 100, // Set the size of the icon

icon: AnimatedIcon(

icon: AnimatedIcons.play_pause, // Predefined play/pause animation

progress: _controller, // Use the controller's progress to control the animation

),

onPressed: _toggleIcon, // Toggle the animation on button press

),

),

);
}

Explanation of the Code:

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:

o Uses AnimatedIcons.play_pause which is a predefined animation that toggles


between a "play" and a "pause" icon.

o The progress parameter is linked to the AnimationController, which drives the


animation's forward and reverse states.

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.

 When you tap on the icon:

o The icon animates from "play" to "pause" or vice versa, depending on the current
state.

o The animation completes in 1 second as defined by the AnimationController's


duration.

 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.

2. After clicking the icon:

o It will animate and change to the "Pause" icon.

o If clicked again, it will animate back to the "Play" icon.

The icon size is set to 100 and animates between the two states.
How to Run It:

1. Create a new Flutter project or use an existing one.

2. Replace the code in main.dart with the code provided above.

3. Run the app using the following command:

4. flutter run

You should see the icon changing smoothly between "play" and "pause" when clicked, demonstrating
an animated icon in action.

Experiment 9: Fetch Data from a REST API and Display It

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 {

final int id;

final String title;

final String body;

Post({required this.id, required this.title, required this.body});

// Factory constructor to create a Post from JSON

factory Post.fromJson(Map<String, dynamic> json) {

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';

import 'package:http/http.dart' as http;

import 'post.dart'; // Import the Post model

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'API Data Fetch Example',

theme: ThemeData(primarySwatch: Colors.blue),

home: PostsScreen(),

);

class PostsScreen extends StatefulWidget {

@override
_PostsScreenState createState() => _PostsScreenState();

class _PostsScreenState extends State<PostsScreen> {

late Future<List<Post>> _posts;

@override

void initState() {

super.initState();

_posts = fetchPosts(); // Fetch data when the app starts

// Function to fetch data from the API

Future<List<Post>> fetchPosts() async {

final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));

if (response.statusCode == 200) {

// Parse the JSON response and convert it into a list of Post objects

List jsonResponse = json.decode(response.body);

return jsonResponse.map((post) => Post.fromJson(post)).toList();

} else {

throw Exception('Failed to load posts');

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(title: Text('Posts from API')),

body: FutureBuilder<List<Post>>(

future: _posts,
builder: (context, snapshot) {

if (snapshot.connectionState == ConnectionState.waiting) {

return Center(child: CircularProgressIndicator()); // Loading indicator

} else if (snapshot.hasError) {

return Center(child: Text('Error: ${snapshot.error}'));

} else if (!snapshot.hasData || snapshot.data!.isEmpty) {

return Center(child: Text('No data found'));

} else {

// Display data in a ListView

return ListView.builder(

itemCount: snapshot.data!.length,

itemBuilder: (context, index) {

Post post = snapshot.data![index];

return ListTile(

title: Text(post.title, style: TextStyle(fontWeight: FontWeight.bold)),

subtitle: Text(post.body),

);

},

);

},

),

);

Steps to Run the Code:

 Install Dependencies:
Ensure the http package is added to your pubspec.yaml file, and then run:

 flutter pub get

 Run the App:


Execute the following command to run the app:
 flutter 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.

You might also like