0% found this document useful (0 votes)
16 views26 pages

Ai Lab

The document outlines the development of various Flutter applications, covering topics such as basic app creation, user management, navigation, and external library integration. It includes step-by-step algorithms and code snippets for setting up projects, implementing user interfaces, and managing data, including JSON and session management. Each section concludes with results demonstrating the successful implementation of the discussed features.

Uploaded by

noobvi631
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)
16 views26 pages

Ai Lab

The document outlines the development of various Flutter applications, covering topics such as basic app creation, user management, navigation, and external library integration. It includes step-by-step algorithms and code snippets for setting up projects, implementing user interfaces, and managing data, including JSON and session management. Each section concludes with results demonstrating the successful implementation of the discussed features.

Uploaded by

noobvi631
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/ 26

5.

Develop an application in android studio to understand the basics of the Flutter


application

AIM:

This application is to create a simple Flutter app that displays a list of items. This will help in
understanding the basic concepts of Flutter, including widget structure, state management,
and layout design. By following this guide, you will learn how to set up a Flutter
environment, create a new Flutter project, and implement a basic user interface.

Algorithm

1. Setup Environment:
o Install Flutter SDK and Android Studio.
o Install Flutter and Dart plugins in Android Studio.
2. Create New Flutter Project:
o Open Android Studio and create a new Flutter project named flutter_basic_app.
3. Design Application Structure:
o Create a main widget that runs the application.
o Define a stateless widget for the home screen that includes a ListView to display
items.
4. Implement the User Interface:
o Use a Scaffold widget for the app layout, including an AppBar.
o Create a list of items to display using ListView.builder().
5. Run the Application:
o Connect a physical device or start an Android emulator.
o Build and run the application to see the output.

Implementation

Step 1: Setup Environment

1. Install Flutter SDK:


o Follow the installation instructions for your OS from the Flutter installation guide.
2. Install Android Studio:
o Download and install Android Studio.
3. Install Flutter and Dart Plugins:
o In Android Studio, go to File > Settings > Plugins (or Preferences on macOS) and
install the Flutter plugin, which automatically includes the Dart plugin.

Step 2: Create New Flutter Project

1. Open Android Studio.


2. Click on New Flutter Project.
3. Choose Flutter Application and click Next.
4. Enter project details:
o Project name: flutter_basic_app
o Flutter SDK path: Ensure this points to your Flutter SDK.
o Click Next, then Finish.

Step 3: Design Application Structure

Replace the contents of the lib/main.dart file with the following code:

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

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {

return MaterialApp(
title: 'Flutter Basic App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatelessWidget {


final List<String> items = List.generate(20, (index) => 'Item $index');

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Basic Flutter App'),

),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index]),

);
},
),
);
}
}

Step 4: Run the Application

1. Connect a Device:
o Connect an Android device or start an emulator.
2. Run the App:
o Click the green "Run" button in Android Studio or press Shift + F10.
o Wait for the application to build and launch.

Output:
Basic Flutter App

Result & Conclusion :

Creating this simple application, you have laid the groundwork for further exploration into Flutter's
capabilities, such as handling user input, navigation, animations, and more complex state
management solutions. This foundational knowledge will be beneficial as you progress in developing
more advanced Flutter applications.
6. Develop a Flutter App by applying the Widgets, layouts and user management

Aim

To develop a Flutter application that demonstrates the use of various widgets, layout management
techniques, and basic user management (e.g., login functionality).

Algorithm

Step 1: Project Setup

1. Open Android Studio.


2. Go to File > New > New Flutter Project.
3. Choose Flutter Application, set the project name (e.g., flutter_user_management), select the
Flutter SDK path, and click Finish.

Step 2: Implement the Code

Code Overview

1. Login Page:
o Text fields for username and password.
o A button to simulate login functionality.
2. Home Page:
o Displays a welcome message for the user.
3. Navigation:
o Switch from the login page to the home page upon successful login.

Code Implementation

lib/main.dart:

import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

debugShowCheckedModeBanner: false,

home: LoginPage(),

);
}

class LoginPage extends StatefulWidget {

@override

_LoginPageState createState() => _LoginPageState();

class _LoginPageState extends State<LoginPage> {

final _usernameController = TextEditingController();

final _passwordController = TextEditingController();

void _login() {

String username = _usernameController.text;

String password = _passwordController.text;

if (username == "user" && password == "password") {

Navigator.push(

context,

MaterialPageRoute(builder: (context) => HomePage(username: username)),

);

} else {

ScaffoldMessenger.of(context).showSnackBar(

SnackBar(content: Text("Invalid username or password")),

);

@override

Widget build(BuildContext context) {

return Scaffold(

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

body: Padding(

padding: const EdgeInsets.all(16.0),


child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

TextField(

controller: _usernameController,

decoration: InputDecoration(labelText: 'Username'),

),

TextField(

controller: _passwordController,

decoration: InputDecoration(labelText: 'Password'),

obscureText: true,

),

SizedBox(height: 20),

ElevatedButton(

onPressed: _login,

child: Text('Login'),

),

],

),

),

);

class HomePage extends StatelessWidget {

final String username;

HomePage({required this.username});

@override
Widget build(BuildContext context) {

return Scaffold(

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

body: Center(

child: Text(

'Welcome, $username!',

style: TextStyle(fontSize: 24),

),

),

);

OUTPUT:

Result

1. The app launches to the Login Page.


2. Users can enter a username and password.
o Correct credentials: Navigate to the Home Page, displaying a personalized welcome
message.
o Incorrect credentials: Display an error message.
3. The app successfully demonstrates the use of widgets, layouts, and user management.
7. Write a Flutter code to perform navigation through screens

Aim

To develop a Flutter application that demonstrates navigation between multiple screens using
Flutter's Navigator widget.

Algorithm

Step 1: Create a Flutter Project

1. Open Android Studio.


2. Create a new Flutter project: File > New > New Flutter Project.
3. Name the project (e.g., navigation_example) and click Finish.

Step 2: Implement Navigation

1. Main Screen:

 Displays a button to navigate to the second screen.

2. Second Screen:

 Displays a message and a button to navigate back to the main screen.

Step 3: Write the Code

lib/main.dart:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Navigation Example',
home: MainScreen(),
);
}
}

class MainScreen extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Main 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: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'You are on the Second Screen!',
style: TextStyle(fontSize: 24),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Go Back to Main Screen'),
),
],
),
),
);
}
}

Step 4: Run the App

1. Start an emulator or connect a physical device.


2. Run the app using the Run button in Android Studio or the command
Output

Screen 1: Main Screen

 A button labeled "Go to Second Screen" is displayed.


 On pressing the button, the app navigates to the second screen.

Screen 2: Second Screen

 Displays a message: "You are on the Second Screen!".


 A button labeled "Go Back to Main Screen" navigates back to the main screen.

Result

 Navigation between screens was successfully implemented using Flutter's Navigator.push


and Navigator.pop methods.
8. Develop an application using importing external libraries

Aim

To create a Flutter application that imports and uses an external library (intl) to format and display
the current date and time in a user-friendly format.

Algorithm

Step 1: Create a Flutter Project

1. Open Android Studio.


2. Create a new Flutter project: File > New > New Flutter Project.
3. Set a project name (e.g., external_library_demo) and click Finish.

Step 2: Add External Library

1. Open the pubspec.yaml file in the project root directory.


2. Add the intl dependency:

dependencies:

flutter:

sdk: flutter

intl: ^0.18.0 # (Check for the latest version at pub.dev)

3. Save the file and run:

flutter pub get

This installs the library.

Step 3: Write the Code

The application will display the current date and time formatted using the intl package.

lib/main.dart:

import 'package:flutter/material.dart';

import 'package:intl/intl.dart';

void main() {

runApp(MyApp());

}
class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

debugShowCheckedModeBanner: false,

home: DateTimeScreen(),

);

class DateTimeScreen extends StatelessWidget {

@override

Widget build(BuildContext context) {

// Get current date and time

DateTime now = DateTime.now();

// Format date and time using intl

String formattedDate = DateFormat.yMMMMd('en_US').format(now); // e.g., November


18, 2024

String formattedTime = DateFormat.jm().format(now); // e.g., 2:45 PM

return Scaffold(

appBar: AppBar(

title: Text('Date and Time Formatter'),

),

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

Text(
'Current Date:',

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

),

Text(

formattedDate,

style: TextStyle(fontSize: 24, color: Colors.blue),

),

SizedBox(height: 20),

Text(

'Current Time:',

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

),

Text(

formattedTime,

style: TextStyle(fontSize: 24, color: Colors.green),

),

],

),

),

);

Step 4: Run the Application

1. Open an emulator or connect a physical device.


2. Run the app using the Run button in Android Studio
Output

Initial Screen:

 Displays the current date and time formatted using the intl library.

Example Output :

Current Date:

November 18, 2024

Current Time:

2:45 PM

Result

The application demonstrates the successful integration of an external library (intl) to


enhance the app's functionality by formatting dates and times.
9. Design a code to work with JSON data in Flutter

Aim

To develop a Flutter application that fetches JSON data from an API, parses it, and displays the data
in a list.

Algorithm

Step 1: Project Setup

1. Create a new Flutter project in Android Studio.


2. Add the http package to the pubspec.yaml file for API calls.

Step 2: Fetch JSON Data

1. Define the API endpoint.


2. Use the http package to fetch the data.
3. Parse the JSON response into a Dart object or list.

Step 3: Update the UI

1. Use state management (setState) to update the UI after data is fetched.


2. Display the data in a widget like ListView.builder.

Step 4: Run the Application

1. Test the app on an emulator or device to verify the data is displayed correctly.

Code

This app fetches and displays a list of posts from a public JSON API.

pubspec.yaml:

dependencies:

flutter:

sdk: flutter

http: ^0.15.0 # Or latest version

lib/main.dart:

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(

debugShowCheckedModeBanner: false,

title: 'JSON Data Example',

home: PostListScreen(),

);

class PostListScreen extends StatefulWidget {

@override

_PostListScreenState createState() => _PostListScreenState();

class _PostListScreenState extends State<PostListScreen> {

List<dynamic> posts = [];

bool isLoading = true;

@override

void initState() {

super.initState();

fetchPosts();

Future<void> fetchPosts() async {

final url = Uri.parse('https://jsonplaceholder.typicode.com/posts');

try {

final response = await http.get(url);

if (response.statusCode == 200) {

setState(() {
posts = json.decode(response.body);

isLoading = false;

});

} else {

throw Exception('Failed to load posts');

} catch (error) {

setState(() {

isLoading = false;

});

print('Error: $error');

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text('Posts List'),

),

body: isLoading

? Center(child: CircularProgressIndicator())

: ListView.builder(

itemCount: posts.length,

itemBuilder: (context, index) {

final post = posts[index];

return ListTile(

title: Text(post['title']),

subtitle: Text(post['body']),

);
},

),

);

Output

Initial State:

 Displays a loading spinner while fetching data from the API.

After Fetching:

 A list of posts is displayed, showing the title and body of each post.

Example:

Title: sunt aut facere repellat

Body: qui est esse reprehenderit ...

Result

 The application successfully fetches JSON data from the API, processes it, and displays it in
a scrollable list.

10. Implement session management using packages for login page


Aim

To create a Flutter application that allows users to log in and persists their login state using session
management techniques with the shared_preferences package.

Algorithm

Step 1: Setup the Project

1. Create a new Flutter project.


2. Add shared_preferences to pubspec.yaml to manage sessions.
3. Create two screens: Login Screen and Home Screen.
4. Store user credentials and login state using shared_preferences.

Step 2: Implement Login Logic

1. On login, verify user credentials (for simplicity, assume static credentials).


2. Use shared_preferences to store a flag indicating if the user is logged in.
3. When the app is opened, check if the user is logged in from previous sessions. If so, navigate
directly to the Home Screen, otherwise show the Login Screen.

Step 3: Implement the Home Screen

1. On the Home Screen, display a "Log out" button that clears the session (removes the login
flag).

Code

pubspec.yaml:

dependencies:

flutter:

sdk: flutter

shared_preferences: ^2.0.15 # Use the latest version

lib/main.dart:

import 'package:flutter/material.dart';

import 'package:shared_preferences/shared_preferences.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override
Widget build(BuildContext context) {

return MaterialApp(

debugShowCheckedModeBanner: false,

home: LoginPage(),

);

class LoginPage extends StatefulWidget {

@override

_LoginPageState createState() => _LoginPageState();

class _LoginPageState extends State<LoginPage> {

final TextEditingController _usernameController = TextEditingController();

final TextEditingController _passwordController = TextEditingController();

final _formKey = GlobalKey<FormState>();

// Sample credentials

final String _correctUsername = 'user';

final String _correctPassword = 'password';

Future<void> _login() async {

final username = _usernameController.text;

final password = _passwordController.text;

if (username == _correctUsername && password == _correctPassword) {

// Save login status using shared_preferences

final prefs = await SharedPreferences.getInstance();


await prefs.setBool('isLoggedIn', true);

// Navigate to the Home Screen

Navigator.pushReplacement(

context,

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

);

} else {

_showErrorDialog();

// Show error dialog

void _showErrorDialog() {

showDialog(

context: context,

builder: (ctx) => AlertDialog(

title: Text('Error'),

content: Text('Invalid username or password'),

actions: [

TextButton(

onPressed: () {

Navigator.of(ctx).pop();

},

child: Text('Okay'),

),

],

),

);
}

@override

Widget build(BuildContext context) {

return Scaffold(

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

body: Padding(

padding: const EdgeInsets.all(16.0),

child: Form(

key: _formKey,

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

TextFormField(

controller: _usernameController,

decoration: InputDecoration(labelText: 'Username'),

validator: (value) {

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

return 'Please enter your username';

return null;

},

),

TextFormField(

controller: _passwordController,

obscureText: true,

decoration: InputDecoration(labelText: 'Password'),

validator: (value) {

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


return 'Please enter your password';

return null;

},

),

SizedBox(height: 20),

ElevatedButton(

onPressed: _login,

child: Text('Login'),

),

],

),

),

),

);

class HomePage extends StatelessWidget {

Future<void> _logout(BuildContext context) async {

final prefs = await SharedPreferences.getInstance();

await prefs.setBool('isLoggedIn', false); // Clear login status

// Navigate back to login page

Navigator.pushReplacement(

context,

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

);

}
@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(title: Text('Home Page')),

body: Center(

child: ElevatedButton(

onPressed: () => _logout(context),

child: Text('Logout'),

),

),

);

class SplashPage extends StatelessWidget {

@override

Widget build(BuildContext context) {

return FutureBuilder(

future: _checkLoginStatus(context),

builder: (ctx, snapshot) {

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

return Scaffold(

body: Center(child: CircularProgressIndicator()),

);

if (snapshot.data == true) {

return HomePage(); // Already logged in


} else {

return LoginPage(); // Not logged in

},

);

Future<bool> _checkLoginStatus(BuildContext context) async {

final prefs = await SharedPreferences.getInstance();

return prefs.getBool('isLoggedIn') ?? false;

Explanation of Code

1. LoginPage: Handles user authentication. If the login credentials are correct, the login status
is saved in shared_preferences as a boolean value (isLoggedIn), and the user is redirected to
the HomePage.
2. HomePage: Displays a logout button that clears the login status and redirects back to the
LoginPage.
3. SharedPreferences: Used for persistent storage of the login state (isLoggedIn). This allows
the app to remember whether the user is logged in after the app is restarted.
4. SplashPage: This page checks if the user is already logged in before navigating to the
appropriate screen.

Output

1. Login Screen:
o The user enters their username and password.
o If valid, they are redirected to the Home Page.
2. Home Screen:
o After successful login, the Home Page will be displayed with a "Logout" button.
o Pressing "Logout" will clear the session and navigate back to the Login Screen.
Result

 The app uses session management through shared_preferences to store the user's login
state.
 After logging in successfully, the user is redirected to the Home Screen. If the app is
restarted, the Splash Screen checks whether the user is logged in or not and navigates
accordingly.
 The user can log out, which will clear the session and navigate back to the Login Screen.

You might also like