Category: Projects

  • StageXL

    Setting Up

    1. Create a new Dart project:
    dart create -t console my_stagexl_project cd my_stagexl_project
    1. Add StageXL to your pubspec.yaml:
    dependencies: stagexl: ^3.0.0
    1. Run dart pub get to install the dependency.

    Basic Example

    Here’s a simple example of a StageXL application that displays a rectangle and handles a mouse click event.

    main.dart

    import 'dart:html';
    import 'package:stagexl/stagexl.dart';
    
    void main() {
      // Create a Stage and Render the Canvas
      var canvas = querySelector('#stage') as CanvasElement;
      var stage = Stage(canvas);
      var renderLoop = RenderLoop();
      renderLoop.addStage(stage);
    
      // Create a simple rectangle
      var rectangle = Shape()
    
    ..graphics.rect(100, 100, 200, 100)
    ..graphics.fillColor(Color.Blue);
    // Add the rectangle to the stage stage.addChild(rectangle); // Add mouse click event rectangle.onMouseClick.listen((event) {
    rectangle.graphics.clear();
    rectangle.graphics.fillColor(Color.Red);
    rectangle.graphics.rect(100, 100, 200, 100);
    rectangle.graphics.fill();
    }); // Start the render loop renderLoop.start(); }

    HTML Setup

    Make sure you have an HTML file to load your Dart application. Create index.html:

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>StageXL Example</title>
      <script defer src="main.dart.js"></script>
      <style>
    
    canvas {
      background-color: #f0f0f0;
    }
    </style> </head> <body> <canvas id="stage" width="800" height="600"></canvas> </body> </html>

    Build and Run

    1. Build your Dart application:
    dart compile js main.dart -o main.dart.js
    1. Open index.html in your browser.

    Explanation

    • Stage: Represents the main area where you draw.
    • Shape: Used to create shapes (like rectangles) that you can draw on the stage.
    • RenderLoop: A loop that continuously renders the stage.
  • Shelf

    Step 1: Set Up HTML

    Create an index.html file:

    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;Digital Bookshelf&lt;/title&gt;
    &lt;link rel="stylesheet" href="styles.css"&gt;
    </head> <body>
    &lt;div class="container"&gt;
        &lt;h1&gt;My Digital Bookshelf&lt;/h1&gt;
        &lt;form id="book-form"&gt;
            &lt;input type="text" id="book-title" placeholder="Book Title" required&gt;
            &lt;input type="text" id="book-author" placeholder="Author" required&gt;
            &lt;button type="submit"&gt;Add Book&lt;/button&gt;
        &lt;/form&gt;
        &lt;div id="shelf" class="shelf"&gt;&lt;/div&gt;
    &lt;/div&gt;
    &lt;script src="script.js"&gt;&lt;/script&gt;
    </body> </html>

    Step 2: Add Some Style

    Create a styles.css file:

    cssCopy codebody {
    
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    color: #333;
    } .container {
    width: 80%;
    max-width: 600px;
    margin: auto;
    padding: 20px;
    background: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    } h1 {
    text-align: center;
    } form {
    display: flex;
    flex-direction: column;
    margin-bottom: 20px;
    } input {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    } button {
    padding: 10px;
    background-color: #5cb85c;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    } button:hover {
    background-color: #4cae4c;
    } .shelf {
    display: flex;
    flex-wrap: wrap;
    } .book {
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 10px;
    margin: 5px;
    width: calc(33.333% - 10px);
    box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
    }

    Step 3: Add Functionality with JavaScript

    Create a script.js file:

    javascriptCopy codedocument.getElementById('book-form').addEventListener('submit', function (e) {
    
    e.preventDefault();
    
    const title = document.getElementById('book-title').value;
    const author = document.getElementById('book-author').value;
    addBookToShelf(title, author);
    // Clear the input fields
    document.getElementById('book-title').value = '';
    document.getElementById('book-author').value = '';
    }); function addBookToShelf(title, author) {
    const shelf = document.getElementById('shelf');
    const bookDiv = document.createElement('div');
    bookDiv.className = 'book';
    bookDiv.innerHTML = &amp;lt;strong&amp;gt;${title}&amp;lt;/strong&amp;gt;&amp;lt;br&amp;gt;&amp;lt;em&amp;gt;${author}&amp;lt;/em&amp;gt;;
    
    shelf.appendChild(bookDiv);
    }

    How It Works

    1. HTML: The form collects the book title and author.
    2. CSS: Basic styles for the layout and appearance of the bookshelf.
    3. JavaScript: When the form is submitted, the book title and author are added to the shelf, and the input fields are cleared.

    Running the Project

    1. Save all three files in the same directory.
    2. Open index.html in a web browser.
  • Routemaster

    Setup a Basic Express Server with Routing

    1. Install Express: Make sure you have Node.js installed. Then create a new directory for your project and install Express:
    mkdir my-routemaster cd my-routemaster npm init -y npm install express
    1. Create the Server: Create a file named server.js:
    const express = require('express'); const app = express(); const PORT = 3000; // Define routes app.get('/', (req, res) => { res.send('Welcome to the Routemaster!'); }); app.get('/about', (req, res) => { res.send('This is the about page.'); }); app.get('/contact', (req, res) => { res.send('This is the contact page.'); }); // Start the server app.listen(PORT, () => { console.log(Server is running on http://localhost:${PORT}); });
    1. Run the Server: Start your server by running:
    node server.js
    1. Access the Routes: Open your browser and go to:
      • http://localhost:3000/ for the home page
      • http://localhost:3000/about for the about page
      • http://localhost:3000/contact for the contact page
  • Moor

    Step 1: Add Dependencies

    First, add the required dependencies to your pubspec.yaml:

    dependencies:
      drift: ^2.4.0
      drift_flutter: ^2.4.0
      sqlite3_flutter_libs: ^0.5.0 # For SQLite support
    
    dev_dependencies:
      build_runner: ^2.3.0
      drift_dev: ^2.4.0
    

    Step 2: Create a Database Model

    Create a new Dart file for your database model, e.g., database.dart.

    import 'package:drift/drift.dart';
    import 'package:drift/native.dart';
    
    part 'database.g.dart'; // The part directive for code generation
    
    @DataClassName('Task') // The class that will represent a row
    class Tasks extends Table {
      IntColumn get id => integer().autoIncrement()(); // Auto-incrementing ID
      TextColumn get name => text().withLength(min: 1, max: 50)(); // Task name
      BoolColumn get isComplete => boolean().withDefault(Constant(false))(); // Completion status
    }
    
    @DriftDatabase(tables: [Tasks])
    class AppDatabase extends _$AppDatabase {
      AppDatabase() : super(NativeDatabase.memory()); // Use in-memory database for testing
    
      @override
      int get schemaVersion => 1;
    
      // Define methods for database operations
      Future<List<Task>> getAllTasks() => select(tasks).get();
      Future insertTask(Insertable<Task> task) => into(tasks).insert(task);
      Future updateTask(Insertable<Task> task) => update(tasks).replace(task);
      Future deleteTask(Insertable<Task> task) => delete(tasks).delete(task);
    }
    

    Step 3: Generate the Code

    Run the following command to generate the necessary code:

    flutter pub run build_runner build
    

    This will create a file named database.g.dart with the generated code.

    Step 4: Use the Database

    Now you can use the database in your Flutter app. Here’s a simple example of how to use it:

    import 'package:flutter/material.dart';
    import 'database.dart'; // Import your database model
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
    
    return MaterialApp(
      home: TaskList(),
    );
    } } class TaskList extends StatefulWidget { @override _TaskListState createState() => _TaskListState(); } class _TaskListState extends State<TaskList> { late AppDatabase _database; @override void initState() {
    super.initState();
    _database = AppDatabase(); // Initialize the database
    } Future<void> _addTask(String name) async {
    final task = TasksCompanion(
      name: Value(name),
      isComplete: Value(false),
    );
    await _database.insertTask(task);
    setState(() {}); // Refresh the UI
    } Future<List<Task>> _fetchTasks() async {
    return await _database.getAllTasks();
    } @override Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Tasks')),
      body: FutureBuilder&lt;List&lt;Task>>(
        future: _fetchTasks(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(child: CircularProgressIndicator());
          }
          final tasks = snapshot.data ?? &#91;];
          return ListView.builder(
            itemCount: tasks.length,
            itemBuilder: (context, index) {
              final task = tasks&#91;index];
              return ListTile(
                title: Text(task.name),
                trailing: Checkbox(
                  value: task.isComplete,
                  onChanged: (value) {
                    // Update task completion status
                    final updatedTask = task.copyWith(isComplete: value);
                    _database.updateTask(updatedTask);
                    setState(() {}); // Refresh the UI
                  },
                ),
              );
            },
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // Add a new task (for example)
          _addTask('New Task');
        },
        child: Icon(Icons.add),
      ),
    );
    } }

    Step 5: Run the App

    Run your Flutter app, and you should see a simple task list that allows you to add and check off tasks!

  • 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}'