Giter VIP home page Giter VIP logo

firestore_model's Introduction

Provides an abstract class for creating observable Firestore models. This model is best extended with Mobx.

Also includes widgets for building these models by their Firestore reference and Firestore collection subscribable list builders.

Usage

To use this plugin, add firestore_model as a dependency to your pubspec.yaml file.

Note: The package is based on the new Firebase refactor.

Examples

All of these code sippets are taken from the Flutter Firestore example app.

Observable model
@JsonSerializable()
class User extends _User with _$User {
  static final collection = FirebaseFirestore.instance.collection('users');

  static User fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
}

abstract class _User extends FirestorePhotoModel<User> with Store {
  @o @JsonKey() String name;
  @o @JsonKey() String description;
  @o @JsonKey(defaultValue: 0) int views = 0;
  @o @JsonKey(defaultValue: 0) int followers = 0;

  @override @a
  void onSnapshot(User x) {
    super.onSnapshot(x);
    name = x.name;
    description = x.description;
    views = x.views;
    followers = x.followers;
  }
}
Reference builder
FirebaseModelBuilder.firestore<Album>(
  bucket: 'overview_preview_$i',
  reference: widget.references[i],
  subscribe: true,
  builder: (_, album) => AnimatedSize(
    vsync: this,
    duration: kFastMotionDuration,
    curve: Curves.fastOutSlowIn,
    child: FancySwitcher(
      child: album == null
          ? const AspectRatio(
              aspectRatio: 1,
              child: Align(
                alignment: Alignment.center,
                child: CircularProgressIndicator(),
              ),
            )
          : AlbumTile(
              key: ValueKey(album.id),
              album: album,
              flip: i.isOdd,
              dense: false,
            ),
    ),
  ),
);
Subscribable collection
class _AlbumList extends StatelessWidget {
  const _AlbumList({Key key, @required this.user}) : super(key: key);

  final User user;

  Widget _buildSubscribedList(FirestoreCollectionBuilderState<Album, dynamic> collection) => SliverList(
        delegate: SliverChildBuilderDelegate(
          (_, i) {
            final index = collection.subscribedItems.length - (i + 1);
            final item = collection.subscribedItems[index];
            return Padding(
              key: ValueKey(item.id),
              padding: index > 0 ? const EdgeInsets.only(bottom: 24) : EdgeInsets.zero,
              // Subscribe to new items to allow the tile to animate when its photos are processed
              child: FirestoreReferenceBuilder<Album>(
                reference: item.reference,
                bucket: item.reference.path,
                subscribe: true,
                builder: (_, album) => AlbumTile(album: item, flip: index.isOdd, dense: true),
              ),
            );
          },
          childCount: collection.subscribedItems.length,
          addAutomaticKeepAlives: false,
        ),
      );

  Widget _buildPaginatedList(FirestoreCollectionBuilderState<Album, dynamic> collection) => SliverList(
        delegate: SliverChildBuilderDelegate(
          (_, i) {
            final item = collection.paginatedItems[i];
            return Padding(
              key: ValueKey(item.id),
              padding: i < collection.paginatedItems.length ? const EdgeInsets.only(bottom: 24) : EdgeInsets.zero,
              child: Paginator(
                paginator: collection.getPaginator(i),
                child: FadingTile(
                  key: ValueKey(item.id),
                  staggerFrom: collection.pageTime,
                  hitsPerPage: collection.itemsPerPage,
                  staggerIndex: i % collection.itemsPerPage,
                  child: AlbumTile(album: item, flip: i.isOdd, dense: true),
                ),
              ),
            );
          },
          childCount: collection.paginatedItems.length,
          addAutomaticKeepAlives: false,
        ),
      );

  @override
  Widget build(BuildContext context) {
    return FirestoreCollectionBuilder<Album, dynamic>(
      bucket: 'photo_list_${user.reference.path}',
      collection: Album.collection.where('owner', isEqualTo: user.id),
      subscribe: true,
      builder: (_, collection) => CustomScrollView(
        slivers: [
          const SliverSafeArea(
            minimum: EdgeInsets.only(top: 24),
            top: false,
            sliver: SliverPadding(padding: EdgeInsets.zero),
          ),
          if (collection.subscribedItems.isNotEmpty) _buildSubscribedList(collection),
          if (collection.subscribedItems.isNotEmpty)
            const SliverToBoxAdapter(
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 24),
                child: ListDivider(text: Text('NEW โ†‘')),
              ),
            ),
          if (collection.paginatedItems.isNotEmpty) _buildPaginatedList(collection),
          const SliverSafeArea(minimum: EdgeInsets.only(bottom: 24), sliver: SliverPadding(padding: EdgeInsets.zero)),
        ],
      ),
    );
  }
}
Firestore toggle
FirestoreToggle(
  toggle: user.reference.collection('followers'),
  id: AuthStore.instance.user?.uid,
  enabled: AuthStore.instance.authenticated && AuthStore.instance.user?.uid != user.id && user.exists == true,
  countToggle: true,
  builder: (context, ready, toggled, handler) => FancySwitcher(
    child: toggled
        ? IconButton(
            tooltip: 'Unfollow ${Format.userName(user)}',
            key: const ValueKey(true),
            onPressed: ready ? handler : null,
            alignment: Alignment.center,
            padding: EdgeInsets.zero,
            icon: Container(
              alignment: Alignment.center,
              padding: const EdgeInsets.all(8),
              child: const Icon(MdiIcons.accountRemoveOutline),
              decoration: ShapeDecoration(
                color: theme.colorScheme.secondary,
                shape: const CircleBorder(),
              ),
            ),
          )
        : IconButton(
            alignment: Alignment.center,
            tooltip: 'Follow ${Format.userName(user)}',
            key: const ValueKey(false),
            onPressed: ready ? handler : null,
            icon: const Icon(MdiIcons.accountPlus),
          ),
    ),
);

firestore_model's People

Contributors

volskaya avatar

Stargazers

 avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.