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

Flutter中如何在另一个类中使用Location类的变量值?

解决Flutter中跨类获取Location实例变量为Null的问题

问题原因

你每次调用Location()都会创建一个全新的Location实例,这个新实例的latitude和longitude根本没经过构造函数初始化,所以值是null。而你之前能正常打印的是已经完成初始化的旧实例的变量,和新创建的这个完全是两个独立对象。

解决方案

  • 传递已初始化的实例
    这是最简单直接的方式,把已经初始化好的Location对象传给第二个类,不要每次都新建:

    // 第二个类的定义
    class SecondClass {
      final Location location;
      // 通过构造函数接收已初始化的Location实例
      SecondClass(this.location);
    
      void fetchLocation() {
        var myLat = location.latitude;
        var myLong = location.longitude;
        // 这里就能拿到有效值了
      }
    }
    
    // 使用时传入已初始化的实例
    var myLocation = Location(latitude: 31.23, longitude: 121.45);
    var secondClass = SecondClass(myLocation);
    
  • 用单例模式复用同一个实例
    如果你的整个应用只需要一个Location实例,把Location改成单例,确保每次获取的都是同一个对象:

    class Location {
      double? latitude;
      double? longitude;
      // 私有单例实例
      static final Location _instance = Location._internal();
      // 工厂构造函数,返回单例
      factory Location({double? latitude, double? longitude}) {
        // 如果初始化时传入值,更新单例的属性
        if (latitude != null) _instance.latitude = latitude;
        if (longitude != null) _instance.longitude = longitude;
        return _instance;
      }
      // 私有构造函数,防止外部新建实例
      Location._internal();
    }
    
    // 初始化一次
    Location(latitude: 31.23, longitude: 121.45);
    // 第二个类里直接获取,拿到的是同一个实例的属性
    var myLat = Location().latitude;
    
  • 状态管理(适合多页面/组件共享数据)
    如果是在多个Widget之间共享位置数据,用状态管理工具(比如Provider、Riverpod、GetX)把Location实例放到全局状态中,需要的地方直接取:
    以Riverpod为例:

    // 定义全局的Location Provider
    final locationProvider = StateProvider<Location>((ref) => 
      Location(latitude: 31.23, longitude: 121.45)
    );
    
    // 在第二个Widget中获取
    class SecondPage extends ConsumerWidget {
      @override
      Widget build(BuildContext context, WidgetRef ref) {
        var location = ref.watch(locationProvider);
        return Text("纬度:${location.latitude},经度:${location.longitude}");
      }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 23:50:33