import 'package:flutter/material.dart';

class ListModel<T> {
  final GlobalKey<AnimatedListState> listKey;
  final List<T> _items;

  ListModel({
    @required this.listKey,
    List<T> initialItems,
  })  : assert(listKey != null),
        _items = initialItems ?? <T>[];

  AnimatedListState get _animateList => listKey.currentState;

  int get length => _items.length;
  T operator [](int index) => _items[index];
  int indexOf(T item) => _items.indexOf(item);

  void insert(int index, T item) {
    _items.insert(index, item);
    _animateList.insertItem(index);
  }

  void remove(T item) {
    int index = _items.indexOf(item);
    _items.remove(item);
    _animateList.removeItem(index,
        (BuildContext context, Animation<double> animation) {
      return Container();
    });
  }

  void add(T item) {
    int curLen = _items.length;

     _items.insert(curLen, item);
    _animateList.insertItem(curLen, duration: Duration(milliseconds: 100));

    var scrollCtrl = _animateList.widget.controller;
    Future.delayed(Duration(milliseconds: 300), () {
      scrollCtrl.animateTo(scrollCtrl.position.maxScrollExtent,
          curve: Curves.ease, duration: Duration(milliseconds: 300));
    });
  }
}
