preview 0.0.6

  • Readme
  • Changelog
  • Example
  • Installing
  • new60


Create samples of you widgets and preview them in real time

Getting Started #

Install #

Run the preview #

  • Open a dart file in vscode and the preview button will appear

  • Click the button to launch Flutter Preview

Adding a preview #

A vscode snippet is availabe for creating a preview, just type preview and it will appear.

  • Create a new class that extends PreviewProvider
  
  class MyPreview extends PreviewProvider {
  
    List<Preview> get previews {
      return [
        
      ];
    }
  }
  • Add as many Preview widgets as samples you want to display
    List<Preview> get previews {
      return [
        Preview(
          frame: Frames.ipadPro12,
          child: MyApp(),
        ),
        Preview(
          frame: Frames.iphoneX,
          child: MyApp(),
        ),
      ];
    }
  

And and the examples will appear in the preview window as soon as you save your file.

They will appear there every time you come back to that file.

Taking the most of Flutter Preview #

Preview Widget #

The Preview widget allows you to give default values that will impact your widget inside. The current availabe values are:

  • theme: Add your app theme to see your widget with your styles.
  • height, width: Set the size you want to set to the widget in case the widget has not size specified.
  • frame: See widget in different device scenarios: an android phone? or maybe an apple watch? More than 20 models and you can create your own (This is done thanks to the amazing package device_frame built by Alo├»s Deniel
  • Need more? We are working to add more in a close future: Locale, Brightness, constraints...

Also you can set a update mode for each preview from hot-reload to hot-restart;

PreviewProvider #

You can use multiple classes that extend PreviewProvider and they will be displayed in different tabs.

By default the name of the tab will be the class name but you can override the title param to customize it.

Custom Providers #

PreviewProvider allows you to group different Previews in a single file. While this can be enough for most, you might want to create your own previews. For that you can extend any widget that extends StatelessWidget and make it implement the mixin Previewer;

class MyCustomPreview extends StatelessWidget with Previewer {
 @override
 Widget build(BuildContext context) {
    return Container();
  }
}

It is important to add with Previewer always when extending any class, otherwise it won't be recognized by Flutter Preview.

A already built-in custom provider is ResizablePreviewProvider that gives you the freedom to resize a widget to see how it could look in different scenarios.

class Resizable extends ResizablePreviewProvider with Previewer {
  @override
  Preview get preview {
    return Preview(
      mode: UpdateMode.hotReload,
      child: MusicCard(
        title: 'Blond',
        singer: 'Frank Ocean',
        image: PreviewImage.asset('preview_assets/cover1.jpg'),
        onTap: () => {},
      ),
    );
  }
}

You can build any other previews or use any packages if you respect this two important rules

  • All preview providers except the default one needs to have with Previewer
  • They need to have an empty constructor without any params.

Let's see a cool example using the device_preview package

class DevicePreviewProvider extends StatelessWidget with Previewer {
  @override
  String get title => 'Device Preview';

  @override
  Widget build(BuildContext context) {
    return DevicePreview(
      builder: (context) => MyApp(),
    );
  }
}

Something is not working as expected? #

Create a new issue and I will take it a look

0.0.1 #

  • TODO: Describe initial release.

example/lib/main.dart

import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:preview/preview.dart';
import 'package:random_color/random_color.dart';
import 'package:preview_example/widgets/chip.dart' as c;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Test',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
        // This makes the visual density adapt to the platform that you run
        // the app on. For desktop platforms, the controls will be smaller and
        // closer together (more dense) than on mobile platforms.
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page 5'),
      builder: previewAppBuilder,
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  
  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  List<Color> colors = List.generate(40,
      (index) => RandomColor().randomMaterialColor(colorHue: ColorHue.blue));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Preview ${Frame().runtimeType}'),
      ),
      body: Center(
        child: Scrollbar(
          child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.all(20),
                  child: Wrap(
                      crossAxisAlignment: WrapCrossAlignment.center,
                      runAlignment: WrapAlignment.spaceBetween,
                      alignment: WrapAlignment.spaceBetween,
                      spacing: 10,
                      runSpacing: 10,
                      children: colors
                          .asMap()
                          .entries
                          .map((e) =>
                              c.Chip(title: 'Tag ${e.key}', color: e.value))
                          .toList()),
                ),
                Text(
                  'You have pushed the button this many times:',
                ),
                Text(
                  '$_counter',
                  style: Theme.of(context).textTheme.headline4,
                ),
              ],
            ),
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'aIncrement',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

class IPhoneX extends PreviewProvider {
  @override
  String get title => 'iPhone X';
  @override
  List<Preview> get previews => [
        Preview(
          key: Key('preview'),
          frame: Frames.iphoneX,
          child: MyApp(),
        ),
      ];
}

class IPad extends PreviewProvider {
  @override
  String get title => 'iPad  Pro';
  @override
  List<Preview> get previews => [
        Preview(
          frame: Frames.ipadPro12,
          child: MyApp(),
        ),
      ];
}

class AllPreview extends PreviewProvider {
  @override
  String get title => 'All';

  @override
  List<Preview> get previews => Frames.values
      .map(
        (e) => Preview(
          key: Key('preview'),
          frame: e,
          child: MyApp(),
        ),
      )
      .toList();
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  preview: ^0.0.6

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:preview/preview.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
37
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
59
Overall:
Weighted score of the above. [more]
60
Learn more about scoring.

We analyzed this package on Jul 11, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.8.4
  • pana: 0.13.15
  • Flutter: 1.17.5

Analysis suggestions

Package not compatible with SDK dart

Because:

  • preview that is a package requiring null.

Health suggestions

Fix lib/src/frame/frame_painter.dart. (-0.50 points)

Analysis of lib/src/frame/frame_painter.dart reported 1 hint:

line 1 col 8: Don't import implementation files from another package.

Format lib/preview.dart.

Run flutter format to format lib/preview.dart.

Format lib/src/frame/frame.dart.

Run flutter format to format lib/src/frame/frame.dart.

Fix additional 3 files with analysis or formatting issues.

Additional issues in the following files:

  • lib/src/preview_page.dart (Run flutter format to format lib/src/preview_page.dart.)
  • lib/src/resizable.dart (Run flutter format to format lib/src/resizable.dart.)
  • lib/src/utils.dart (Run flutter format to format lib/src/utils.dart.)

Maintenance issues and suggestions

Make sure dartdoc successfully runs on your package's source files. (-10 points)

Running dartdoc failed with the following output: NoSuchMethodError: The getter 'attributes' was called on null. Receiver: null Tried calling: attributes

#0      DartdocCustomizer._addPubPackageLink (package:pub_dev/dartdoc/customization.dart:168:17)
#1      DartdocCustomizer.customizeHtml (package:pub_dev/dartdoc/customization.dart:61:7)
#2      DartdocCustomizer.customizeFile (package:pub_dev/dartdoc/customization.dart:35:31)
<asynchronous suspension>
#3      DartdocCustomizer.customizeDir (package:pub_dev/dartdoc/customization.dart:26:25)
<asynchronous suspension>
#4      DartdocJobProcessor.process (package:pub_dev/dartdoc/dartdoc_runner.dart:211:14)
<asynchronous suspension>
#5      JobProcessor.run (package:pub_dev/job/job.dart:69:28)
<asynchronous suspension>
#6      JobMaintenance.run (package:pub_dev/job/job.dart:119:18)
#7      _workerMain.<anonymous closure> (package:pub_dev/service/entrypoint/dartdoc.dart:111:26)
#8      StackZoneSpecification._registerUnaryCallback.<anonymous closure>.<anonymous closure> (package:stack_trace/src/stack_zone_specification.dart:129:26)
#9      StackZoneSpecification._run (package:stack_trace/src/stack_zone_specification.dart:209:15)
#10     StackZoneSpecification._registerUnaryCallback.<anonymous closure> (package:stack_trace/src/stack_zone_specification.dart:129:14)
#11     _rootRunUnary (dart:async/zone.dart:1192:38)
#12     _CustomZone.runUnary (dart:async/zone.dart:1085:19)
#13     _FutureListener.handleValue (dart:async/future_impl.dart:141:18)
#14     Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:682:45)
#15     Future._propagateToListeners (dart:async/future_impl.dart:711:32)
#16     Future._completeWithValue (dart:async/future_impl.dart:526:5)
#17     _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:36:15)
#18     _completeOnAsyncReturn (dart:async-patch/async_patch.dart:298:13)
#19     DartdocJobProcessor.generateDocsForSdk (package:pub_dev/dartdoc/dartdoc_runner.dart)
#20     StackZoneSpecification._registerUnaryCallback.<anonymous closure>.<anonymous closure> (package:stack_trace/src/stack_zone_specification.dart:129:26)
#21     StackZoneSpecification._run (package:stack_trace/src/stack_zone_specification.dart:209:15)
#22     StackZoneSpecification._registerUnaryCallback.<anonymous closure> (package:stack_trace/src/stack_zone_specification.dart:129:14)
#23     _rootRunUnary (dart:async/zone.dart:1192:38)
#24     _CustomZone.runUnary (dart:async/zone.dart:1085:19)
#25     _FutureListener.handleValue (dart:async/future_impl.dart:141:18)
#26     Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:682:45)
#27     Future._propagateToListeners (dart:async/future_impl.dart:711:32)
#28     Future._completeWithValue (dart:async/future_impl.dart:526:5)
#29     Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:556:7)
#30     StackZoneSpecification._run (package:stack_trace/src/stack_zone_specification.dart:209:15)
#31     StackZoneSpecification._registerCallback.<anonymous closure> (package:stack_trace/src/stack_zone_specification.dart:119:48)
#32     _rootRun (dart:async/zone.dart:1184:13)
#33     _CustomZone.run (dart:async/zone.dart:1077:19)
#34     _CustomZone.runGuarded (dart:async/zone.dart:979:7)
#35     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1019:23)
#36     _microtaskLoop (dart:async/schedule_microtask.dart:43:21)
#37     _startMicrotaskLoop (dart:async/schedule_microtask.dart:52:5)
#38     _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:118:13)
#39     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:169:5)

Homepage URL isn't helpful. (-10 points)

Update the homepage field from pubspec.yaml: link to a website about the package or use the source repository URL.

Repository URL doesn't exist. (-10 points)

At the time of the analysis the repository field https://github.com/jamesblasco/flutter_preview/ was unreachable.

Package is pre-v0.1 release. (-10 points)

While nothing is inherently wrong with versions of 0.0.*, it might mean that the author is still experimenting with the general direction of the API.

The package description is too short. (-1 points)

Add more detail to the description field of pubspec.yaml. Use 60 to 180 characters to describe the package, what it does, and its target use case.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.7.0 <3.0.0
analyzer >=0.35.0 <0.40.0 0.39.12
args >=1.4.0 <2.0.0 1.6.0
async ^2.3.0 2.4.2
dart_style ^1.3.4 1.3.6
device_frame ^0.1.0 0.1.2
flutter 0.0.0
http >=0.12.0+2 <0.13.0 0.12.1
path >=0.9.0 <2.0.0 1.7.0
vm_service >=3.0.0 <5.0.0 4.1.0
Transitive dependencies
_fe_analyzer_shared 5.0.0
charcode 1.1.3
collection 1.14.12 1.14.13
convert 2.1.1
crypto 2.1.5
csslib 0.16.1
freezed_annotation 0.7.1 0.11.0
glob 1.2.0
html 0.14.0+3
http_parser 3.1.4
js 0.6.2
json_annotation 3.0.1
meta 1.1.8 1.2.2
node_interop 1.1.1
node_io 1.1.1
package_config 1.9.3
pedantic 1.9.0 1.9.2
pub_semver 1.4.4
sky_engine 0.0.99
source_span 1.7.0
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6 1.2.0
vector_math 2.0.8 2.1.0-nullsafety
watcher 0.9.7+15
yaml 2.2.1
Dev dependencies
flutter_test