Home
ML Lab
Lab 1 Lab 2 Lab 3 Lab 4 Lab 5 Lab 6 Lab 7 Lab 8 Lab 9 Lab 10
Flutter
Lab 1 Lab 2 Lab 3 Lab 4 Lab 5 Lab 6 Lab 7 Lab 8 Lab 9 Lab 10 Lab 11 Lab 12
Contact
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_california_housing
data = fetch_california_housing(as_frame=True)
housing_df = data.frame

numerical_features = housing_df.select_dtypes(include=[np.number]).columns

plt.figure(figsize=(15, 10))
for i, feature in enumerate(numerical_features):
    plt.subplot(3, 3, i + 1)
    sns.histplot(housing_df[feature], kde=True, bins=30, color='blue')
    plt.title(f'Distribution of {feature}')
plt.tight_layout()
plt.show()
plt.figure(figsize=(15, 10))
for i, feature in enumerate(numerical_features):
    plt.subplot(3, 3, i + 1)
    sns.boxplot(x=housing_df[feature], color='orange')
    plt.title(f'Box Plot of {feature}')
plt.tight_layout()
plt.show()
print("Outliers Detection:")
outliers_summary = {}
for feature in numerical_features:
    Q1 = housing_df[feature].quantile(0.25)
    Q3 = housing_df[feature].quantile(0.75)
    IQR = Q3 - Q1
    lower_bound = Q1 - 1.5 * IQR
    upper_bound = Q3 + 1.5 * IQR
    outliers = housing_df[(housing_df[feature] < lower_bound) | (housing_df[feature] > upper_bound)]
    outliers_summary[feature] = len(outliers)
    print(f"{feature}: {len(outliers)} outliers")
print("\nDataset Summary:")
print(housing_df.describe())
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_california_housing
california_data = fetch_california_housing(as_frame=True)
data = california_data.frame
correlation_matrix = data.corr()
plt.figure(figsize=(10, 8))
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt='.2f', linewidths=0.5)
plt.title('Correlation Matrix of California Housing Features')
plt.show()
sns.pairplot(data, diag_kind='kde', plot_kws={'alpha': 0.5})
plt.suptitle('Pair Plot of California Housing Features', y=1.02)
plt.show()
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt

iris = load_iris()
data = iris.data
labels = iris.target
label_names = iris.target_names
iris_df = pd.DataFrame(data, columns=iris.feature_names)

pca = PCA(n_components=2)
data_reduced = pca.fit_transform(data)

reduced_df = pd.DataFrame(data_reduced, columns=['Principal Component 1', 'Principal Component 2'])
reduced_df['Label'] = labels

plt.figure(figsize=(8, 6))
colors = ['r', 'g', 'b']
for i, label in enumerate(np.unique(labels)):
    plt.scatter(
        reduced_df[reduced_df['Label'] == label]['Principal Component 1'],
        reduced_df[reduced_df['Label'] == label]['Principal Component 2'],
        label=label_names[label],
        color=colors[i]
)
plt.title('PCA on Iris Dataset')
plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
plt.legend()
plt.grid()
plt.show()
import pandas as pd
import numpy as np
data = pd.read_csv('book.csv')
concept=np.array(data)[:,:-1]
target=np.array(data)[:,-1]
h=concept[0].copy()
specific_h=['0']*len(h)
for i,val in enumerate(concept):
    if target[i]=='yes':
        print("\nInstance",i+1,"is Positive:")
        for x in range(len(specific_h)):
            if specific_h[x]=='0'or specific_h[x]==val[x]:
                specific_h[x]=val[x]
            else:
                specific_h[x]="?"
        print("The hypothesis for the training instance",i+1,"is:",specific_h,"\n")
    if target[i]=='no':
        print("\nInstance",i+1,"is Negative Instance hence it is Ignored:")
        print("The Hypothesis for the training instance",i+1,"is:",specific_h,"\n")
print("\n The Maximally specific hypothesis for the training instance is",specific_h)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
x_values=np.random.rand(100).reshape(-1,1)
labels=np.array([1 if x<=0.5 else 2 for x in x_values[:50]])
X_train,y_train=x_values[:50],labels
X_test=x_values[50:]
k_values=[1,2,3,4,5,20,30]
for k in k_values:
    knn=KNeighborsClassifier(n_neighbors=k)
    knn.fit(X_train,y_train)
    y_pred=knn.predict(X_test)
    print(f'k={k}:')
    for i,(x_val,pred) in enumerate(zip(X_test,y_pred),start=51):
        print(f'point {i}:x={x_val[0]:.4f},class={pred}')
    print()
    plt.figure()
    plt.scatter(X_train,y_train,color='blue',label='Training Data')
    plt.scatter(X_train,y_pred,color='red',label='Classified Test Data')
    plt.xlabel('x values')
    plt.ylabel('Class')
    plt.title(f'k-NN Classification (k={k})')
    plt.legend()
    plt.show()
import matplotlib.pyplot as plt

from sklearn.datasets import fetch_california_housing

from sklearn.model_selection import train_test_split

from sklearn.preprocessing import StandardScaler

import numpy as np

def locally_weighted_linear_regression(X,Y,tau):

  m=len(X)

  predictions=np.zeros(m)

  X_b=np.c_[np.ones((m,1)),X] 

  for i in range(m):

   W=np.eye(m)*np.exp(-np.sum((X-X[i])**2,axis=1)/(2*tau**2))

   theta=np.linalg.lstsq(X_b.T @ W @ X_b,X_b.T @ W @ Y,rcond=None)[0]

   predictions[i]=X_b[i]@ theta

  return predictions

data=fetch_california_housing()

X=data.data[:,0]

Y=data.target

scaler=StandardScaler()

X_scaled=scaler.fit_transform(X.reshape(-1,1))

X_scaled=X_scaled[:200]

Y=Y[:200]

X_train,X_test,Y_train,Y_test=train_test_split(X_scaled,Y,test_size=0.2,random_state=42)

tau=0.5

train_predictions=locally_weighted_linear_regression(X_train,Y_train,tau)

plt.figure(figsize=(10,6))

plt.scatter(X_train,Y_train,color='palegreen',label='Training data')

plt.scatter(X_test,Y_test,color='black',label='Test data')

#plt.plot(X_train,train_predictions,color='coral',label='Localllly Weighted Regression')

plt.plot(np.sort(X_train.flatten()),locally_weighted_linear_regression(np.sort(X_train.flatten()).reshape(-1,1),Y_train,tau),color='red',label='Locally Weighted Regression')

plt.legend()

plt.xlabel('Median Income')

plt.ylabel('House Value (in thousands)')

plt.title('Locally Weighted Linear Regression on California Housing Dataset')

plt.show()
import numpy as np
import ssl
ssl._create_default_https_context=ssl._create_unverified_context
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.metrics import mean_squared_error, r2_score
def linear_regression_california():
    housing=fetch_california_housing(as_frame=True)
    X = housing.data[["AveRooms"]]
    y = housing.target
    X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=42)
    model=LinearRegression()
    model.fit(X_train,y_train)
    y_pred=model.predict(X_test)
    plt.scatter(X_test,y_test,color="blue",label="Actual")
    plt.plot(X_test,y_pred,color="red",label="Predicted")
    plt.xlabel("Average number of rooms(AveRooms)")
    plt.ylabel("Median value of homes($100,000)")
    plt.title("Linear Regression-California Housing Dataset")
    plt.legend()
    plt.show()
    print("Linear Regression-California Housing Dataset")
    print("Mean Squared Error:",mean_squared_error(y_test,y_pred))
def polynomial_regression_auto_mpg():
    url="https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data"
    column_names=["mpg","cylinders","displacement","horsepower","weight","acceleration","model_year","origin"]
    data=pd.read_csv(url,sep='\s+',names=column_names,na_values="?")
    data=data.dropna()
    X=data["displacement"].values.reshape(-1,1)
    y=data["mpg"].values
    X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=42)
    poly_model=make_pipeline(PolynomialFeatures(degree=2),StandardScaler(),LinearRegression())
    poly_model.fit(X_train,y_train)
    y_pred=poly_model.predict(X_test)
    plt.scatter(X_test,y_test,color="purple",label="Actual")
    plt.scatter(X_test,y_pred,color="coral",label="predicted")
    plt.xlabel("Displacement")
    plt.ylabel("Miles per gallon(mpg)")
    plt.title("Polynomial Regression-Auto MPG Dataset")
    plt.legend()
    plt.show()
    print("Polynomial Regression-Auto MPG Dataset")
    print("Mean Squared Error:",mean_squared_error(y_test,y_pred))
print("Demonstrating Linear Regression and Polynomial Regression\n")
linear_regression_california()
polynomial_regression_auto_mpg()
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.metrics import accuracy_score
data = load_breast_cancer()
X = data.data
y = data.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
clf = DecisionTreeClassifier(random_state=42)
clf.fit(X_train, y_train)
plt.figure(figsize=(12, 8))
plot_tree(clf, filled=True, feature_names=data.feature_names, class_names=data.target_names)
plt.title("Decision Tree - Breast Cancer Dataset")
plt.show()
new_sample = np.array([X_test[0]])
prediction = clf.predict(new_sample)
prediction_class = "Benign" if prediction == 1 else "Malignant"
print(f"Predicted Class for the new sample: {prediction_class}")
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Model Accuracy: {accuracy * 100:.2f}%")
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import fetch_olivetti_faces
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
import ssl
ssl._create_default_https_context=ssl._create_unverified_context
from sklearn.metrics import accuracy_score,classification_report,confusion_matrix
faces=fetch_olivetti_faces(shuffle=True,random_state=42)
X,y=faces.data,faces.target
fig,axes=plt.subplots(2,5,figsize=(10,5))
for i,ax in enumerate(axes.flat):
    ax.imshow(X[i].reshape(64,64),cmap='gray')
    ax.set_title(f"Person {y[i]}")
    ax.axis('off')
plt.suptitle("Sample Images from Olivetti Faces Dataset")
plt.show()
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,stratify=y,random_state=42)
model=GaussianNB()
model.fit(X_train,y_train)
y_pred=model.predict(X_test)
fig,axes=plt.subplots(2,5,figsize=(10,5))
for i,ax in enumerate(axes.flat):
    ax.imshow(X[i].reshape(64,64),cmap='gray')
    ax.set_title(f"Pred:{y_pred[i]}\nActual:{y_test[i]}")
    ax.axis('off')
plt.suptitle("Predictions on Test Images")
plt.show()
accuracy=accuracy_score(y_test,y_pred)
print(f"\nNative Bayes Classifier Accuracy:{accuracy:.2f}")
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import load_breast_cancer
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
data = load_breast_cancer()
X = data.data
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
kmeans = KMeans(n_clusters=2, random_state=42, n_init=10)
clusters = kmeans.fit_predict(X_scaled)
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)
centroids_original = kmeans.cluster_centers_
centroids_pca = pca.transform(centroids_original)
plt.figure(figsize=(8, 6))
for cluster, color in zip(range(2), ["red", "blue"]):
    plt.scatter(X_pca[clusters == cluster, 0], X_pca[clusters == cluster, 1], color=color, alpha=0.6, edgecolor="k", label=f"Cluster {cluster}" )
plt.scatter(centroids_pca[:, 0], centroids_pca[:, 1], s=250, c='black', marker='X', label="Centroids")
plt.legend(loc="upper right")
plt.title("K-Means Clustering on Wisconsin Breast Cancer Dataset")
plt.xlabel("Principal Component 1")
plt.ylabel("Principal Component 2")
plt.show()
import 'package:flutter/material.dart';
 
void main() {
  runApp(const HelloWorldApp());
}
 
class HelloWorldApp extends StatelessWidget {
  const HelloWorldApp({super.key});
 
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hello Flutter App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomeScreen(),
    );
  }
}
 
class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Hello Flutter App'),
      ),
      body: const Center(
        child: GreetingColumn(),
      ),
    );
  }
}
 
class GreetingColumn extends StatelessWidget {
  const GreetingColumn({super.key});
 
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: const [
        Text(
          'Hello World',
          style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
        ),
        SizedBox(height: 20),
        Text(
          'Hello Flutter',
          style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
        ),
      ],
    );
  }
}
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: 'Counter App',
theme: ThemeData(primarySwatch: Colors.blue),
home: const CounterScreen(),
);
}
}
class CounterScreen extends StatefulWidget {
const CounterScreen({super.key});
 
  @override
  _CounterScreenState createState() => _CounterScreenState();
}
 
class _CounterScreenState extends State {
  int _counter = 0;
 
  void _increment() {
    setState(() {
      _counter++;
    });
  }
 
  void _decrement() {
    setState(() {
      _counter--;
    });
  }
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Counter App')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              'Counter Value:',
              style: TextStyle(fontSize: 20),
            ),
            Text(
              '$_counter',
              style: const TextStyle(fontSize: 40, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton(
                  onPressed: _increment,
                  child: const Text('Increment'),
                ),
                const SizedBox(width: 10),
                ElevatedButton(
                  onPressed: _decrement,
                  child: const Text('Decrement'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
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: 'Login App',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const LoginScreen(),
    );
  }
}
 
class LoginScreen extends StatefulWidget {
  const LoginScreen({super.key});
 
  @override
  _LoginScreenState createState() => _LoginScreenState();
}
 
class _LoginScreenState extends State {
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
 
  void _login() {
    String email = _emailController.text;
    String password = _passwordController.text;
 
    if (email == "admin" && password == "12345") {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text("Login Successful!")),
      );
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text("Invalid Credentials!")),
      );
    }
  }
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Login Screen")),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              "Welcome Back!",
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 20),
            TextField(
              controller: _emailController,
              decoration: const InputDecoration(
                labelText: "Email",
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 15),
            TextField(
              controller: _passwordController,
              obscureText: true,
              decoration: const InputDecoration(
                labelText: "Password",
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _login,
              style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 15),
              ),
              child: const Text("Login"),
            ),
          ],
        ),
      ),
    );
  }
}
Sky,Temp,Humidity,Wind,Water,Forecast,Target
Sunny,Warm,Normal,Strong,Warm,Same,yes
Sunny,Warm,High,Strong,Warm,Same,yes
Rainy,Cold,High,Strong,Warm,Change,no
Sunny,Warm,High,Strong,Cool,Change,yes
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: 'Calculator',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const CalculatorScreen(),
    );
  }
}
 
class CalculatorScreen extends StatefulWidget {
  const CalculatorScreen({super.key});
  @override
  _CalculatorScreenState createState() => _CalculatorScreenState();
}
class _CalculatorScreenState extends State {
  String _output = "0";
  String _input = "";
  double _num1 = 0;
  double _num2 = 0;
  String _operator = "";
  void _buttonPressed(String value) {
    setState(() {
      if (value == "C") {
        _input = "";
        _output = "0";
        _num1 = 0;
        _num2 = 0;
        _operator = "";
      } else if (value == "=") {
        if (_operator.isNotEmpty && _input.isNotEmpty) {
          _num2 = double.tryParse(_input) ?? 0;
          switch (_operator) {
            case "+":
              _output = (_num1 + _num2).toString();
              break;
            case "-":
              _output = (_num1 - _num2).toString();
              break;
            case "×":
              _output = (_num1 * _num2).toString();
              break;
            case "÷":
              _output = _num2 != 0 ? (_num1 / _num2).toString() : "Error";
              break;
          }
          _input = "";
          _operator = "";
        }
      } else if (["+", "-", "×", "÷"].contains(value)) {
        if (_input.isNotEmpty) {
          _num1 = double.tryParse(_input) ?? 0;
          _operator = value;
          _input = "";
        }
      } else {
        _input += value;
        _output = _input;
      }
    });
  }
  Widget _buildButton(String text, {Color color = Colors.blue}) {
    return Expanded(
      child: ElevatedButton(
        onPressed: () => _buttonPressed(text),
        style: ElevatedButton.styleFrom(
          padding: const EdgeInsets.all(20),
          backgroundColor: color,
        ),
        child: Text(
          text,
          style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
        ),
      ),
    );
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Calculator")),
      body: Column(
        children: [
          Expanded(
            child: Container(
              alignment: Alignment.bottomRight,
              padding: const EdgeInsets.all(20),
              child: Text(
                _output,
                style: const TextStyle(fontSize: 40, fontWeight: FontWeight.bold),
              ),
            ),
          ),
          Column(
            children: [
              Row(children: [_buildButton("7"), _buildButton("8"), _buildButton("9"), _buildButton("÷",
color: Colors.orange)]),
              Row(children: [_buildButton("4"), _buildButton("5"), _buildButton("6"), _buildButton("×",
color: Colors.orange)]),
              Row(children: [_buildButton("1"), _buildButton("2"), _buildButton("3"), _buildButton("-",
color: Colors.orange)]),
              Row(children: [_buildButton("0"), _buildButton("C", color: Colors.red), _buildButton("=",
color: Colors.green), _buildButton("+", color: Colors.orange)]),
            ],
          ),
        ],
      ),
    );
  }
}
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
 
void main() {
  runApp(const MyApp());
}
 
class MyApp extends StatelessWidget {
  const MyApp({super.key});
 
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
title: 'Weather App',
theme: ThemeData(primarySwatch: Colors.blue),
home: const WeatherScreen(),
);
}
}
class WeatherScreen extends StatefulWidget {
const WeatherScreen({super.key});
@override
_WeatherScreenState createState() => _WeatherScreenState();
}
class _WeatherScreenState extends State {
final TextEditingController _cityController = TextEditingController();
String _weatherInfo = "Enter a city to check the weather!";
String _temperature = "";
String _iconUrl = "";
Future _fetchWeather(String city) async {
const String apiKey = "f170617f038a0fb58ea2713ec7bc4ed1"; // Replace with your API key
final String url =
"https://api.openweathermap.org/data/2.5/weather?q=$city&appid=$apiKey&units=metric";
    try {
      final response = await http.get(Uri.parse(url));
 
      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        setState(() {
          _weatherInfo = data["weather"][0]["description"].toString().toUpperCase();
          _temperature = "${data["main"]["temp"].toString()}°C";
          _iconUrl =
              "https://openweathermap.org/img/wn/${data["weather"][0]["icon"]}@2x.png";
        });
      } else {
        setState(() {
          _weatherInfo = "City not found. Try again!";
          _temperature = "";
          _iconUrl = "";
        });
      }
    } catch (e) {
      setState(() {
        _weatherInfo = "Error fetching weather. Check your connection!";
        _temperature = "";
        _iconUrl = "";
      });
    }
  }
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Weather App")),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            TextField(
              controller: _cityController,
              decoration: InputDecoration(
                labelText: "Enter City Name",
                border: OutlineInputBorder(),
                suffixIcon: IconButton(
                  onPressed: () => _fetchWeather(_cityController.text),
                  icon: const Icon(Icons.search),
                ),
              ),
            ),
            const SizedBox(height: 20),
            if (_iconUrl.isNotEmpty)
              Image.network(_iconUrl, height: 80), // Weather icon
            Text(
              _temperature,
              style: const TextStyle(fontSize: 40, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 10),
            Text(
              _weatherInfo,
              textAlign: TextAlign.center,
              style: const TextStyle(fontSize: 20),
            ),
          ],
        ),
      ),
    );
  }
}
import 'dart:async';
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: 'Stopwatch',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const StopwatchScreen(),
    );
  }
}
 
class StopwatchScreen extends StatefulWidget {
  const StopwatchScreen({super.key});
 
  @override
  _StopwatchScreenState createState() => _StopwatchScreenState();
}
 
class _StopwatchScreenState extends State {
  Stopwatch _stopwatch = Stopwatch();
  Timer? _timer;
 
  String _formatTime(int milliseconds) {
    int seconds = (milliseconds ~/ 1000) % 60;
    int minutes = (milliseconds ~/ (1000 * 60)) % 60;
    int hours = (milliseconds ~/ (1000 * 60 * 60));
 
    String hoursStr = hours.toString().padLeft(2, '0');
    String minutesStr = minutes.toString().padLeft(2, '0');
    String secondsStr = seconds.toString().padLeft(2, '0');
 
    return "$hoursStr:$minutesStr:$secondsStr";
  }
 
  void _startStopwatch() {
    if (!_stopwatch.isRunning) {
      _stopwatch.start();
      _timer = Timer.periodic(const Duration(milliseconds: 100), (timer) {
        setState(() {});
      });
    }
  }
 
  void _stopStopwatch() {
    if (_stopwatch.isRunning) {
      _stopwatch.stop();
      _timer?.cancel();
      setState(() {});
    }
  }
 
  void _resetStopwatch() {
    _stopwatch.reset();
    _timer?.cancel();
    setState(() {});
  }
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Stopwatch")),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const SizedBox(height: 50),
          Center(
            child: Text(
              _formatTime(_stopwatch.elapsedMilliseconds),
              style: const TextStyle(fontSize: 50, fontWeight: FontWeight.bold),
            ),
          ),
          const SizedBox(height: 30),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                onPressed: _startStopwatch,
                style: ElevatedButton.styleFrom(backgroundColor: Colors.green),
                child: const Text("Start"),
              ),
              const SizedBox(width: 10),
              ElevatedButton(
                onPressed: _stopStopwatch,
                style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
                child: const Text("Stop"),
              ),
              const SizedBox(width: 10),
              ElevatedButton(
                onPressed: _resetStopwatch,
                style: ElevatedButton.styleFrom(backgroundColor: Colors.blue),
                child: const Text("Reset"),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
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: 'Navigation App',
theme: ThemeData(primarySwatch: Colors.blue),
home: const HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Home Screen")),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => const SecondScreen()),
            );
          },
          child: const Text("Go to Second Screen"),
        ),
      ),
    );
  }
}
 
class SecondScreen extends StatelessWidget {
  const SecondScreen({super.key});
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Second Screen")),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text("Back to Home Screen"),
        ),
      ),
    );
  }
}
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: 'E-Commerce UI',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});

  final List> products = const [
    {
      "name": "Nike Shoes",
      "price": "\$120",
      "image": "https://picsum.photos/200",
    },
    {
      "name": "Apple Watch",
      "price": "\$250",
      "image": "https://picsum.photos/201",
    },
    {
      "name": "Headphones",
      "price": "\$80",
      "image": "https://picsum.photos/220",
    },
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("E-Commerce UI"),
        actions: [
          IconButton(
            icon: const Icon(Icons.shopping_cart),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const CartScreen()),
              );
            },
          ),
        ],
      ),
      body: GridView.builder(
        padding: const EdgeInsets.all(10),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 0.8,
          crossAxisSpacing: 10,
          mainAxisSpacing: 10,
        ),
        itemCount: products.length,
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder:
                      (context) => ProductDetailsScreen(
                        name: products[index]["name"]!,
                        price: products[index]["price"]!,
                        image: products[index]["image"]!,
                      ),
                ),
              );
            },
            child: Card(
              elevation: 4,
              child: Column(
                children: [
                  Image.network(
                    products[index]["image"]!,
                    height: 100,
                    fit: BoxFit.cover,
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                      products[index]["name"]!,
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  Text(
                    products[index]["price"]!,
                    style: const TextStyle(fontSize: 16, color: Colors.blue),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}

class ProductDetailsScreen extends StatelessWidget {
  final String name;
  final String price;
  final String image;

  const ProductDetailsScreen({
    super.key,
    required this.name,
    required this.price,
    required this.image,
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(name)),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.network(image, height: 150),
            const SizedBox(height: 20),
            Text(
              name,
              style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            Text(
              price,
              style: const TextStyle(fontSize: 20, color: Colors.blue),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => const CartScreen()),
                );
              },
              child: const Text("Add to Cart"),
            ),
          ],
        ),
      ),
    );
  }
}

class CartScreen extends StatelessWidget {
  const CartScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Cart")),
      body: const Center(child: Text("Your cart is empty!")),
    );
  }
}

import 'dart:async';
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: 'Animated Logo',
theme: ThemeData(primarySwatch: Colors.blue),
home: const AnimatedLogoScreen(),
);
}
}
class AnimatedLogoScreen extends StatefulWidget {
const AnimatedLogoScreen({super.key});
@override
_AnimatedLogoScreenState createState() => _AnimatedLogoScreenState();
}
class _AnimatedLogoScreenState extends State
with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation _animation;
 
  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    )..repeat(reverse: true);
 
    _animation = Tween(begin: 100, end: 200).animate(
      CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
    );
 
    Timer(const Duration(seconds: 5), () {
      _controller.stop();
    });
  }
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: AnimatedBuilder(
          animation: _animation,
          builder: (context, child) {
            return SizedBox(
              width: _animation.value,
              height: _animation.value,
              child: Image.network(
                'https://upload.wikimedia.org/wikipedia/commons/1/17/Google-flutter-logo.png',
              ),
            );
          },
        ),
      ),
    );
  }
 
  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}
print("Flutter Lab 11: Storage")
import 'package:flutter/material.dart';
void main() {
  runApp(const QuizApp());
}
class QuizApp extends StatelessWidget {
  const QuizApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Quiz App',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const QuizScreen(),
    );
  }
}
class QuizScreen extends StatefulWidget {
  const QuizScreen({super.key});
 
  @override
  _QuizScreenState createState() => _QuizScreenState();
}
class _QuizScreenState extends State {
  final List> _questions = [
    {
      "question": "What is the capital of France?",
      "options": ["Berlin", "Madrid", "Paris", "Rome"],
      "answer": "Paris"
    },
    {
      "question": "Which programming language is used in Flutter?",
      "options": ["Java", "Dart", "Kotlin", "Swift"],
      "answer": "Dart"
    },
    {
      "question": "Who developed Flutter?",
      "options": ["Apple", "Microsoft", "Google", "Facebook"],
      "answer": "Google"
    },
  ];
  int _currentQuestionIndex = 0;
  int _score = 0;
  bool _quizCompleted = false;
 
  void _checkAnswer(String selectedAnswer) {
    if (selectedAnswer == _questions[_currentQuestionIndex]["answer"]) {
      _score++;
    }
    setState(() {
      if (_currentQuestionIndex < _questions.length - 1) {
        _currentQuestionIndex++;
      } else {
        _quizCompleted = true;
      }
    });
  }
 
  void _restartQuiz() {
    setState(() {
      _currentQuestionIndex = 0;
      _score = 0;
      _quizCompleted = false;
    });
  }
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Quiz App")),
      body: _quizCompleted
          ? ScoreBoard(score: _score, total: _questions.length, restartQuiz: _restartQuiz)
          : QuizQuestion(
              question: _questions[_currentQuestionIndex]["question"],
              options: _questions[_currentQuestionIndex]["options"],
              checkAnswer: _checkAnswer,
            ),
    );
  }
}
 
class QuizQuestion extends StatelessWidget {
  final String question;
  final List options;
  final Function(String) checkAnswer;
 
  const QuizQuestion({super.key, required this.question, required this.options, required
this.checkAnswer});
 
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(20),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            question,
            style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 20),
          ...options.map((option) => ElevatedButton(
                onPressed: () => checkAnswer(option),
                child: Text(option, style: const TextStyle(fontSize: 18)),
              )),
        ],
      ),
    );
  }
}
 
class ScoreBoard extends StatelessWidget {
  final int score;
  final int total;
  final VoidCallback restartQuiz;
 
  const ScoreBoard({super.key, required this.score, required this.total, required
this.restartQuiz});
 
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text("Quiz Completed!", style: const TextStyle(fontSize: 24, fontWeight:
FontWeight.bold)),
          const SizedBox(height: 20),
          Text("Your Score: $score / $total", style: const TextStyle(fontSize: 22, color:
Colors.blue)),
          const SizedBox(height: 20),
          ElevatedButton(
            onPressed: restartQuiz,
            child: const Text("Restart Quiz"),
          ),
        ],
      ),
    );
  }
}