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

Flutter中为类变量赋值时出现Setter错误的问题排查

问题分析与解决方案

错误原因

你代码里的fetchcategory是静态方法,而_categorylist是类的实例变量(属于每个SqfliteProvider实例)。静态方法属于类本身,不需要创建实例就能调用,所以它无法访问仅属于实例的成员变量,这就是赋值时提示需要setter的本质原因。

解决方案

有两种常见的修复方式,根据你的业务需求选择:

方案1:将方法改为实例方法

如果每个SqfliteProvider实例需要维护自己的分类列表,去掉fetchcategory的static关键字,改成实例方法:

class SqfliteProvider {
  List<CategoryModel> _categorylist = [];

  List<CategoryModel> get categories {
    return _categorylist;
  }

  // 去掉static关键字
  Future<List<CategoryModel>?> fetchcategory() async {
    final db = await _getdb();

    List<CategoryModel> templist = [];
    List<Map<String, dynamic>> maplist = await db.query('categorytb');

    if (maplist.isEmpty) return null;

    templist = maplist.map((e) => CategoryModel.frommap(e)).toList();

    // 现在可以正常赋值了
    _categorylist = templist;
    return templist;
  }
}

调用时需要先创建SqfliteProvider实例:

final provider = SqfliteProvider();
await provider.fetchcategory();

方案2:将变量改为静态变量

如果希望全局共享一份分类列表,把_categorylist改成静态变量:

class SqfliteProvider {
  // 改成静态变量
  static List<CategoryModel> _categorylist = [];

  static List<CategoryModel> get categories {
    return _categorylist;
  }

  static Future<List<CategoryModel>?> fetchcategory() async {
    final db = await _getdb();

    List<CategoryModel> templist = [];
    List<Map<String, dynamic>> maplist = await db.query('categorytb');

    if (maplist.isEmpty) return null;

    templist = maplist.map((e) => CategoryModel.frommap(e)).toList();

    // 静态方法可以访问静态变量
    _categorylist = templist;
    return templist;
  }
}

这种方式调用时不需要创建实例,直接通过类调用:

await SqfliteProvider.fetchcategory();

内容的提问来源于stack exchange,提问作者Irfan Ganatra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:11:16