首页 > 解决方案 > 如何通过 Flutter 中的 Inherited Widget 获取当前位置并在树内传递?

问题描述

我正在尝试在其他路线的应用程序中共享用户的当前位置。

我的小部件树非常广泛,可以继续向下传递值,所以我想在下面的小部件中让它更容易并在 1 分钟的间隔内更新。

我已经尝试过 Provider 和 Inherited 小部件,但我的值为 null 并且出现错误:

The following NoSuchMethodError was thrown building:
The getter 'currentPosition' was called on null.
Receiver: null
Tried calling: currentPosition

我的第一堂课

class _HomeScreenState extends State<HomeScreen> {
  Placemark _currentPlaceMark;
  Position _currentPosition =
      Position(longitude: -23.708422, latitude: -46.5568553);

  initState() {
    super.initState();
    //Get the current location of user
    _determinePosition();
  }

  @override
  Widget build(BuildContext context) {
    return CurrentPositionInherited(
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: mainTitleApp,
        theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: Scaffold(
            drawer: CustomDrawer(),
            appBar: AppBar(
              title: Text(mainTitleApp),
            ),
            body: BodyCategoriesList()),
      ),
      currentPosition: _currentPosition,
    );
  }

我在 Init 调用以确定当前位置的方法

void _determinePosition() async {
    
    var pos = await Geolocator.getCurrentPosition();
    setState(() {
      _currentPosition = pos;
    });

    placemarkFromCoordinates(pos.latitude, pos.longitude)
        .then((value) => setState(() {
              _currentPlaceMark = value.first;
            }));

}

我继承的小部件

class CurrentPositionInherited extends InheritedWidget {
  const CurrentPositionInherited({
    Key key,
    @required this.currentPosition,
    @required Widget child,
  })  : assert(child != null),
        super(key: key, child: child);

  final Position currentPosition;

  static CurrentPositionInherited of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType()
        as CurrentPositionInherited;
  }

  @override
  bool updateShouldNotify(CurrentPositionInherited old) =>
      currentPosition != old.currentPosition;
}

在 BodyCategoriesList() 内部它有 2 层小部件导致其他路由(因为我调用 MaterialPageRoute 来构建其他页面)然后我尝试使用这种方法调用 location 属性:

  Widget _buildSubtitle(RatingModel rating, BuildContext context) {
    print(CurrentPositionInherited.of(context)
        .currentPosition
        .latitude
        .toString());       
  }

我只想分享我在这个深度小部件中更新的当前位置,但我无法做到这一点,我正在尝试几个小时!

标签: flutterdartflutter-providerinherited-widget

解决方案


推荐阅读