如何更新变量并在不同的有状态小部件中使用它们?

问题描述 投票:0回答:2

我要做的是,当我点击列表图块时,它会在地图上的位置(基于纬度和经度)生成新标记。

但变量不更新,只显示初始值为0.如果我删除0并开始热重载,它们打印为null。

class UpdatedStoresListState extends State<UpdatedStoresList> {

  double updatedLat = 0;
  double updatedLon = 0;

  @override
  void initState() {
    super.initState();
  }

当我点击ListTile小部件时,它会生成新的纬度和经度。

class UpdatedStoresListState extends State<UpdatedStoresList> {
...

children: <Widget>[
  GestureDetector(
    onTap: () {
      setState(() {
        updatedLat = snapshot.data[index].latitude;
        updatedLon = snapshot.data[index].longitude;
        print('Lat: $updatedLat');
        // 52.902...
        print('Lon: $updatedLon');
        // -129.9031...
      });
    },
    child: ListTile(

我需要为'Marker'小部件使用新值。它位于另一个不同的.dart文件中的statefulwidget中。

class _MainMapState extends State<MainMap> {
...

Marker(
  width: 40.0,
  height: 40.0,
  point: LatLng(UpdatedStoresListState().updatedLat, UpdatedStoresListState().updatedLon),
  builder: (ctx) => Container(
    child: FlutterLogo(),
  ),
)

我非常感谢您提供的任何帮助

dart flutter
2个回答
0
投票

如果您有兴趣使用BLoC,请按照以下步骤操作:创建文件lat_long_bloc.dart并在该文件中创建一个BLoC。

class LatLongBloc {
   StreamController _latLongStreamController = StreamController<LatLong>();

   Stream get latLongStream => _latLongStreamController.stream;

   dispose(){
     _latLongStreamController.close();
   }

   updateLatLong(LatLng latLong){
     _latLongStreamController.sink.add(latLong);
   }
}

final latLongBloc = LatLongBloc();

在您的GestureDetecture中,将您的代码更改为:

GestureDetector(
    onTap: () {
      updatedLat = snapshot.data[index].latitude;
      updatedLon = snapshot.data[index].longitude;
      latLongBloc.updateLatLong(LatLng(updatedLat , updatedLon ));
    },
    child: ListTile(

用StreamBuilder包装你的Marker:

StreamBuilder(
        stream: latLongBloc.latLongStream,
        builder: (context, snapshot) {
          LatLng latLog = snapshot.data;
          return Marker(
            width: 40.0,
            height: 40.0,
            point: LatLng(latLog.lat, latLog.long),
            builder: (ctx) => Container(
              child: FlutterLogo(),
            ),
          );
        },
      )

就是这样,每当你调用BLoC的updateLatLong()时,你的Marker Widget都会被更新。


0
投票

point: LatLng(UpdatedStoresListState().updatedLat, UpdatedStoresListState().updatedLon) 这是完全错误的,我建议你开始使用redux或bloc,因为你正在管理一个大的共享应用程序状态。

© www.soinside.com 2019 - 2024. All rights reserved.