0% found this document useful (0 votes)
0 views

Android projects

File of android development projects

Uploaded by

surjeetkaran777
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Android projects

File of android development projects

Uploaded by

surjeetkaran777
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 65

A60205222153

1. Create a Dart function performOperation that accepts two integers and a


lambda function as parameters. The lambda function should define the
operation to be performed on the two integers (e.g., addition, subtraction,
multiplication). Demonstrate this by passing different lambda functions for
various operations like addition, subtraction, etc.

Code:-
void main() {

int performOperation(int a, int b, int Function(int, int) operation)

{ return operation(a, b);

int add(int x, int y) => x + y;

int subtract(int x, int y) => x - y;

int multiply(int x, int y) => x * y;

int divide(int x, int y) => y != 0 ? x ~/ y : 0;

print('Addition: ${performOperation(10, 5, add)}'); print('Subtraction:

${performOperation(10, 5, subtract)}'); print('Multiplication:

${performOperation(10, 5, multiply)}'); print('Division:

${performOperation(10, 5, divide)}');

print('Modulus: ${performOperation(10, 3, (x, y) => x % y)}'); print('Power:

${performOperation(2, 3, (x, y) => x * x * x)}');}

1
A60205222153

Output:-
Addition: 15

Subtraction: 5

Multiplication: 50

Division: 2

Modulus: 1

Power: 8

2
A60205222153

2. Implement a higher-order function makeCounter that returns a function


(counter) which increments a counter each time it is called. The returned
function should return the current count value. Demonstrate how to create a
counter and call it multiple times to show the incrementing count.

Code:-
void main() {

Function makeCounter()
{ int count = 0;
return ()
{ count += 1;
return count;
};
}

var counter = makeCounter();


print(counter());
print(counter());
print(counter());

var anotherCounter = makeCounter();


print(anotherCounter());
print(anotherCounter());
}

Output:-
1

3
A60205222153

3. Write a Dart function sumList that takes a list of integers as a parameter and
returns the sum of all elements in the list. Call the function with different
lists and print the results.

Code:-
void main() {
int sumList(List<int> numbers)
{ int sum = 0;
for (int number in numbers)
{ sum += number;
}
return sum;
}

// Test cases
List<int> list1 = [1, 2, 3, 4, 5];
List<int> list2 = [10, 20, 30, 40];
List<int> list3 = [];

print(sumList(list1)); // Output: 15 print(sumList(list2));


// Output: 100 print(sumList(list3)); // Output: 0
}

Output:-
15
100
0

4
A60205222153

4. Create a class ShoppingList that has a final list property called items. Initialize
the list with a set of grocery items. Write a method to add more items to the
list and display all items. What happens if you try to reassign the items
property to a new list?

Code:-
class ShoppingList
{ final List<String>
items;

ShoppingList() : items = ['Milk', 'Eggs', 'Bread', 'Butter'];

void addItem(String item) {


items.add(item);
}

void displayItems()
{ print('Shopping List:');
for (var item in items) {
print(item);
}
}
}

void main() {
var shoppingList = ShoppingList();
shoppingList.displayItems();
shoppingList.addItem('Cheese');
shoppingList.addItem('Tomatoes');
shoppingList.displayItems();
}

5
A60205222153

•Since the items property is marked as final, you cannot reassign it to a


new list. Attempting to do so (e.g., shoppingList.items = ['New list'];)
will cause a compilation error in Dart. The final keyword ensures that
the reference to the list cannot be changed after initialization,
although the contents of the list can still be modified (like adding
items).

Output:-
Shopping List:

Milk

Eggs

Bread Butter

Shopping List:

Milk

Eggs

Bread

Butter

Cheese

Tomatoes

6
A60205222153

5. Create a class Playlist that has a list property song (list of strings).
Include methods to:

Add a song to the playlist.

Remove a song from the playlist.

Get the total number of songs. Display all songs in the playlist.

Code:-
class Playlist
{ List<String> songs;

Playlist() : songs = [];

void addSong(String song) {


songs.add(song);
print('Added: $song');
}

void removeSong(String song) {


if (songs.remove(song))
{ print('Removed: $song');
} else {
print('$song not found in the playlist.');
}
}

int totalSongs()
{ return
songs.length;
}

void displaySongs() {
if (songs.isEmpty) {
print('The playlist is empty.');
} else {
7
A60205222153

print('Playlist:');
for (var song in songs) {
print('- $song');
}
}
}
}

void main() { var


playlist = Playlist();

playlist.displaySongs();

playlist.addSong('Shape of You'); playlist.addSong('Blinding


Lights'); playlist.addSong('Levitating');

playlist.displaySongs();

print('Total Songs: ${playlist.totalSongs()}');

playlist.removeSong('Blinding Lights'); playlist.removeSong('Dance


Monkey');

playlist.displaySongs();
print('Total Songs: ${playlist.totalSongs()}');
}

8
A60205222153

Output:-

The playlist is empty.


Added: Shape of You
Added: Blinding Lights
Added: Levitating Playlist:
- Shape of You
- Blinding Lights
- Levitating
Total Songs:
3
Removed: Blinding Lights Dance
Monkey not found in the playlist.
Playlist:
- Shape of You
- Levitating
Total Songs:
2

9
A60205222153

6. Write a program which includes different combinations of parameter in


a single function parameter

➢ Positional+ Optional Named


➢ Positional+ Optional
➢ Positional+ Default
➢ Optional Named + Default
➢ Optional Positional + Default ➢ Optional Named + Optional Positional If
any combination does not work give reason why.
Code:-
void main() {
// Positional + Optional Named print('\
n1. Positional + Optional Named');
positionalAndOptionalNamed(10, value2: 20);

// Positional + Optional print('\n2.


Positional + Optional');
positionalAndOptional(10);

// Positional + Default print('\n3.


Positional + Default');
positionalAndDefault(10);

// Optional Named + Default print('\n4.


Optional Named + Default');
optionalNamedAndDefault(value1: 10, value2: 20);

// Optional Positional + Default print('\n5.


Optional Positional + Default');
optionalPositionalAndDefault(10);

// Optional Named + Optional Positional print('\n6.


Optional Named + Optional Positional');
optionalNamedAndOptionalPositional(10, value2: 20);
}

10
A60205222153

// 1. Positional + Optional Named void


positionalAndOptionalNamed(int value1, {int? value2})
{ print('Value 1: $value1');
print('Value 2: ${value2 ?? "Not Provided"}');
}

// 2. Positional + Optional void


positionalAndOptional(int value1, [int? value2])
{ print('Value 1: $value1');
print('Value 2: ${value2 ?? "Not Provided"}');
}

// 3. Positional + Default void positionalAndDefault(int


value1, [int value2 = 100]) {
print('Value 1: $value1');
print('Value 2: $value2');
}

// 4. Optional Named + Default void


optionalNamedAndDefault({int value1 = 10, int value2 = 20})
{ print('Value 1: $value1');
print('Value 2: $value2');
}

// 5. Optional Positional + Default void


optionalPositionalAndDefault([int value1 = 10, int value2 = 20])
{ print('Value 1: $value1');
print('Value 2: $value2');
}

// 6. Optional Named + Optional Positional void


optionalNamedAndOptionalPositional([int? value1, {int? value2}])
{ print('Value 1: ${value1 ?? "Not Provided"}');
print('Value 2: ${value2 ?? "Not Provided"}');}

11
A60205222153

Output:-
1. Positional + Optional Named
Value 1: 10
Value 2: 20

2. Positional + Optional
Value 1: 10
Value 2: Not Provided

3. Positional + Default
Value 1: 10
Value 2: 100

4. Optional Named + Default


Value 1: 10
Value 2: 20

5. Optional Positional + Default


Value 1: 10
Value 2: 20

6. Optional Named + Optional Positional


Value 1: 10
Value 2: 20

12
A60205222153

7. Implement a class Employee that has private properties:


_id (int)
_name (String)
_salary (double)
Use getters and setters to access and modify the Employee details. Write a
Dart program to create an Employee object, update its details using setters,
and display the information using getters.

Code:-
class Employee
{ int _id;
String _name; double
_salary;

Employee(this._id, this._name, this._salary);

int get id => _id;


set id(int value) {
if (value > 0) _id = value;
}

String get name => _name;


set name(String value) {
if (value.isNotEmpty) _name = value;
}

double get salary => _salary;


set salary(double value) {
if (value >= 0) _salary = value;
}

void displayInfo()
{ print('Employee Details:');
print('ID: $_id');

13
A60205222153

print('Name: $_name');
print('Salary: \$$_salary');
}
}

void main() {
var emp = Employee(1, 'John Doe', 50000);

emp.displayInfo();

emp.id = 2;
emp.name = 'Jane Smith';
emp.salary = 60000;

emp.displayInfo();

emp.id = -1; emp.name


= ''; emp.salary = -500;

emp.displayInfo();
}

14
A60205222153

Output:-
Employee Details:

ID: 1

Name: John Doe

Salary: $50000.0

Employee Details: ID:

Name: Jane Smith

Salary: $60000.0

Employee Details: ID:

Name: Jane Smith

Salary: $60000.0

15
A60205222153

8. Create “Hello World” application. That will display “Hello World” in the
middle of the screen using TextView Widget in the red color, use style property
of Text Widget.

Code:-
import 'package:flutter/material.dart';

void main() {

runApp(HelloWorldApp());

class HelloWorldApp extends StatelessWidget {

@override

Widget build(BuildContext context)

{ return MaterialApp(

home: Scaffold(

body:

Center( child:

Text( 'Hello

World', style:

TextStyle(

color: Colors.red,

fontSize: 24,

fontWeight: FontWeight.bold,

),

),

),
16
A60205222153

)}});

17
A60205222153

Output:-

18
A60205222153

9. Create a screen with a Container widget that

• Has a width of 300 pixels and a height of 300 pixels.

• The container should have a background color of green.

• Inside the container, place two widgets:

➢ A Text widget with the text "Top-left" aligned to the top left.

➢ A Text widget with the text "Bottom-right" aligned to the bottom right.

➢ An Icon at center of the container

• Both texts should be white with font size 16.

• Use the alignment property of the Container to align the texts.

Code:-
import 'package:flutter/material.dart';

void main() {

runApp(ContainerApp());

class ContainerApp extends StatelessWidget {

@override

Widget build(BuildContext context)

{ return MaterialApp(

home:

Scaffold( appBar:

AppBar(

title: Text('Container Example'),

),

body: Center( child:

19
A60205222153

Container( width:

11
0
A60205222153

300, height: 300,

color: Colors.green,

child: Stack(

children: [

Align(

alignment: Alignment.topLeft,

child: Text(

'Top-left',

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

),

),

Align(

alignment: Alignment.bottomRight,

child: Text(

'Bottom-right',

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

),

),

Center( child: Icon(

Icons.star,

color: Colors.white,

size: 50,

),),

],

11
1
A60205222153

),),),),);

Output:-

20
A60205222153

10. Create sample application with login module. (Check username and
password) On successful login, Change TextView “Login Successful”. And on
failing login, alert user using SnackBar “Login fail”.

Code:-
import 'package:flutter/material.dart';

void main() {

runApp(LoginApp());

class LoginApp extends StatelessWidget {

@override

Widget build(BuildContext context)

{ return MaterialApp(

home: LoginScreen(),

);

class LoginScreen extends StatefulWidget {

@override

_LoginScreenState createState() => _LoginScreenState();

class _LoginScreenState extends State<LoginScreen> {

final TextEditingController usernameController = TextEditingController();

21
A60205222153

final TextEditingController passwordController = TextEditingController();

void login() {

String username = usernameController.text;

String password = passwordController.text;

if (username == 'admin' && password == 'password123') {

// Successful login

ScaffoldMessenger.of(context).showSnackBar( Sna

ckBar(

content: Text('Login Successful'),

backgroundColor: Colors.green,

),

);

} else {

// Failed login

ScaffoldMessenger.of(context).showSnackBar( Sna

ckBar(

content: Text('Login Failed'),

backgroundColor: Colors.red,

),

);

22
A60205222153

@override

Widget build(BuildContext context)

{ return Scaffold(

appBar: AppBar(

title: Text('Login Screen'),

),

body: Padding(

padding: const EdgeInsets.all(16.0),

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

TextField(

controller: usernameController,

decoration:

InputDecoration( labelText:

'Username',

border: OutlineInputBorder(),

),

),

SizedBox(height: 10), TextField(

controller: passwordController,

obscureText: true,

decoration:
23
A60205222153

InputDecoration( labelText:

'Password',

24
A60205222153

border: OutlineInputBorder(),

),

),

SizedBox(height: 20),

ElevatedButton( onPr

essed: login, child:

Text('Login'),

),

SizedBox(height: 20), Text(

'Login Status: ${usernameController.text.isNotEmpty ? 'Checking...' :


'Enter Username and Password'}',

style: TextStyle(fontSize: 16),

),

],

),

),

);

25
A60205222153

Output:-

26
A60205222153

11. Create login application where you will have to validate usename and
passwords till the username and password is not validated, login button should
remain disabled. Code:- import 'package:flutter/material.dart'; void main() {
runApp(LoginApp());

class LoginApp extends StatelessWidget {

@override

Widget build(BuildContext context)

{ return MaterialApp(

home: LoginScreen(),

);

class LoginScreen extends StatefulWidget {

@override

_LoginScreenState createState() => _LoginScreenState();

class _LoginScreenState extends State<LoginScreen> {

final TextEditingController usernameController = TextEditingController();

final TextEditingController passwordController = TextEditingController();

bool isLoginButtonEnabled = false;

void _validateInputs() {

String username = usernameController.text; String

password = passwordController.text;

27
A60205222153

setState(() {

isLoginButtonEnabled = username.isNotEmpty && password.isNotEmpty;

});

void login() {

String username = usernameController.text;

String password = passwordController.text;

if (username == 'admin' && password == 'password123') {

// Successful login

ScaffoldMessenger.of(context).showSnackBar( Sna

ckBar(

content:

Text('Login Successful'),

backgroundColor: Colors.green,

),

);

} else {

// Failed login

ScaffoldMessenger.of(context).showSnackBar( Sna

ckBar(

content: Text('Login Failed'),

backgroundColor: Colors.red,

),
28
A60205222153

);

@override

Widget build(BuildContext context)

{ return Scaffold(

appBar: AppBar(

title: Text('Login Screen'),

),

body: Padding(

padding: const EdgeInsets.all(16.0),

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

TextField(

controller: usernameController,

decoration:

InputDecoration( labelText:

'Username',

border: OutlineInputBorder(),

),

onChanged: (_) => _validateInputs(),

),

SizedBox(height: 10), TextField(


29
A60205222153

controller: passwordController,

obscureText: true,

decoration:

InputDecoration( labelText:

'Password',

border: OutlineInputBorder(),

),

onChanged: (_) => _validateInputs(),

),

SizedBox(height: 20),

ElevatedButton(

onPressed: isLoginButtonEnabled ? login : null,

child: Text('Login'),

style: ElevatedButton.styleFrom(

primary: isLoginButtonEnabled ? Colors.blue : Colors.grey,

),

),

],

),

21
0
A60205222153

Output:

30
A60205222153

12. Design and implement a Flutter application with the following


specifications:

➢ The app should display a list of items (e.g., a shopping list or task list) in the
main body.

➢ Add a Floating Action Button at the bottom-right corner of the screen.

➢ When the FAB is tapped:

o Open a dialog with a TextField to enter a new item.


o Include "Cancel" and "Add" buttons in the dialog.

➢ If the user taps "Add" after entering text, the new item should be added to
the list.

➢ If the user taps "Cancel" or dismisses the dialog, no changes should be made
to the list.

➢ Ensure the list is scrollable if it grows beyond the screen size.

➢ Add a delete feature: Long-pressing an item in the list should show a


confirmation dialog. If confirmed, remove the item from the list.

Code:-
import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context)

{ return MaterialApp(

31
A60205222153

home: ShoppingListScreen(),

);

class ShoppingListScreen extends StatefulWidget {

@override

_ShoppingListScreenState createState() => _ShoppingListScreenState();

class _ShoppingListScreenState extends State<ShoppingListScreen>

{ List<String> items = [];

void _addItem(String item)

{ setState(() { items.add(item);

});

void _removeItem(int index)

{ setState(() {

items.removeAt(index);

});

void _showAddItemDialog() {

final TextEditingController textController = TextEditingController();

showDialog(

32
A60205222153

context: context,

builder: (BuildContext context)

{ return AlertDialog(

title: Text('Add New Item'),

content:

TextField( controller:

textController,

decoration: InputDecoration(hintText: 'Enter item name'),

),

actions: <Widget>[

TextButton( onPresse

d: () {

Navigator.of(context).pop();

},

child: Text('Cancel'),

),

TextButton( onPr

essed: () {

String newItem = textController.text; if

(newItem.isNotEmpty) {

_addItem(newItem);

Navigator.of(context).pop();

33
A60205222153

},

34
A60205222153

child: Text('Add'),

),

],

);

},

);

void _showDeleteItemDialog(int index) {

showDialog(

context: context,

builder: (BuildContext context)

{ return AlertDialog(

title: Text('Confirm Delete'),

content: Text('Are you sure you want to delete this item?'),

actions: <Widget>[

TextButton( onPr

essed: () {

Navigator.of(context).pop();

},

child: Text('Cancel'),

),

35
A60205222153

TextButton( onPr

essed: () {

_removeItem(index);

Navigator.of(context).pop();

},

child: Text('Delete'),

),

],

);

},

);

@override

Widget build(BuildContext context)

{ return Scaffold(

appBar: AppBar(

title: Text('Shopping List'),

),

body:

ListView.builder( itemCount:

items.length, itemBuilder:

(context, index) { return

ListTile(

36
A60205222153

title: Text(items[index]),

onLongPress: () {

_showDeleteItemDialog(index);

}, );

},

),

floatingActionButton: FloatingActionButton(

onPressed:

_showAddItemDialog,

child: Icon(Icons.add),

),);

Output:

37
A60205222153

13. Create a flutter application to add custom fonts, image (using image
network, image asset) and theme in your app (write the code of pubspec.yaml
also the steps included+ for fonts and images).

Code:-
import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context)

{ return MaterialApp(

theme:

ThemeData( primaryColor:

Colors.blue, textTheme:

TextTheme( bodyText1:

TextStyle( fontFamily:

'CustomFont', fontSize: 18,

),

),

),

home: MyHomePage(),

);

38
A60205222153

class MyHomePage extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold( appBar: AppBar(

title: Text('Custom Fonts, Images, and Themes'),

),

body:

Center( child:

Column(

mainAxisAlignment: MainAxisAlignment.center,

children: <Widget>[

Image.asset('assets/images/logo.png', width: 100, height: 100)

Image.network(

'https://www.example.com/image.jpg',

width: 100,

height: 100,

),

Text(

'Hello, Flutter!', style:

TextStyle( fontFamily:

'CustomFont', fontSize:

24,

39
A60205222153

color: Colors.blue,

31
0
A60205222153

),

),

],

),

),

);

Output:-

31
1
A60205222153

14. Create an application that will pass two number using Text View to the next
screen, and on the next screen display sum of that number.

Code:-
import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context)

{ return MaterialApp(

title: 'Number Passing App',

theme: ThemeData(primarySwatch: Colors.blue),

home: InputScreen(),

);

class InputScreen extends StatefulWidget {

@override

_InputScreenState createState() => _InputScreenState();

class _InputScreenState extends State<InputScreen> {

final TextEditingController num1Controller = TextEditingController();

final TextEditingController num2Controller = TextEditingController();


40
A60205222153

@override

Widget build(BuildContext context)

{ return Scaffold(

appBar: AppBar(title: Text('Enter Numbers')),

body: Padding(

padding: const EdgeInsets.all(16.0),

child: Column(

children: [

TextField(

controller: num1Controller,

keyboardType: TextInputType.number,

decoration:

InputDecoration( labelText: 'Enter first

number',

border: OutlineInputBorder(),

),

),

SizedBox(height: 16),

TextField(

controller: num2Controller,

keyboardType: TextInputType.number,

decoration: InputDecoration(

41
A60205222153

labelText: 'Enter second number',

border: OutlineInputBorder(),

),

),

SizedBox(height: 16),

ElevatedButton( onPres

sed: () {

final num1 = double.tryParse(num1Controller.text) ?? 0;

final num2 = double.tryParse(num2Controller.text) ?? 0;

Navigator.push(

context,

MaterialPageRoute(

builder: (context) => ResultScreen(num1: num1, num2: num2),

),

);

},

child: Text('Calculate Sum'),

),

],

),

),

);

42
A60205222153

class ResultScreen extends StatelessWidget {

final double num1;

final double num2;

ResultScreen({required this.num1, required this.num2});

@override

Widget build(BuildContext context)

{ final sum = num1 + num2; return

Scaffold(

appBar: AppBar(title: Text('Result')),

body: Center(

child: Text(

'The sum of $num1 and $num2 is $sum',

style: TextStyle(fontSize: 24),

textAlign: TextAlign.center,

),

),

);

43
A60205222153

Output:-

44
A60205222153

15. Create a Flutter app with two screens: Screen 1 has a list of three buttons
labeled "Button1", "Button2", and "Button3". When a button is clicked, the app
navigates to Screen 2 using Navigator.push() with MaterialPageRoute and
passes the item name (e.g., "name1") as a parameter. Screen 2: Displays the
item name passed from the first screen and has a back button to return to
Screen 1.

Code:-
import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context)

{ return MaterialApp(

title: 'Number Passing App',

theme: ThemeData(primarySwatch: Colors.blue),

home: InputScreen(),

);

class InputScreen extends StatefulWidget {

@override

_InputScreenState createState() => _InputScreenState();

45
A60205222153

class _InputScreenState extends State<InputScreen> {

final TextEditingController num1Controller = TextEditingController();

final TextEditingController num2Controller = TextEditingController();

@override

Widget build(BuildContext context)

{ return Scaffold(

appBar: AppBar(title: Text('Enter Numbers')),

body: Padding(

padding: const EdgeInsets.all(16.0),

child: Column(

children: [

TextField(

controller: num1Controller,

keyboardType: TextInputType.number,

decoration:

InputDecoration( labelText: 'Enter first

number',

border: OutlineInputBorder(),

),

),

SizedBox(height: 16),

TextField(

46
A60205222153

controller: num2Controller,

keyboardType:

TextInputType.number,

decoration:

InputDecoration( labelText:

'Enter second number', border:

OutlineInputBorder(),

),

),

SizedBox(height: 16),

ElevatedButton( onPres

sed: () {

final num1 = double.tryParse(num1Controller.text) ?? 0;

final num2 = double.tryParse(num2Controller.text) ?? 0;

Navigator.push(

context,

MaterialPageRoute(

builder: (context) => ResultScreen(num1: num1, num2: num2),

),

);

},

child: Text('Calculate Sum'),

),

],
47
A60205222153

),

),

);

class ResultScreen extends StatelessWidget {

final double num1;

final double num2;

ResultScreen({required this.num1, required this.num2});

@override

Widget build(BuildContext context)

{ final sum = num1 + num2;

return Scaffold(

appBar: AppBar(title: Text('Result')),

body: Center(

child: Text(

'The sum of $num1 and $num2 is $sum',

style: TextStyle(fontSize: 24),

textAlign: TextAlign.center,

),

),);

48
A60205222153

Output:-

49
A60205222153

16. Create an application where users can add, delete, and mark tasks as

completed in a to-do list using shared preferences.

Code:-
import 'package:flutter/material.dart';

import 'package:shared_preferences/shared_preferences.dart';

import 'dart:convert'; void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context)

{ return MaterialApp(

title: 'To-Do List',

theme: ThemeData(primarySwatch: Colors.blue),

home: TodoListScreen(),

);

class TodoListScreen extends StatefulWidget {

@override

_TodoListScreenState createState() => _TodoListScreenState();

50
A60205222153

class _TodoListScreenState extends State<TodoListScreen> {

final TextEditingController _taskController = TextEditingController();

List<Map<String, dynamic>> _tasks = [];

@override

void initState() {

super.initState();

_loadTasks();

Future<void> _loadTasks() async {

final prefs = await SharedPreferences.getInstance();

final String? tasksString = prefs.getString('tasks');

if (tasksString != null)

{ setState(() {

_tasks = List<Map<String, dynamic>>.from(json.decode(tasksString));

});

Future<void> _saveTasks() async {

final prefs = await SharedPreferences.getInstance();

final String tasksString = json.encode(_tasks);

await prefs.setString('tasks', tasksString);

51
A60205222153

void _addTask(String taskName)

{ setState(() {

_tasks.add({'name': taskName, 'completed': false});

});

_saveTasks();

void _deleteTask(int index)

{ setState(() {

_tasks.removeAt(index);

});

_saveTasks();

void _toggleTaskCompletion(int index)

{ setState(() {

_tasks[index]['completed'] = !_tasks[index]['completed'];

});

_saveTasks();

@override

Widget build(BuildContext context)

{ return Scaffold(

appBar: AppBar(

52
A60205222153

title: Text('To-Do List'),

),

body:

Column( children

: [ Padding(

padding: const EdgeInsets.all(16.0),

child: Row(

children: [

Expanded( child

: TextField(

controller: _taskController,

decoration:

InputDecoration( labelText:

'Enter a task', border:

OutlineInputBorder(),

),

),

),

SizedBox(width: 8), ElevatedButton(

onPressed: () {

if (_taskController.text.isNotEmpty) {

_addTask(_taskController.text);

_taskController.clear();

}
53
A60205222153

},

child: Text('Add'),

),

],

),

),

Expanded(

child:

ListView.builder( itemCount:

_tasks.length, itemBuilder:

(context, index) { final task =

_tasks[index]; return ListTile(

title: Text(

task['name'],

style: TextStyle(

decoration: task['completed']

? TextDecoration.lineThrough

: TextDecoration.none,

),

),

leading:

Checkbox( value:

task['completed'],

54
A60205222153

onChanged: (_) =>

_toggleTaskCompletion(index),

),

trailing:

IconButton( icon:

Icon(Icons.delete),

onPressed: () => _deleteTask(index),

),);

},

),),],),);

Output:-

55
A60205222153

17. Write a program to fetch remote data from a News API using the http
package and display the news headlines in a ListView.

Code:-
import 'package:flutter/material.dart';

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

import 'dart:convert';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context)

{ return MaterialApp(

title: 'News Headlines',

theme: ThemeData(primarySwatch: Colors.blue),

home: NewsListScreen(),

);

class NewsListScreen extends StatefulWidget {

@override

_NewsListScreenState createState() => _NewsListScreenState();

56
A60205222153

class _NewsListScreenState extends State<NewsListScreen>

{ List<dynamic> _newsHeadlines = [];

bool _isLoading = true;

@override

void initState() { super.initState();

_fetchNews();

Future<void> _fetchNews() async {

const String apiUrl =

'https://newsapi.org/v2/topheadlines?country=us&apiKey=YOUR_API_KEY'; //
Replace YOUR_API_KEY with a valid key

try {

final response = await http.get(Uri.parse(apiUrl));

if (response.statusCode == 200) {

final data = json.decode(response.body);

setState(() {

_newsHeadlines = data['articles'];

_isLoading = false;

});

} else {

throw Exception('Failed to load news');

} catch (e) {

setState(() {
57
A60205222153

_isLoading = false;

});

print('Error: $e');

@override

Widget build(BuildContext context)

{ return Scaffold(

appBar: AppBar(

title: Text('News Headlines'),

),

body: _isLoading

? Center(child: CircularProgressIndicator())

: ListView.builder(

itemCount: _newsHeadlines.length,

itemBuilder: (context, index) {

final newsItem = _newsHeadlines[index];

return ListTile(

title: Text(newsItem['title'] ?? 'No Title'),

subtitle: Text(newsItem['description'] ?? 'No Description'),

onTap: () {

if (newsItem['url'] != null) {

_openNewsUrl(context, newsItem['url']);

58
A60205222153

},

);

},

),

);

void _openNewsUrl(BuildContext context, String url) {

showDialog(

context: context,

builder: (context) =>

AlertDialog( title: Text('News

Link'),

content: Text('URL: $url'),

actions: [

TextButton(

onPressed: () => Navigator.pop(context),

child: Text('Close'),

),

],

)}});

59
A60205222153

Output:-

60

You might also like