NoSuchMethodError - 颤振

时间:2021-06-25 01:28:29

标签: ios flutter dart nosuchmethoderror nosuchmethod

当我为某个页面运行应用程序时,出现错误:

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY
╞═══════════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building Builder:
The method '-' was called on null.
Receiver: null
Tried calling: -(null)

The relevant error-causing widget was:
  MaterialApp
  file:///Users/daiquery/folder/Workspace/runsmith/runsmith/lib/main.dart:28:14

When the exception was thrown, this was the stack:
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1      _MapState.calculateDistance (package:runsmith/pages/map.dart:51:17)
#2      _MapState.initState (package:runsmith/pages/map.dart:34:33)
#3      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4711:57)
#4      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4548:5)
...     Normal element mounting (24 frames)
#28     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3611:14)
#29     MultiChildRenderObjectElement.inflateWidget
(package:flutter/src/widgets/framework.dart:6221:36)
#30     MultiChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:6232:32)
...     Normal element mounting (170 frames)
#200    Element.inflateWidget (package:flutter/src/widgets/framework.dart:3611:14)
#201    MultiChildRenderObjectElement.inflateWidget
(package:flutter/src/widgets/framework.dart:6221:36)
#202    Element.updateChild (package:flutter/src/widgets/framework.dart:3363:18)
#203    RenderObjectElement.updateChildren
(package:flutter/src/widgets/framework.dart:5654:32)
#204    MultiChildRenderObjectElement.update
(package:flutter/src/widgets/framework.dart:6243:17)
#205    Element.updateChild (package:flutter/src/widgets/framework.dart:3350:15)
#206    ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:4599:16)
#207    StatefulElement.performRebuild
(package:flutter/src/widgets/framework.dart:4746:11)
#208    Element.rebuild (package:flutter/src/widgets/framework.dart:4267:5)
#209    StatefulElement.update (package:flutter/src/widgets/framework.dart:4778:5)
#210    Element.updateChild (package:flutter/src/widgets/framework.dart:3350:15)
#211    ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:4599:16)
#212    Element.rebuild (package:flutter/src/widgets/framework.dart:4267:5)
#213    ProxyElement.update (package:flutter/src/widgets/framework.dart:4922:5)
#214    Element.updateChild (package:flutter/src/widgets/framework.dart:3350:15)
#215    ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:4599:16)
#216    Element.rebuild (package:flutter/src/widgets/framework.dart:4267:5)
#217    ProxyElement.update (package:flutter/src/widgets/framework.dart:4922:5)
#218    _InheritedNotifierElement.update
(package:flutter/src/widgets/inherited_notifier.dart:181:11)
#219    Element.updateChild (package:flutter/src/widgets/framework.dart:3350:15)
#220    SingleChildRenderObjectElement.update
(package:flutter/src/widgets/framework.dart:6090:14)
#221    Element.updateChild (package:flutter/src/widgets/framework.dart:3350:15)
#222    ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:4599:16)
#223    StatefulElement.performRebuild
(package:flutter/src/widgets/framework.dart:4746:11)
#224    Element.rebuild (package:flutter/src/widgets/framework.dart:4267:5)
#225    StatefulElement.update (package:flutter/src/widgets/framework.dart:4778:5)
#226    Element.updateChild (package:flutter/src/widgets/framework.dart:3350:15)
#227    SingleChildRenderObjectElement.update
(package:flutter/src/widgets/framework.dart:6090:14)
#228    Element.updateChild (package:flutter/src/widgets/framework.dart:3350:15)
#229    SingleChildRenderObjectElement.update
(package:flutter/src/widgets/framework.dart:6090:14)
#230    Element.updateChild (package:flutter/src/widgets/framework.dart:3350:15)
#231    ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:4599:16)
#232    Element.rebuild (package:flutter/src/widgets/framework.dart:4267:5)
#233    ProxyElement.update (package:flutter/src/widgets/framework.dart:4922:5)
#234    Element.updateChild (package:flutter/src/widgets/framework.dart:3350:15)
#235    ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:4599:16)
#236    StatefulElement.performRebuild
(package:flutter/src/widgets/framework.dart:4746:11)
#237    Element.rebuild (package:flutter/src/widgets/framework.dart:4267:5)
#238    BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2582:33)
#239    WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:875:21)
#240    RendererBinding._handlePersistentFrameCallback
(package:flutter/src/rendering/binding.dart:328:5)
#241    SchedulerBinding._invokeFrameCallback
(package:flutter/src/scheduler/binding.dart:1144:15)
#242    SchedulerBinding.handleDrawFrame
(package:flutter/src/scheduler/binding.dart:1082:9)
#243    SchedulerBinding._handleDrawFrame
(package:flutter/src/scheduler/binding.dart:998:5)
#247    _invoke (dart:ui/hooks.dart:163:10)
#248    PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:259:5)
#249    _drawFrame (dart:ui/hooks.dart:126:31)
(elided 3 frames from dart:async)

我尝试导航到其他页面,并且成功了。 这是我的代码:

import 'dart:async';
import 'dart:math';
import 'dart:developer' as developer;
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:runsmith/domain/run.dart';
import 'package:runsmith/pages/runend.dart';
import 'package:runsmith/domain/screensize_reducers.dart';
import 'package:runsmith/domain/formattime.dart';
import 'package:geolocator/geolocator.dart';

class MapPage extends StatefulWidget {
  @override
  _MapState createState() => _MapState();
}

class _MapState extends State<MapPage> {
  Stopwatch _elapsedTime;
  String now;
  Run currentRun;
  double distanceTravelled = 0.00;
  double distanceBetweenLastPoints;
  double latitudeData;
  double longitudeData;
  var month = DateTime.now().month;
  var day = DateTime.now().day;
  var lastLatitude;
  var lastLongitude;
// literally random comment to test
  @override
  void initState() {
    lastLatitude = latitudeData;
    lastLongitude = longitudeData;
    distanceBetweenLastPoints = calculateDistance(
        latitudeData, longitudeData, lastLatitude, lastLongitude);

    print(distanceBetweenLastPoints);
    distanceBetweenLastPoints = Geolocator.distanceBetween(
        latitudeData, longitudeData, lastLatitude, lastLongitude);

    super.initState();

    _elapsedTime = Stopwatch();
    _elapsedTime.start();
  }

  double calculateDistance(lat1, lon1, lat2, lon2) {
    var p = 0.017453292519943295;
    var c = cos;
    var a = 0.5 -
        c((lat2 - lat1) * p) / 2 +
        c(lat1 * p) * c(lat2 * p) * (1 - c((lon2 - lon1) * p)) / 2;
    return 12742 * asin(sqrt(a));
  }

  getCurrentLocation() async {
    final geoposition = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.best);

    setState(() {
      latitudeData = geoposition.latitude;
      longitudeData = geoposition.longitude;
    });
  }

  // points every 600ms and finding the distance between them, then
  // adding this to the distanceTravelled variable as an integer
  // two variables, last location and current location

  @override
  void dispose() {
    // _timer.cancel();
    super.dispose();
  }

  void handleStartStop() {
    if (_elapsedTime.isRunning) {
      _elapsedTime.stop();
    } else {
      _elapsedTime.start();
    }

    setState(() {});
  }

  GoogleMapController mapController;
  final LatLng _center = const LatLng(45.521563, -122.677433);

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
    Geolocator.getPositionStream(desiredAccuracy: LocationAccuracy.best)
        .listen((l) {
      mapController.animateCamera(
        CameraUpdate.newCameraPosition(
          CameraPosition(target: LatLng(l.latitude, l.longitude), zoom: 15),
        ),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          body: Column(
        children: [
          Container(
            height: screenHeight(context, dividedBy: 3),
            child: GoogleMap(
              onMapCreated: _onMapCreated,
              initialCameraPosition: CameraPosition(
                target: _center,
                zoom: 11.0,
              ),
            ),
          ),
          Container(
            color: Colors.blue,
            height: screenHeight(context),
            child: Column(
              children: [
                Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                  Padding(
                      padding: EdgeInsets.all(10),
                      child: Text('text',
                          style: TextStyle(
                              fontWeight: FontWeight.bold,
                              height: 2.0,
                              fontSize: 50))),
                  Padding(
                      padding: EdgeInsets.all(10),
                      child: Text(formatTime(_elapsedTime.elapsedMilliseconds),
                          style: TextStyle(
                              fontWeight: FontWeight.bold,
                              height: 2.0,
                              fontSize: 50)))
                ]),
                Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                  RaisedButton(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(50)),
                    onPressed: handleStartStop,
                    child: Icon(!_elapsedTime.isRunning
                        ? Icons.play_arrow
                        : Icons.pause),
                  ),
                  RaisedButton(
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(50)),
                    onPressed: () {
                      if (_elapsedTime.isRunning == false) {
                        // currentRun.runId = 00001;
                        // currentRun.time =
                        //     _elapsedTime.elapsedMilliseconds.toString();
                        // currentRun.date = now;
                        // currentRun.miles = 5.00;

                        // print(currentRun);
                        Navigator.push(
                          context,
                          MaterialPageRoute(builder: (context) => RunEndPage()),
                        );
                      } else {
                        return;
                      }
                    },
                    child: Icon(Icons.stop),
                  )
                ])
              ],
            ),
          ),
        ],
      )),
    );
  }
}

我一直收到这个错误,虽然我尝试删除某些部分,添加调试器以查看哪里出了问题,查看了以前的导航器,但我还没有找到解决方案。

1 个答案:

答案 0 :(得分:1)

calculateDistance 方法中,您正在执行以下计算

var a = 0.5 -
c((lat2 - lat1) * p) / 2 +
c(lat1 * p) * c(lat2 * p) * (1 - c((lon2 - lon1) * p)) / 2;

但是 lat/lon 的值在这里是 null,因为它是从 initState

调用的

您可以在声明解决此问题的同时将 latitudeData/longitudeData 初始化为 0 值。

double latitudeData = 0;
double longitudeData = 0;