You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Dart中借助Mixin实现私有字段与抽象方法的复用?附实践示例

关于Dart Mixin的实用发现:私有字段与抽象方法的结合

最近在折腾Dart的Mixin特性时,我挖到了两个挺实用的点:Mixin不仅能包含私有字段,还可以像抽象类那样定义抽象方法。这在只需要少量抽象方法的场景下特别省心——完全不用专门建个抽象类再去继承,直接把这些抽象方法整合到Mixin里,就能轻松实现代码复用。

目前我在设计上有点纠结:到底该用传统的继承方式,还是继续用这种把抽象方法塞进Mixin的方案?下面是我实验用的代码示例:

import 'package:flutter/cupertino.dart';

mixin Favourite {
  bool _isFavourite = false;
  bool get isFavourite;
}

class ProductProvider with Favourite, ChangeNotifier implements Comparable<ProductProvider> {
  final String id;
  final String title;
  final String description;
  final String imageUrl;
  final double price;

  ProductProvider({
    required this.id,
    required this.title,
    required this.description,
    required this.imageUrl,
    required this.price,
  });

  ProductProvider.noPrice({
    required this.id,
    required this.title,
    required this.description,
    required this.imageUrl,
    bool isFavourite = false,
  }) : price = 0.0;

  toggleFavourite() {
    this._isFavourite = !this._isFavourite;
    notifyListeners();
  }

  @override
  bool get isFavourite => _isFavourite;

  factory ProductProvider.fromJSON(Map<String, dynamic> json) {
    return json['price'] != null
        ? ProductProvider(
            id: json['id'],
            title: json['title'],
            description: json['description'],
            imageUrl: json['imageUrl'],
            price: json['price'] is int ? json['price'].toDouble() : json['price'])
        : ProductProvider.noPrice(
            id: json['id'],
            title: json['title'],
            description: json['description'],
            imageUrl: json['imageUrl'],
            isFavourite: json['isFavourite'] ?? false,
          );
  }

  @override
  int compareTo(ProductProvider other) {
    return (price - other.price).toInt();
  }
}

一点小分析

  • 这里的FavouriteMixin既封装了私有状态_isFavourite,又通过抽象getterisFavourite强制混入的类实现对外的状态访问接口,兼顾了封装性和接口约束。
  • 相比于继承抽象类,用Mixin的好处是可以同时混入多个功能模块(比如这里同时混入Favourite和ChangeNotifier),不会受Dart单继承的限制,灵活性拉满。

不过目前我还在权衡:如果后续需要扩展更多相关的抽象方法,是继续在Mixin里添加,还是应该抽出一个抽象类来做继承?欢迎大家一起讨论~

内容的提问来源于stack exchange,提问作者Solen Dogan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 04:47:41