car_provider.dart 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import 'dart:collection';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter_provider_demo/dao/car_dao.dart';
  4. import 'package:flutter_provider_demo/model/car_model.dart';
  5. /// Description: car provider
  6. /// Time : 09/04/2023 Monday
  7. /// Author : liuyuqi.gov@msn.cn
  8. class CarProvider extends ChangeNotifier {
  9. late List<CarModel> _cars;
  10. int _count = 0;
  11. int get count => _count;
  12. UnmodifiableListView<CarModel> get allCars => UnmodifiableListView(_cars);
  13. UnmodifiableListView<CarModel> get unStartedCars =>
  14. UnmodifiableListView(_cars.where((car) => car.start == false));
  15. UnmodifiableListView<CarModel> get startedCars =>
  16. UnmodifiableListView(_cars.where((car) => car.start == true));
  17. Future<List<CarModel>> getCars() async {
  18. _cars = await CarDao.getCars();
  19. notifyListeners();
  20. return _cars;
  21. }
  22. void deleteCar(BuildContext context, CarModel car) async {
  23. await CarDao.deleteCar(car);
  24. _cars.remove(car);
  25. notifyListeners();
  26. }
  27. /// add car
  28. void addCar(CarModel car) async {
  29. final id = await CarDao.addCar(car);
  30. if (id > 0) {
  31. _cars.add(car);
  32. notifyListeners();
  33. }
  34. }
  35. void _showSnackBar(BuildContext context, String message) {
  36. final snackBar = SnackBar(
  37. duration: const Duration(milliseconds: 500),
  38. content: Text(
  39. message,
  40. style: const TextStyle(color: Colors.white),
  41. ),
  42. backgroundColor: Theme.of(context).primaryColor,
  43. );
  44. ScaffoldMessenger.of(context).showSnackBar(snackBar);
  45. }
  46. void startCar(BuildContext context, CarModel car) {
  47. notifyListeners();
  48. }
  49. }