Author: saqibkhan

  • Step 1: Set Up Your Project

    Step 1: Set Up Your Project

    Create a new folder for your project and add the following files:

    • index.html
    • styles.css
    • script.js

    Step 2: HTML Structure

    In index.html, add the following code:

    htmlCopy code<!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;Weather App&lt;/title&gt;
    &lt;link rel="stylesheet" href="styles.css"&gt;
    </head> <body>
    &lt;div class="container"&gt;
        &lt;h1&gt;Weather App&lt;/h1&gt;
        &lt;input type="text" id="cityInput" placeholder="Enter city name"&gt;
        &lt;button id="getWeatherBtn"&gt;Get Weather&lt;/button&gt;
        &lt;div id="weatherResult"&gt;&lt;/div&gt;
    &lt;/div&gt;
    &lt;script src="script.js"&gt;&lt;/script&gt;
    </body> </html>

    Step 3: CSS Styling

    In styles.css, add some basic styles:

    cssCopy codebody {
    
    font-family: Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f0f0f0;
    margin: 0;
    } .container {
    text-align: center;
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    } input {
    padding: 10px;
    margin: 10px 0;
    width: 200px;
    } button {
    padding: 10px 20px;
    } #weatherResult {
    margin-top: 20px;
    }

    Step 4: JavaScript Logic

    In script.js, write the logic to fetch weather data from the API:

    javascriptCopy codeconst apiKey = 'YOUR_API_KEY'; // Replace with your OpenWeatherMap API key
    
    document.getElementById('getWeatherBtn').addEventListener('click', getWeather);
    
    async function getWeather() {
    
    const city = document.getElementById('cityInput').value;
    if (!city) {
        alert('Please enter a city name');
        return;
    }
    const url = https://api.openweathermap.org/data/2.5/weather?q=${city}&amp;amp;appid=${apiKey}&amp;amp;units=metric;
    try {
        const response = await fetch(url);
        if (!response.ok) throw new Error('City not found');
        
        const data = await response.json();
        displayWeather(data);
    } catch (error) {
        document.getElementById('weatherResult').innerText = error.message;
    }
    } function displayWeather(data) {
    const { name, main, weather } = data;
    const weatherResult = `
        &lt;h2&gt;Weather in ${name}&lt;/h2&gt;
        &lt;p&gt;Temperature: ${main.temp}°C&lt;/p&gt;
        &lt;p&gt;Condition: ${weather&#91;0].description}&lt;/p&gt;
    `;
    document.getElementById('weatherResult').innerHTML = weatherResult;
    }

    Step 5: Get Your API Key

    1. Sign up at OpenWeatherMap.
    2. Get your API key from the API keys section.
    3. Replace YOUR_API_KEY in the JavaScript code with your actual API key.

    Step 6: Run Your App

    Open index.html in your web browser. You should see a simple weather app where you can input a city name and get the current weather.Create a new folder for your project and add the following files:

    • index.html
    • styles.css
    • script.js

    Step 2: HTML Structure

    In index.html, add the following code:

    htmlCopy code<!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;Weather App&lt;/title&gt;
    &lt;link rel="stylesheet" href="styles.css"&gt;
    </head> <body>
    &lt;div class="container"&gt;
        &lt;h1&gt;Weather App&lt;/h1&gt;
        &lt;input type="text" id="cityInput" placeholder="Enter city name"&gt;
        &lt;button id="getWeatherBtn"&gt;Get Weather&lt;/button&gt;
        &lt;div id="weatherResult"&gt;&lt;/div&gt;
    &lt;/div&gt;
    &lt;script src="script.js"&gt;&lt;/script&gt;
    </body> </html>

    Step 3: CSS Styling

    In styles.css, add some basic styles:

    cssCopy codebody {
    
    font-family: Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f0f0f0;
    margin: 0;
    } .container {
    text-align: center;
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    } input {
    padding: 10px;
    margin: 10px 0;
    width: 200px;
    } button {
    padding: 10px 20px;
    } #weatherResult {
    margin-top: 20px;
    }

    Step 4: JavaScript Logic

    In script.js, write the logic to fetch weather data from the API:

    javascriptCopy codeconst apiKey = 'YOUR_API_KEY'; // Replace with your OpenWeatherMap API key
    
    document.getElementById('getWeatherBtn').addEventListener('click', getWeather);
    
    async function getWeather() {
    
    const city = document.getElementById('cityInput').value;
    if (!city) {
        alert('Please enter a city name');
        return;
    }
    const url = https://api.openweathermap.org/data/2.5/weather?q=${city}&amp;amp;appid=${apiKey}&amp;amp;units=metric;
    try {
        const response = await fetch(url);
        if (!response.ok) throw new Error('City not found');
        
        const data = await response.json();
        displayWeather(data);
    } catch (error) {
        document.getElementById('weatherResult').innerText = error.message;
    }
    } function displayWeather(data) {
    const { name, main, weather } = data;
    const weatherResult = `
        &lt;h2&gt;Weather in ${name}&lt;/h2&gt;
        &lt;p&gt;Temperature: ${main.temp}°C&lt;/p&gt;
        &lt;p&gt;Condition: ${weather&#91;0].description}&lt;/p&gt;
    `;
    document.getElementById('weatherResult').innerHTML = weatherResult;
    }

    Step 5: Get Your API Key

    1. Sign up at OpenWeatherMap.
    2. Get your API key from the API keys section.
    3. Replace YOUR_API_KEY in the JavaScript code with your actual API key.

    Step 6: Run Your App

    Open index.html in your web browser. You should see a simple weather app where you can input a city name and get the current weather.

  • Option 1: Flask (Python)

    Step 1: Set Up Your Environment

    1. Install Flask:
    pip install Flask
    1. Create a new Flask app: Create a file named app.py:
    from flask import Flask, render_template, request, redirect app = Flask(__name__) recipes = [] @app.route('/') def index(): return render_template('index.html', recipes=recipes) @app.route('/add', methods=['POST']) def add_recipe(): recipe = { 'title': request.form['title'], 'ingredients': request.form['ingredients'].split(','), 'instructions': request.form['instructions'] } recipes.append(recipe) return redirect('/') if __name__ == '__main__': app.run(debug=True)

    Step 2: Create Templates

    1. Create a templates folder and inside it, create index.html:
    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Recipe App</title> </head> <body> <h1>Recipe List</h1> <ul> {% for recipe in recipes %} <li> <strong>{{ recipe.title }}</strong><br> Ingredients: {{ recipe.ingredients | join(', ') }}<br> Instructions: {{ recipe.instructions }} </li> {% endfor %} </ul> <h2>Add a New Recipe</h2> <form method="POST" action="/add"> <input type="text" name="title" placeholder="Recipe Title" required><br> <textarea name="ingredients" placeholder="Ingredients (comma separated)" required></textarea><br> <textarea name="instructions" placeholder="Instructions" required></textarea><br> <button type="submit">Add Recipe</button> </form> </body> </html>

    Step 3: Run Your App

    Run your app with:

    python app.py
    

    Visit http://127.0.0.1:5000 in your web browser to see your recipe app!

    Option 2: React (JavaScript)

    Step 1: Set Up Your React App

    1. Create a new React app:
    npx create-react-app recipe-app cd recipe-app
    1. Install necessary packages (optional, for form handling):
    npm install axios

    Step 2: Create Components

    1. Create a RecipeForm.js component:
    javascriptCopy codeimport React, { useState } from 'react'; const RecipeForm = ({ addRecipe }) => { const [title, setTitle] = useState(''); const [ingredients, setIngredients] = useState(''); const [instructions, setInstructions] = useState(''); const handleSubmit = (e) => { e.preventDefault(); addRecipe({ title, ingredients: ingredients.split(','), instructions }); setTitle(''); setIngredients(''); setInstructions(''); }; return ( <form onSubmit={handleSubmit}> <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Recipe Title" required /> <textarea value={ingredients} onChange={(e) => setIngredients(e.target.value)} placeholder="Ingredients (comma separated)" required /> <textarea value={instructions} onChange={(e) => setInstructions(e.target.value)} placeholder="Instructions" required /> <button type="submit">Add Recipe</button> </form> ); }; export default RecipeForm;
    1. Create a RecipeList.js component:
    import React from 'react'; const RecipeList = ({ recipes }) => { return ( <ul> {recipes.map((recipe, index) => ( <li key={index}> <strong>{recipe.title}</strong><br /> Ingredients: {recipe.ingredients.join(', ')}<br /> Instructions: {recipe.instructions} </li> ))} </ul> ); }; export default RecipeList;
    1. Update App.js:
    javascriptCopy codeimport React, { useState } from 'react'; import RecipeForm from './RecipeForm'; import RecipeList from './RecipeList'; const App = () => { const [recipes, setRecipes] = useState([]); const addRecipe = (recipe) => { setRecipes([...recipes, recipe]); }; return ( <div> <h1>Recipe App</h1> <RecipeForm addRecipe={addRecipe} /> <RecipeList recipes={recipes} /> </div> ); }; export default App;

    Step 3: Run Your App

    Run your app with:

    npm start
    

    Visit http://localhost:3000 in your web browser to see your recipe app!

  • Step 1: Set Up Your Environment

    You’ll need Python installed on your machine. You can download it from python.org.

    Step 2: Create a New Python File

    Create a new file called finance_tracker.py.

    Step 3: Basic Structure

    Here’s a basic outline of your finance tracker:

    import json
    import os
    
    class FinanceTracker:
    
    def __init__(self):
        self.file_path = 'finance_data.json'
        self.data = self.load_data()
    def load_data(self):
        if os.path.exists(self.file_path):
            with open(self.file_path, 'r') as file:
                return json.load(file)
        return {'income': &#91;], 'expenses': &#91;]}
    def save_data(self):
        with open(self.file_path, 'w') as file:
            json.dump(self.data, file)
    def add_income(self, amount, source):
        self.data&#91;'income'].append({'amount': amount, 'source': source})
        self.save_data()
    def add_expense(self, amount, category):
        self.data&#91;'expenses'].append({'amount': amount, 'category': category})
        self.save_data()
    def get_balance(self):
        total_income = sum(item&#91;'amount'] for item in self.data&#91;'income'])
        total_expenses = sum(item&#91;'amount'] for item in self.data&#91;'expenses'])
        return total_income - total_expenses
    def display(self):
        print("Income:")
        for item in self.data&#91;'income']:
            print(f"Source: {item&#91;'source']}, Amount: {item&#91;'amount']}")
        print("\nExpenses:")
        for item in self.data&#91;'expenses']:
            print(f"Category: {item&#91;'category']}, Amount: {item&#91;'amount']}")
        print(f"\nCurrent Balance: {self.get_balance()}")
    def main():
    tracker = FinanceTracker()
    while True:
        print("\nPersonal Finance Tracker")
        print("1. Add Income")
        print("2. Add Expense")
        print("3. View Data")
        print("4. Exit")
        choice = input("Choose an option: ")
        if choice == '1':
            amount = float(input("Enter income amount: "))
            source = input("Enter source of income: ")
            tracker.add_income(amount, source)
        elif choice == '2':
            amount = float(input("Enter expense amount: "))
            category = input("Enter category of expense: ")
            tracker.add_expense(amount, category)
        elif choice == '3':
            tracker.display()
        elif choice == '4':
            break
        else:
            print("Invalid choice. Please try again.")
    if __name__ == "__main__":
    main()

    Step 4: Explanation of the Code

    1. Imports: We import json for data storage and os for file handling.
    2. FinanceTracker Class: This class handles loading, saving, adding income/expenses, calculating balance, and displaying data.
      • load_data: Loads data from a JSON file.
      • save_data: Saves the current data to a JSON file.
      • add_income and add_expense: Methods to add income and expenses.
      • get_balance: Calculates the current balance.
      • display: Displays all income and expenses, along with the current balance.
    3. Main Function: This function provides a simple text menu for user interaction.

    Step 5: Running the Application

    1. Open your terminal or command prompt.
    2. Navigate to the directory where you saved finance_tracker.py.
    3. Run the script using the command:
    python finance_tracker.py

    Step 6: Features to Consider Adding

    Once you have the basic tracker running, you can consider adding features like:

    • Categories for income and expenses.
    • Graphical representation of your financial data using libraries like matplotlib.
    • Monthly reports or summaries.
    • Data export options (e.g., to CSV).
  • What is Dart Sass?

    Dart Sass is the primary implementation of Sass, a popular CSS preprocessor. Sass adds features like variables, nested rules, mixins, and more, making your CSS more maintainable and easier to write.

    Setting Up Dart Sass

    1. Install Dart Sass: You can install Dart Sass via npm. If you don’t have Node.js and npm installed, download them from Node.js.
    npm install -g sass
    1. Create a Project Directory: Create a new directory for your project and navigate into it.
    mkdir my-sass-project cd my-sass-project
    1. Create a Sass File: Create a .scss file (e.g., styles.scss).
    // styles.scss $primary-color: #3498db; $padding: 10px; body { font-family: Arial, sans-serif; background-color: $primary-color; padding: $padding; h1 { color: white; text-align: center; } p { color: darken($primary-color, 10%); padding: $padding; } }
    1. Compile Sass to CSS: To compile your Sass file to CSS, run the following command:
    sass styles.scss styles.css 
    1. This command will generate a styles.css file with the compiled CSS.

    Basic Sass Features

    1. Variables: Variables allow you to store values that you can reuse throughout your stylesheet.
    $font-stack: Helvetica, sans-serif; $primary-color: #333; body { font-family: $font-stack; color: $primary-color; }
    1. Nesting: Sass allows you to nest your CSS selectors in a way that follows the same visual hierarchy of your HTML.
    nav { ul { list-style: none; padding: 0; li { display: inline; margin-right: 15px; a { text-decoration: none; color: $primary-color; } } } }
    1. Mixins: Mixins let you create reusable styles that can accept arguments.
    @mixin rounded-corners($radius) { border-radius: $radius; -webkit-border-radius: $radius; -moz-border-radius: $radius; } .box { @include rounded-corners(10px); background-color: $primary-color; padding: $padding; }
    1. Functions: Sass has built-in functions, and you can also create your own.
    @function calculate-rem($pixels) { @return $pixels / 16 * 1rem; } body { font-size: calculate-rem(16px); }

    Watching for Changes

    To automatically compile Sass whenever you make changes, use the --watch flag:

    sass --watch styles.scss:styles.css
    
  • Getting Started with StageXL

    Installation:

    1. Install Dart SDK.
    2. Create a new Dart project and add the StageXL dependency to your pubspec.yaml:yamlCopy codedependencies: stagexl: ^2.0.0

    Basic Setup:

    dartCopy codeimport 'dart:html';
    import 'package:stagexl/stagexl.dart';
    
    void main() {
      // Create a Stage
      var canvas = CanvasElement(width: 800, height: 600);
      document.body.append(canvas);
      
      var stage = Stage(canvas);
      var renderLoop = RenderLoop();
      renderLoop.addStage(stage);
      
      // Background Color
      stage.stageColor = Color.Black;
    }
    

    2. Drawing Shapes

    Creating Shapes:

    void createShapes(Stage stage) {
      var rectangle = Shape()
    
    ..graphics.rect(50, 50, 200, 100)
    ..graphics.fillColor(Color.Red);
    stage.addChild(rectangle); }

    3. Loading Images

    Image Loading Example:

    void loadImage(Stage stage) {
      var loader = BitmapData.load('path/to/image.png');
      loader.onLoad.listen((_) {
    
    var bitmap = Bitmap(loader.data);
    bitmap.x = 100;
    bitmap.y = 100;
    stage.addChild(bitmap);
    }); }

    4. Handling Events

    Mouse Click Event:

    void setupMouseEvents(Stage stage) {
      stage.onMouseClick.listen((MouseEvent e) {
    
    print('Mouse clicked at: ${e.stageX}, ${e.stageY}');
    }); }

    5. Animation Loop

    Creating an Animation:

    void animate(Stage stage) {
      var circle = Shape()
    
    ..graphics.circle(50, 50, 30)
    ..graphics.fillColor(Color.Blue);
    stage.addChild(circle); int dx = 2; // change in x stage.onEnterFrame.listen((_) {
    circle.x += dx;
    if (circle.x > stage.stageWidth || circle.x &lt; 0) {
      dx = -dx; // Reverse direction
    }
    }); }

    6. Using Tiled Backgrounds

    Tile a Background:

    void createTiledBackground(Stage stage) {
      var bitmapData = BitmapData.load('path/to/tile.png');
      
      for (var i = 0; i < stage.stageWidth; i += 50) {
    
    for (var j = 0; j &lt; stage.stageHeight; j += 50) {
      var tile = Bitmap(bitmapData.data)
        ..x = i
        ..y = j;
      stage.addChild(tile);
    }
    } }

    7. Text and Fonts

    Adding Text:

    void addText(Stage stage) {
      var textField = TextField()
    
    ..text = 'Hello, StageXL!'
    ..defaultTextFormat = TextFormat('Arial', 24, Color.White);
    stage.addChild(textField); }

    8. Building a Simple Game Loop

    Game Loop Example:

    void gameLoop(Stage stage) {
      var player = Shape()
    
    ..graphics.rect(0, 0, 50, 50)
    ..graphics.fillColor(Color.Green);
    stage.addChild(player); stage.onEnterFrame.listen((_) {
    // Update player position, handle input, etc.
    player.x += 1;
    if (player.x > stage.stageWidth) {
      player.x = 0; // Reset position
    }
    }); }
  • Step 1: Set Up Your Development Environment

    1. Install Dart SDK: Make sure you have the Dart SDK installed. You can download it from Dart’s official site.
    2. Install AngularDart: Create a new Dart project using the Dart command-line tools. Open your terminal and run:
    dart create -t web-angular my_angular_app cd my_angular_app
    1. Add AngularDart Dependency: Open the pubspec.yaml file and add AngularDart dependencies:yamlCopy codedependencies: angular: ^6.0.0 Then run:
    dart pub get

    Step 2: Create a Simple Component

    1. Create a Component: In the lib directory, create a new file called app_component.dart.
    import 'package:angular/angular.dart'; @Component( selector: 'my-app', template: ''' <h1>Hello, AngularDart!</h1> <input [(ngModel)]="name" placeholder="Enter your name"> <p>Your name is: {{ name }}</p> ''', directives: [coreDirectives], ) class AppComponent { String name = ''; }
    1. Update the Main Entry Point: In lib/main.dart, update the code to bootstrap the AngularDart app.
    import 'package:angular/angular.dart'; import 'package:my_angular_app/app_component.dart'; void main() { bootstrap(AppComponent); }

    Step 3: Run Your Application

    1. Build and Serve the Application: You can run your application using:
    webdev serve
    1. Open in a Browser: Navigate to http://localhost:8080 in your browser. You should see the header and the input field.

    Step 4: Add Styles

    You can add styles to your application. Create a styles.css file in the web directory:

    h1 {
      color: blue;
    }
    
    input {
      margin: 10px;
    }
    

    Then link it in web/index.html:

    <head>
      <link rel="stylesheet" type="text/css" href="styles.css">
    </head>
    
  • Setting Up Dart DevTools

    1. Install Flutter SDK (if you haven’t already): Make sure you have Flutter installed. You can check this by running:
    flutter --version
    1. Create a Flutter Project: You can create a new Flutter project using:
    flutter create my_app cd my_app
    1. Run Your App: Launch your app in debug mode:
    flutter run
    1. Open Dart DevTools: After your app starts, you’ll see a message in the terminal that includes a link to Dart DevTools. Click on the link, or run:bashCopy codeflutter pub global run devtools

    Features of Dart DevTools

    Dart DevTools provides several powerful features:

    1. Performance Monitoring:
      • You can analyze the performance of your app. Look for the Performance tab in DevTools to view CPU and memory usage.
      • You can record and inspect frames, helping you identify performance bottlenecks.
    2. Widget Inspector:
      • Use the Inspector tab to view the widget tree. This helps you visualize the layout of your widgets.
      • Click on a widget in the UI to see its properties in the inspector.
    3. Debugging:
      • Use the Debugger tab to set breakpoints, step through code, and inspect variables.
      • You can pause your app execution to inspect the state of your application at any point.
    4. Logging:
      • The Logging tab provides a console to see your app’s logs and debug messages. Use print() statements in your code to output messages.

    Example Code Snippet

    Here’s a simple Flutter app to demonstrate how to use Dart DevTools effectively:

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
    
    return MaterialApp(
      title: 'Dart DevTools Demo',
      home: MyHomePage(),
    );
    } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() {
    setState(() {
      _counter++;
      print('Counter incremented to $_counter'); // Log statement for debugging
    });
    } @override Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dart DevTools Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: &lt;Widget>&#91;
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
    } }

    Using Dart DevTools

    1. Running the App: Run the app using flutter run.
    2. Inspecting Widgets: Click on the FloatingActionButton in the UI and then use the Inspector tab to see its properties and hierarchy.
    3. Setting Breakpoints: Open the Debugger tab, find the _incrementCounter method, and set a breakpoint. When you click the button, the debugger will pause execution at the breakpoint, allowing you to inspect the value of _counter.
  • Step 1: Setting Up Your Environment

    1. Install Dart SDK: Make sure you have the Dart SDK installed. You can download it from the Dart SDK website.
    2. Install Aqueduct: Use the following command to install Aqueduct globally.
    pub global activate aqueduct

    Step 2: Create a New Aqueduct Project

    1. Create a new project:
    aqueduct create my_aqueduct_app cd my_aqueduct_app
    1. Run the application:
    aqueduct serve Your server should now be running at http://localhost:8888.

    Step 3: Define Your Model

    Create a model for your application. For example, let’s create a simple Task model.

    1. Create a new model:In lib/model/task.dart, add the following code:
    import 'package:aqueduct/aqueduct.dart'; class Task extends ManagedObject<_Task> implements _Task {} class _Task { @primaryKey int id; String title; bool completed; }

    Step 4: Set Up Database Configuration

    1. Configure the database:In config.yaml, configure your database connection. For example, if you’re using PostgreSQL, it would look something like this:
    database: host: localhost port: 5432 username: your_username password: your_password databaseName: your_database_name
    1. Migrate the database:Run the following command to create the database tables:bashCopy codeaqueduct db generate aqueduct db upgrade

    Step 5: Create a Controller

    Create a controller to manage the Task model.

    1. Create a controller:In lib/controller/task_controller.dart, add the following code:
    import 'package:aqueduct/aqueduct.dart'; import '../model/task.dart'; class TaskController extends ResourceController { TaskController(this.context); final ManagedContext context; @Operation.get() Future<Response> getAllTasks() async { final tasks = await context.fetch<Task>(); return Response.ok(tasks); } @Operation.post() Future<Response> createTask(@Bind.body() Task task) async { final insertedTask = await context.insertObject(task); return Response.ok(insertedTask); } }

    Step 6: Set Up the Router

    1. Add the router:In lib/my_aqueduct_app.dart, set up the router to use your TaskController:
    import 'package:aqueduct/aqueduct.dart'; import 'controller/task_controller.dart'; import 'model/task.dart'; class MyAqueductApp extends ApplicationChannel { @override Future prepare() async { // Database setup final config = DatabaseConfiguration(options["database"]); final database = PostgreSQLPersistentStore.fromConnectionInfo( config.username, config.password, config.host, config.port, config.databaseName); context = ManagedContext(dataModel, database); } ManagedContext context; @override Controller get entryPoint { final router = Router(); router.route("/tasks").link(() => TaskController(context)); return router; } }

    Step 7: Test Your Application

    1. Run the server again:bashCopy codeaqueduct serve
    2. Use an API testing tool (like Postman or curl) to test your endpoints:
      • GET all tasks:
    curl http://localhost:8888/tasks
    1. Create a new task:
    curl -X POST http://localhost:8888/tasks -H "Content-Type: application/json" -d '{"title": "My first task", "completed": false}'
  • What’s the use of Navigation.push in Flutter?

    The role of Navigation.push in Flutter is to add a route to a bundle of other routes which are managed by the navigator.

  • What is used to import packages for your project?

    pubspec.yaml file is used to import packages in the Dart code. It allows us to set the constraints for the application. This file contains project dependencies, general project settings, and project assets.