Flutter Lab Program
5a1
import 'package:flutter/material.dart';
class MyStatelessWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Stateless Widget Example'),
),
body: Center(
child: Text(
'Hello, Flutter!', // In this example, MyStatelessWidget does not change after it is built. The text "Hello, Flutter!" is static.
style: TextStyle(fontSize: 24),
),
),
);
}
}
void main() {
runApp(MaterialApp(
home: MyStatelessWidget(),
));
}
5a2
import 'package:flutter/material.dart';
class MyStatefulWidget extends StatefulWidget {
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Stateful Widget Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pressed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium, // Updated to headlineMedium
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
void main() {
runApp(MaterialApp(
home: MyStatefulWidget(),
));
}
5b
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class CounterProvider with ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
void decrement() {
_count--;
notifyListeners();
}
}
void main() {
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => CounterProvider()),
],
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Provider Counter Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: CounterScreen(),
);
}
}
class CounterScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
final counterProvider = context.watch<CounterProvider>();
return Scaffold(
appBar: AppBar(
title: Text('Provider Counter Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('You have pushed the button this many times:'),
Text(
'${counterProvider.count}',
style: Theme.of(context).textTheme.headlineMedium,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
icon: Icon(Icons.add),
onPressed: counterProvider.increment,
),
IconButton(
icon: Icon(Icons.remove),
onPressed: counterProvider.decrement,
),
],
),
],
),
),
);
}
}
6a
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
title: 'Portfolio',
theme: ThemeData(
primarySwatch: Colors.blue,
textTheme: TextTheme(
titleLarge: TextStyle(fontSize: 28, fontWeight: FontWeight.bold),
bodyMedium: TextStyle(fontSize: 16, color: Colors.grey[600]),
),
cardTheme: CardTheme(
elevation: 4,
margin: EdgeInsets.all(10),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
),
),
home: PortfolioPage(),
));
class PortfolioPage extends StatelessWidget {
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text("Portfolio"), centerTitle: true),
backgroundColor: Colors.pink[50],
body: Column(
children: [
ProfileSection(),
InfoCard(title: "Education", content: ["B.Tech in CSE"]),
InfoCard(title: "Skills", content: ["Flutter Developer", "Web Developer"]),
],
),
);
}
class ProfileSection extends StatelessWidget {
@override
Widget build(BuildContext context) => Card(
child: ListTile(
leading: CircleAvatar(backgroundImage: AssetImage('assets/man.png'), radius: 40),
title: Text("XXXXX", style: Theme.of(context).textTheme.titleLarge),
subtitle: Text("Software Engineer"),
),
);
}
class InfoCard extends StatelessWidget {
final String title;
final List<String> content;
InfoCard({required this.title, required this.content});
@override
Widget build(BuildContext context) => Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title, style: Theme.of(context).textTheme.titleLarge),
...content.map((item) => Text(item, style: Theme.of(context).textTheme.bodyMedium)),
],
),
),
);
}
7
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Form Validation Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const FormPage(),
);
}
}
class FormPage extends StatefulWidget {
const FormPage({super.key});
@override
_FormPageState createState() => _FormPageState();
}
class _FormPageState extends State<FormPage> {
final _formKey = GlobalKey<FormState>();
// Controllers for input fields
final _nameController = TextEditingController();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
@override
void dispose() {
_nameController.dispose();
_emailController.dispose();
_passwordController.dispose();
super.dispose();
}
void _submitForm() {
if (_formKey.currentState!.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Form submitted successfully!')),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Form Validation'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: _nameController,
decoration: const InputDecoration(
labelText: 'Name',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your name';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _emailController,
decoration: const InputDecoration(
labelText: 'Email',
border: OutlineInputBorder(),
),
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your email';
}
if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) {
return 'Please enter a valid email';
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _passwordController,
decoration: const InputDecoration(
labelText: 'Password',
border: OutlineInputBorder(),
),
obscureText: true,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a password';
}
if (value.length < 6) {
return 'Password must be at least 6 characters long';
}
return null;
},
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _submitForm,
child: const Text('Submit'),
),
],
),
),
),
);
}
}
8
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Scale Animation with ',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: AnimatedScaleWidget(),
);
}
}
class AnimatedScaleWidget extends StatefulWidget {
@override
_AnimatedScaleWidgetState createState() => _AnimatedScaleWidgetState();
}
class _AnimatedScaleWidgetState extends State<AnimatedScaleWidget> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _scaleAnimation;
@override
void initState() {
super.initState();
// Create an AnimationController
_controller = AnimationController(
duration: const Duration(seconds: 2),
vsync: this,
)..repeat(reverse: true); // Repeat animation with reverse effect
// Define the scale animation
_scaleAnimation = Tween<double>(begin: 0.5, end: 1.5).animate(
CurvedAnimation(parent: _controller, curve: Curves.elasticInOut),
);
}
@override
void dispose() {
_controller.dispose(); // Dispose of the controller when not needed
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Scale Animation with Image"),
),
body: Center(
child: ScaleTransition(
scale: _scaleAnimation, // Apply the scale animation
child: Image.asset(
'assets/images.jpg', // Path to your image
width: 150, // Set the width of the image
height: 150, // Set the height of the image
fit: BoxFit.contain, // Ensures the image fits within the box
),
),
),
);
}
}
9
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: 'Flutter API Fetch',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: UserListScreen(),
);
}
}
class UserListScreen extends StatefulWidget {
@override
_UserListScreenState createState() => _UserListScreenState();
}
class _UserListScreenState extends State<UserListScreen> {
List<User> users = [];
bool isLoading = true;
String? errorMessage;
@override
void initState() {
super.initState();
fetchUsers();
}
Future<void> fetchUsers() async {
final response =
await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users'));
if (response.statusCode == 200) {
List<dynamic> jsonResponse = json.decode(response.body);
users = jsonResponse.map((user) => User.fromJson(user)).toList();
setState(() {
isLoading = false;
});
} else {
setState(() {
isLoading = false;
errorMessage = 'Failed to load users';
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('User List'),
),
body: isLoading
? Center(child: CircularProgressIndicator())
: errorMessage != null
? Center(child: Text(errorMessage!))
: ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
return Card(
margin: EdgeInsets.all(8),
child: ListTile(
title: Text(users[index].name),
subtitle: Text(users[index].email),
),
);
},
),
);
}
}
class User {
final int id;
final String name;
final String email;
User({required this.id, required this.name, required this.email});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'],
name: json['name'],
email: json['email'],
);
}
}
// update it in pubspec.yaml
// dependencies:
// flutter:
// sdk: flutter
// http: 1.2.2
10
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: 'Flutter API Fetch',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: UserListScreen(),
);
}
}
class UserListScreen extends StatefulWidget {
@override
_UserListScreenState createState() => _UserListScreenState();
}
class _UserListScreenState extends State<UserListScreen> {
List<User> users = [];
bool isLoading = true;
String? errorMessage;
@override
void initState() {
super.initState();
fetchUsers();
}
Future<void> fetchUsers() async {
final response =
await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users'));
if (response.statusCode == 200) {
List<dynamic> jsonResponse = json.decode(response.body);
users = jsonResponse.map((user) => User.fromJson(user)).toList();
setState(() {
isLoading = false;
});
} else {
setState(() {
isLoading = false;
errorMessage = 'Failed to load users';
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('User List'),
),
body: isLoading
? Center(child: CircularProgressIndicator())
: errorMessage != null
? Center(child: Text(errorMessage!))
: ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
return Card(
margin: EdgeInsets.all(8),
child: ListTile(
title: Text(users[index].name),
subtitle: Text(users[index].email),
),
);
},
),
);
}
}
class User {
final int id;
final String name;
final String email;
User({required this.id, required this.name, required this.email});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'],
name: json['name'],
email: json['email'],
);
}
}
// update it in pubspec.yaml
// dependencies:
// flutter:
// sdk: flutter
// http: 1.2.2
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:exp10/main.dart'; // Adjust this based on your file path
void main() {
testWidgets('shows loading indicator while fetching data', (tester) async {
// Build the widget
await tester.pumpWidget(MyApp());
// Assert: Check if CircularProgressIndicator is shown (loading state)
expect(find.byType(CircularProgressIndicator), findsOneWidget);
});
}
Comments
Post a Comment