mafs_flutter library

A Flutter library for creating interactive math visualizations.

Mafs Flutter is a port of the React Mafs library, providing a declarative API for building interactive mathematical visualizations with pan and zoom support.

Note: This library has no Material or Cupertino dependencies—it uses only dart:ui, rendering, and widgets layers.

Getting Started

The main entry point is the Mafs widget, which sets up the coordinate system and provides context to child widgets:

import 'dart:math' as math;
import 'package:flutter/widgets.dart';
import 'package:mafs_flutter/mafs_flutter.dart';

Mafs(
  viewBox: const ViewBox(x: (-5, 5), y: (-5, 5)),
  pan: true,
  zoom: true,
  children: [
    Coordinates.cartesian(),
    Plot.ofX(y: (x) => math.sin(x), color: MafsColors.blue),
    MafsPoint(x: 0, y: 0),
  ],
)

Display Components

Interaction

Core Concepts

  • ViewBox: Defines the visible coordinate range in math units
  • Coordinate System: Y-axis increases upward (mathematical convention)
  • Transforms: Nest MafsTransform to apply geometric transformations
  • Theme: Use MafsTheme and MafsColors for consistent styling

Example: Interactive Distance Calculator

class DistanceDemo extends StatefulWidget {
  @override
  State<DistanceDemo> createState() => _DistanceDemoState();
}

class _DistanceDemoState extends State<DistanceDemo> {
  Offset _point1 = const Offset(1, 1);
  Offset _point2 = const Offset(-1, -1);

  double get _distance {
    final dx = _point1.dx - _point2.dx;
    final dy = _point1.dy - _point2.dy;
    return math.sqrt(dx * dx + dy * dy);
  }

  @override
  Widget build(BuildContext context) {
    return Mafs(
      viewBox: const ViewBox(x: (-3, 3), y: (-3, 3)),
      children: [
        Coordinates.cartesian(),
        MovablePoint(
          point: _point1,
          onMove: (p) => setState(() => _point1 = p),
        ),
        MovablePoint(
          point: _point2,
          onMove: (p) => setState(() => _point2 = p),
        ),
        Line.segment(point1: _point1, point2: _point2),
        MafsText(
          x: 0,
          y: 2,
          text: 'd = ${_distance.toStringAsFixed(2)}',
        ),
      ],
    );
  }
}

Classes

AxisOptions
Configuration options for an axis.
CameraController
A controller for camera pan and zoom interactions.
CameraState
Camera state for pan and zoom interactions.
CartesianCoordinates
A Cartesian coordinate system with grid lines, axes, and labels.
CoordinateContext
An inherited widget that provides coordinate system information to descendants.
CoordinateContextData
Data class containing coordinate system bounds and viewport dimensions.
Coordinates
Namespace for coordinate system factories.
LaTeXStyle
Style information for LaTeX rendering.
Line
A namespace containing different line component variants.
LinePointAngle
An infinite line at a point with a given angle.
LinePointSlope
An infinite line at a point with a given slope.
LineSegment
A line segment between two points.
LineThroughPoints
An infinite line passing through two points.
Mafs
The root widget for Mafs visualizations.
MafsCircle
A widget that renders a circle in Mafs coordinates.
MafsColors
Default theme colors for Mafs visualizations.
MafsEllipse
A widget that renders an ellipse in the Mafs coordinate system.
MafsLaTeX
A widget that renders LaTeX mathematical notation at a specific coordinate.
MafsPoint
A point displayed at a specific coordinate.
MafsPolygon
A widget that renders a closed polygon in the Mafs coordinate system.
MafsPolyline
A widget that renders an open polyline in the Mafs coordinate system.
MafsText
Text displayed at a specific coordinate.
MafsTheme
An inherited widget that provides MafsThemeData to descendants.
MafsThemeData
Theme data for Mafs visualizations.
MafsTransform
A widget that applies geometric transformations to its children in math space.
MafsVector
A vector (arrow) from a tail point to a tip point.
MafsWidget
A widget that positions any Flutter widget at math coordinates.
MatrixBuilder
A builder for creating matrices from a chain of transformations.
MatrixOps
Matrix operations for 2D transformations.
MovablePoint
A draggable point that can be moved around the coordinate system.
PaneContext
An inherited widget that provides pane information for efficient rendering.
PaneContextData
Data class containing pane information for efficient infinite plot rendering.
PaneManager
A widget that computes and provides pane context based on coordinate context.
Plot
A namespace containing different plot component variants.
PlotOfX
A widget that plots y = f(x) functions.
PlotOfY
A widget that plots x = f(y) functions.
PlotParametric
A widget that renders a parametric curve.
PolarCoordinates
A polar coordinate system with concentric circles and radial lines.
RenderLineSegment
The render object for LineSegment.
RenderLineThroughPoints
The render object for LineThroughPoints.
RenderMafsEllipse
The render object for MafsEllipse.
RenderMafsPoint
The render object for MafsPoint.
RenderMafsPolyBase
Base render object for polygon and polyline rendering.
RenderMafsPolygon
The render object for MafsPolygon.
RenderMafsPolyline
The render object for MafsPolyline.
RenderMafsText
The render object for MafsText.
RenderMafsVector
The render object for MafsVector.
RenderPlotParametric
The render object for PlotParametric.
RenderPolarCoordinates
Render object for PolarCoordinates.
SpanContext
An inherited widget that provides coordinate span information to descendants.
SpanContextData
Data class containing the span (range) of the visible coordinate system.
TransformContext
An inherited widget that provides transformation matrices to descendants.
TransformContextData
Data class containing transformation matrices for Mafs rendering.
ViewBox
Configuration for the viewable area of a Mafs visualization.
ZoomConfig
Configuration for zoom behavior.

Enums

Anchor
Anchor positions for alignment.
CardinalDirection
Cardinal directions for positioning text relative to a point.
CoordinateAspect
Aspects of CoordinateContext that can be depended on independently.
PreserveAspectRatio
How to handle aspect ratio when the viewport doesn't match the viewBox.
StrokeStyle
Common stroke styles for Mafs elements.
TransformAspect
Aspects of TransformContext that can be depended on independently.

Mixins

FilledStyle
Mixin that provides common styling properties for filled shapes.
StrokedStyle
Mixin that provides common styling properties for stroked shapes.

Extensions

Vec2 on Offset
Extension methods for 2D vector operations on Offset.

Functions

clamp(double number, double min, double max) → double
Clamp a number between min and max.
computeAnchor(Anchor anchor, double x, double y, double width, double height) → (double, double)
Given an anchor and a bounding box, compute the x and y coordinates such that rendering an element at those coordinates will align it with the anchor.
defaultLabelMaker(double value) → String
Default label maker that formats numbers nicely.
pickClosestToValue(double value, List<double> options) → ({int index, double value})
Find the value in options closest to value.
range(double min, double max, [double step = 1]) → List<double>
Generate a list of numbers from min to max (inclusive) with step.
round(double value, [int precision = 0]) → double
Round a value to the specified precision decimal places.
roundToNearestPowerOf10(double value) → double
Round a value to the nearest power of 10.
sampleParametric(Offset fn(double t), (double, double) domain, int minDepth, int maxDepth, double threshold) → List<Offset>
Sample a parametric function and return a list of points.

Typedefs

ConstraintFunction = Offset Function(Offset position)
Function that constrains a point's position.
Interval = (double, double)
An interval represented as (min, max).
LabelMaker = String Function(double value)
Function that creates a label string from a numeric value.
LaTeXBuilder = Widget Function(BuildContext context, LaTeXStyle style)
Builder function for custom LaTeX rendering.
Matrix2D = (double, double, double, double, double, double)
Mafs' internal linear algebra functions.
PointCallback = void Function(Offset point)
Callback for tap/click events on the Mafs canvas.