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

Flutter技术问题:如何在不同Dart类之间传递变量

通过方法在Dart文件间传递int、bool值

我来给你演示具体怎么实现——其实核心就是在目标类里定义一个接收参数的方法,然后在调用方创建类实例并调用这个方法传值就行,非常直观。

第一步:在目标文件中定义接收类

比如我们新建一个data_handler.dart文件,里面写一个用来接收和存储值的类:

class DataHandler {
  // 类内部的成员变量,用来保存传递过来的值
  int? storedInt;
  bool? storedBool;

  // 专门用来接收参数的方法
  void setValues(int inputInt, bool inputBool) {
    storedInt = inputInt;
    storedBool = inputBool;
    
    // 可选:这里可以加一些参数接收后的逻辑,比如打印确认
    print("成功接收int值: $storedInt");
    print("成功接收bool值: $storedBool");
  }
}

第二步:在调用文件中传值

假设我们在main.dart里要把值传过去,只需要导入目标文件,创建类实例,然后调用方法就行:

import 'data_handler.dart';

void main() {
  // 1. 创建DataHandler类的实例
  final handler = DataHandler();

  // 2. 定义要传递的int和bool变量
  final myNumber = 100;
  final isActive = false;

  // 3. 调用方法把值传进去
  handler.setValues(myNumber, isActive);

  // 验证一下:直接访问类里的变量确认值是否传递成功
  print("验证存储的int值: ${handler.storedInt}");
  print("验证存储的bool值: ${handler.storedBool}");
}

额外拓展:如果需要更灵活的传值

如果有时候只需要更新其中一个类型的值,也可以拆分方法,比如单独写updateInt(int value)和updateBool(bool value),这样调用起来更灵活:

// 在DataHandler类里新增方法
void updateInt(int value) {
  storedInt = value;
}

void updateBool(bool value) {
  storedBool = value;
}

这样在调用方就可以单独更新某一个值:

handler.updateInt(200);
handler.updateBool(true);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:56:22