首页 > 解决方案 > 如何在 Dart 中获得车辆的速度

问题描述

我在 Dart 有一个小项目,我正在使用该库location。使用该库,我尝试使用 GPS 位置计算车辆的速度。问题是每次运行项目时我都会在控制台中遇到错误:

The following NoSuchMethodError was thrown building ListenLocationWidget(dirty, state: _ListenLocationState#55ce8):
The getter 'speed' was called on null.
Receiver: null
Tried calling: speed

这是我的小项目的链接: https ://github.com/flo/VehicleSpeed

这是我计算位置之间速度的代码:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:location/location.dart';

class ListenLocationWidget extends StatefulWidget {
  const ListenLocationWidget({Key key}) : super(key: key);

  @override
  _ListenLocationState createState() => _ListenLocationState();
}

class _ListenLocationState extends State<ListenLocationWidget> {
  final Location location = Location();

  LocationData _location;
  StreamSubscription<LocationData> _locationSubscription;
  String _error;

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

  Future<void> _listenLocation() async {
    _locationSubscription =
        location.onLocationChanged.handleError((dynamic err) {
      setState(() {
        _error = err.code;
      });
      _locationSubscription.cancel();
    }).listen((LocationData currentLocation) {
      setState(() {
        _error = null;
        _location = currentLocation;
      });
    });
  }

  Future<void> _stopListen() async {
    _locationSubscription.cancel();
  }

  Widget _calculateSpeedBetweenLocations() {
    return Text(
      '${_location.speed != null && _location.speed * 3600 / 1000 > 0 ? (_location.speed * 3600 / 1000).toStringAsFixed(2) : 0} KM/h',
      style: TextStyle(
        color: Colors.lightGreen[500],
        fontSize: 20,
        letterSpacing: 4,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        _calculateSpeedBetweenLocations(),
      ],
    );
  }
}

这是我的主屏幕:

import 'package:vehicle_speed_demo/location/permissionStatus.dart';
import 'package:vehicle_speed_demo/location/serviceEnabled.dart';
import 'package:vehicle_speed_demo/location/getLocation.dart';
import 'package:vehicle_speed_demo/location/listenLocation.dart';
import 'package:flutter/material.dart';

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  void initState() {
    super.initState();
  }

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

  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Colors.grey[900],
        appBar: _appBar(),
        body: _buildUI(),
      ),
    );
  }

  Widget _appBar() {
    return AppBar(
      backgroundColor: Colors.purple[800],
      elevation: 0.0,
      title: Text(
        'My App',
        style: TextStyle(
          color: Colors.white,
          fontSize: 30.0,
        ),
      ),
      automaticallyImplyLeading: false,
    );
  }

  Widget _buildUI() {
    return Container(
        child: Padding(
      padding: const EdgeInsets.all(10),
      child: Column(
        children: <Widget>[
          Wrap(
            spacing: 30.0, // gap between sections
            runSpacing: 30.0, // gap between lines
            alignment: WrapAlignment.spaceAround,
            children: <Widget>[
              Divider(color: Colors.white, height: 20),
              _buildSpeedSection(),
            ],
          ),
        ],
      ),
    ));
  }

  Widget _buildSpeedSection() {
    return Container(
      height: 150,
      width: 170,
      child: Column(
        children: <Widget>[
          Text(
            'SPEED',
            style: TextStyle(
              color: Colors.white,
              fontSize: 30,
            ),
          ),
          PermissionStatusWidget(),
          ServiceEnabledWidget(),
          GetLocationWidget(),
          ListenLocationWidget(),
        ],
      ),
    );
  }
}

任何帮助将不胜感激 !

标签: flutterdart

解决方案


也许,_location.speed 导致了问题,因为最初,_location 为空。未来需要一些时间来执行,因此总结一下,您正在尝试访问 _location 的 speed 属性,该属性一开始为空。

试试这个:

Widget _calculateSpeedBetweenLocations() {

// Check if location is null
if(_location == null) return Text("Hold on!");

return Text(
  '${_location.speed != null && _location.speed * 3600 / 1000 > 0 ? (_location.speed * 3600 / 1000).toStringAsFixed(2) : 0} KM/h',
  style: TextStyle(
    color: Colors.lightGreen[500],
    fontSize: 20,
    letterSpacing: 4,
  ),
);

推荐阅读