Flutter

flutter-cover
Use TwicPics Flutter Widget to get images best practices out-of-the-box.

TwicPics Flutter Widget is available as a Flutter Package.

Installation

Add the twicpics_components package to your Flutter project by running:

$ flutter pub add twicpics_components

Setup

Install TwicPics in your Flutter project

You will need a TwicPics domain to initialize the package. Create an account for free to get your domain.
// main.dart

import 'package:twicpics_components/twicpics_components.dart';

void main() {
  install(
    domain: "https://<your-domain>.twic.pics/",
  );
  runApp(...);
}

For an exhaustive list of options, see Setup Options.

Setup Options

OptionDescriptionTypeDefault
cacheCleanOnStartUpClears the cache when the application starts.booleanfalse
cacheStalePeriodDefines the duration of validity of a cached asset.DurationDuration( days: 7)
cacheMaxNrOfObjectsDefines how large the cache is allowed to be.Integer200
debugActivate logs from the cache manager.booleanfalse
domainThis is your very own TwicPics domain. Providing it is mandatory.String
maxDPRTwicPics will take the "Device Pixel Ratio" (DPR) of the current device into consideration when determining the sizes of images to load. By default, it will not take a DPR greater than 2 into consideration. If the DPR of the device is higher than 2, TwicPics will assume it to be 2. Using maxDPR, you can lower this limit down to 1 or be more permissive (for instance by setting it to 3 or 4).Number2
pathPath to prepend to all src attributes. For instance, if path is "some/folder" then a src attribute set to "image.jpg" will be expanded into "some/folder/image.jpg"String
stepTo avoid requesting too may variants of the same image, TwicPics will round the width of images to the closest multiple of step. The height will then be computed in order to respect the original aspect ratio.Integer50

Usage

TwicImg comes as a Flutter Widget and is used as such.

Basic usage

// my_widget.dart

import 'package:twicpics_components/twicpics_components.dart';

class MyWidget extends StatelessWidget {
  const MyWidget({super.key});
  
  Widget build(BuildContext context) {
    return TwicImg(
      src: 'path/to/my/image',
    );
  }
}

Bulk loading

When embedding TwicImg in a lazily loading-compatible tree, it is recommended to disable TwcImg's lazy-loading feature:

// grid_sample.dart

class GridSample extends StatelessWidget {
  const GridSample({super.key});
  
    Widget build(BuildContext context) {
      return GridView.count(
        primary: false,
        crossAxisCount: 3,
        children: [
          TwicImg(
            src: 'path/to/my/image',
            eager: true,
          ),
          // ...
        ]
      );
}

Working with ratio="none"

Allows to display an image with a free height while respecting its natural aspect ratio.

Hero image

An image that occupies all available space:

// hero_sample.dart

import 'package:flutter/material.dart';
import 'package:twicpics_components/twicpics_components.dart';

class HeroSample extends StatelessWidget {
  const HeroSample({super.key});
  
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      child: TwicImg(
        src: 'path/to/my/image.jpg',
          ratio: 'none',
        ),
    );
  }
}

Hero banner

You can specify the height of your image while respecting its natural aspect ratio and optimizing your Cumulative Layout Shift (CLS) metric.

// hero_banner.dart

import 'package:flutter/material.dart';
import 'package:twicpics_components/twicpics_components.dart';

class HeroBanner extends StatelessWidget {
  const HeroBanner({super.key});
  
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      height: 200,
      child: TwicImg(
        src: 'path/to/my/image.jpg',
        ratio: 'none',
      ),
    );
  }
}

Working with Row Widget

When using Row Widget you have to constrain available width for TwicImg as in:

import 'package:flutter/material.dart';
import 'package:twicpics_components/twicpics_components.dart';

class RomSample extends StatelessWidget {
  const RomSample({super.key});
  
  Widget build(BuildContext context) {
    return Row(
      children: [
        SizedBox(
          width: 100, //fixed width
          child: TwicImg(
            src:'path/to/my/image.jpg',
          ),
        ),
        Expanded( // makes child fills the available space
          child: TwicImg(
            src:'path/to/my/image.jpg',
          ),
        ),
      ],
    );
  }
}

Widget Properties

TwicImg

TwicImg( 
  { 
      Key? key,
      TwicPosition? anchor,
      bool? eager,
      String? focus,
      String? intrinsic,
      TwicMode? mode,
      TwicPlaceholder? placeholder,
      TwicPosition? position,
      String? preTransform,
      <String? | double?> ratio,
      required String src,
      int? step,
      Duration? transitionDuration,
  } 
)
AttributeDescriptionTypeDefault
keyKeeps widget state when parent tree rebuilds.Key
anchorPositions the image in both TwicMode.contain and TwicMode.cover mode. position and focus take precedence in TwicMode.contain and TwicMode.cover mode respectively. Please note that anchor is applied after an eventual preTransform.TwicPosition
eagerLoad the image as soon as the widget is mounted. This effectively means disabling lazy loading for this image. Recommended when TwicImg is placed within a parent that natively handles lazy-loading.booleanfalse
focusSets the focus point in TwicMode.cover mode. focus takes precedence over anchor when both are provided. See the TwicPics focus attribute documentation for more information. Only use this attribute if you need a specific focus point or if you want to leverage smart cropping with focus="auto": if you only need border-based positionning (TwicPosition values), use anchor instead.String
intrinsicDimensions in pixels of the original image, formatted <width>x<height> (eg. 1920x1080). It prevents image upscaling and limits the number of generated variants. If using preTransform, you should specify the intrinsic dimensions of the resulting image. Using incorrect values can lead to display issues, see the intrinsic attribute documentation. String
modeDetermines if the image fills the area and is cropped accordingly (TwicMode.cover) or if the image will sit inside the area with no cropping (TwicMode.contain).TwicModeTwicMode.cover
placeholderDisplays a low quality version before the final image is actually loaded.TwicPlaceholderTwicPlaceholder.preview
positionPositions the image in TwicMode.contain mode. position takes precedence over anchor when both are provided. Only use this property if you need precise positionning: if you only need border-based positionning (TwicPosition values), use anchor instead.TwicPositionTwicPosition.center
preTransformA slash-separated list of TwicPics API transformations to be performed before resizing the image (see the TwicPics Manipulation documentation). Note that anchor and focus are applied after preTransform: if you need to specify a specific focus point for your preTransform then it needs to be part of the expression (like preTransform="focus=auto/crop=50px50p" for instance). Be aware that using this option can lead to unexpected results so use with caution!String
ratioA unitless width/height or width:height value pair (as in 4/3 or 4:3) that defines the aspect ratio of the display area. If height is not specified, it is assumed to be 1. A square area will be created by default. When set to none, ratio is determined based on width and height as computed by the Flutter following the parent size definitions. You are responsible for properly sizing the component when ratio="none".String or number1
srcMandatory path to the image.String
stepSee the TwicPics step attribute documentation for more information.int
transitionDurationDuration of the transition effect between placeholder and the final image.DurationDuration( milliseconds: 400 )

TwicMode enum

Defines how assets should be resized to fit its container.

ValueDescription
containresize asset so that it completely fits inside the target area while conserving the original aspect ratio.
coverresize asset so that it completely fills the target area while conserving the original aspect ratio.

TwicPosition enum

Defines a position within the parent container.

ValueDescription
bottomThe center point along the bottom edge.
bottomLeftThe bottom left corner.
bottomRightThe bottom right corner.
centerThe center point, both horizontally and vertically.
leftThe center point along the left edge.
rightThe center point along the right edge.
topThe center point along the top edge.
topLeftThe top left corner.
topRightThe top right corner.

TwicPlaceholder enum

Defines placeholder characteristics.

ValueDescription
previewdisplays a blurry preview of requested asset.
maincolorfills container with a solid color containing the most important color in the requested asset.
meancolorfills container with a solid color containing the mean color in the requested asset.
nonedisplays an empty container.

Feedback and support

TwicPics Flutter Widgets are open-source on GitHub. For features requests and bugs, open an issue. The TwicPics team also remains available for support via the live chat (at the bottom right.)

responsive images

The All-In-One Toolbox For Your Medias

The simplest, most powerful way to tackle responsive images & videos