繁体   English   中英

失去与设备的连接。 退出 (sigterm) - Flutter 崩溃

[英]Lost connection to device. Exited (sigterm) - Flutter Crash

我的 Flutter 应用程序在加载时崩溃

它运行一个 FutureBuilder,我相信这就是问题所在。

我的应用发出 API 调用并将数据返回到 map 标记。

当我让 FutureBuilder 返回一个列表视图时,它工作正常。

但是,当我将其更改为返回包含我的 Map SDK 和调用 API 的按钮的堆栈时,它会在启动时崩溃。

相关代码如下,谢谢!

class HomePage extends StatefulWidget { 

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

class _HomePageState extends State<HomePage> {
  Future<Stations> stations;
  BuildContext _context;
  MapMarkerExample _mapMarkerExample; 
  


  @override
  void initState() {
   stations = API_Call().fetchStations(); 
   super.initState();
  }
  


  @override
  Widget build(BuildContext context) {
    return Scaffold(
         appBar: AppBar(
          title: Text('Example 1'),
        ),
        
      body: Container(
 
        child: FutureBuilder<Stations>(
          future: stations,
       
            builder: (context, snapshot) {
     
        if (snapshot.hasError) {
          return Text("Error");
        }
  
        if (snapshot.connectionState == ConnectionState.done) {
          return 
          
          Stack(
          children: [
            HereMap(onMapCreated: _onMapCreated),
          

            Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    button('Stations Near Me', _anchoredMapMarkersButtonClicked),
                    button('Clear', _clearButtonClicked),
                  ],
                ),
              ],
            ),
          ],
            );
        }
        
        return Text("Loading");
           
           

            }
        ) 
      )
        );
           }

api_call.dart

class API_Call {

Future<Stations> fetchStations() async {
    var client = http.Client();

      final response = await client.get(
      'https://transit.hereapi.com/v8/stations?in=x,-x&return=transport&apiKey=API_KEY');
   
    if (response.statusCode == 200) {
    return Stations.fromJson(jsonDecode(response.body)); 
  } else {
    throw Exception('Failed to load stations');
  }
    }
    }

api_manager.dart

 typedef ShowDialogFunction = void Function(String title, String message);

 class MapMarkerExample{
 
    
  void showAnchoredMapMarkers() { 
  print('step5');
  
   GeoCoordinates geoCoordinates = _callGeoCoordinates();
           // use the coords .. to add a marker
           _addCircleMapMarker(geoCoordinates, 0);
           _addPOIMapMarker(geoCoordinates, 1);
           print('step6');
  } 

    
 GeoCoordinates _callGeoCoordinates() {
   print('step7');
   var stations;

   Future<Stations> fetchStations() async {
       stations = await API_Call().fetchStations(); 
       for (Station stations in stations) {
           GeoCoordinates geoCoordinates = GeoCoordinates (stations.place.location.lat, stations.place.location.lng);
           // use the coords .. to add a marker
           _addCircleMapMarker(geoCoordinates, 0);
           _addPOIMapMarker(geoCoordinates, 1);
           } 
        }
    }


  HereMapController _hereMapController;
  List<MapMarker> _mapMarkerList = [];
  MapImage _poiMapImage;
  MapImage _circleMapImage;
  ShowDialogFunction _showDialog;
  List<MapMarker3D> _mapMarker3DList = [];
   
   MapMarkerExample(ShowDialogFunction showDialogCallback, HereMapController hereMapController) {
    _showDialog = showDialogCallback;
    _hereMapController = hereMapController;

    double distanceToEarthInMeters = 8000;
    _hereMapController.camera.lookAtPointWithDistance(
      GeoCoordinates(x, -x), distanceToEarthInMeters);

    // Setting a tap handler to pick markers from map.
    _setTapGestureHandler();

    _showDialog("Note", "Tap markers for more.");
    }




  void clearMap() {
    for (var mapMarker in _mapMarkerList) {
      _hereMapController.mapScene.removeMapMarker(mapMarker);
    }
    _mapMarkerList.clear();

    for (var mapMarker3D in _mapMarker3DList) {
      _hereMapController.mapScene.removeMapMarker3d(mapMarker3D);
    }
    _mapMarker3DList.clear();
  }

  Future<void> _addPOIMapMarker(GeoCoordinates geoCoordinates, int drawOrder) async {
    // Reuse existing MapImage for new map markers.
    if (_poiMapImage == null) {
      Uint8List imagePixelData = await _loadFileAsUint8List('assets/poi.png');
      _poiMapImage = MapImage.withPixelDataAndImageFormat(imagePixelData, ImageFormat.png);
    }

    Anchor2D anchor2D = Anchor2D.withHorizontalAndVertical(0.5, 1);

    MapMarker mapMarker = MapMarker.withAnchor(geoCoordinates, _poiMapImage, anchor2D);
    mapMarker.drawOrder = drawOrder;

    Metadata metadata = new Metadata();
    metadata.setString("key_poi", "Next Departures");
    mapMarker.metadata = metadata;

    _hereMapController.mapScene.addMapMarker(mapMarker);
    _mapMarkerList.add(mapMarker);
  }

  Future<void> _addCircleMapMarker(GeoCoordinates geoCoordinates, int drawOrder) async {
    // Reuse existing MapImage for new map markers.
    if (_circleMapImage == null) {
      Uint8List imagePixelData = await _loadFileAsUint8List('assets/circle.png');
      _circleMapImage = MapImage.withPixelDataAndImageFormat(imagePixelData, ImageFormat.png);
    }
    
    MapMarker mapMarker = MapMarker(geoCoordinates, _circleMapImage);
    mapMarker.drawOrder = drawOrder;

    _hereMapController.mapScene.addMapMarker(mapMarker);
    _mapMarkerList.add(mapMarker);
  }

  Future<Uint8List> _loadFileAsUint8List(String assetPathToFile) async {
    // The path refers to the assets directory as specified in pubspec.yaml.
    ByteData fileData = await rootBundle.load(assetPathToFile);
    return Uint8List.view(fileData.buffer);
  }

  void _setTapGestureHandler() {
    _hereMapController.gestures.tapListener = TapListener.fromLambdas(lambda_onTap: (Point2D touchPoint) {
      _pickMapMarker(touchPoint);
    });
  }

  void _pickMapMarker(Point2D touchPoint) {
    double radiusInPixel = 2;
    _hereMapController.pickMapItems(touchPoint, radiusInPixel, (pickMapItemsResult) {
      // Note that 3D map markers can't be picked yet. Only marker, polgon and polyline map items are pickable.
      List<MapMarker> mapMarkerList = pickMapItemsResult.markers;
      if (mapMarkerList.length == 0) {
        print("No map markers found.");
        return;
      }
    });
  }
    }

api_manager.dart中,这看起来很可疑,并且您没有从这个 function 中返回任何内容,它也可以解释说future not complete的错误

 Future<Stations> fetchStations() async {
   stations = await API_Call().fetchStations(); 
   
       for (Station stations in stations) {
           GeoCoordinates geoCoordinates = GeoCoordinates (stations.place.location.lat, stations.place.location.lng);
           // use the coords .. to add a marker
           _addPOIMapMarker(geoCoordinates, 1);
           }   

          // GeoCoordinates geoCoordinates = stations.coordinates;
          // _addPOIMapMarker(geoCoordinates, 1);
 
    }
 }

你必须从中返回一个Stations object,在你的 for 循环之后尝试return stations; ,它可以解决您的问题,如果错误发生变化,这也是一个好的开始。

还将您在未来构建器中的行更改为:

if (snapshot.connectionState == ConnectionState.done && snapshot.hasData) 

同时,删除这个_setTapGestureHandler() 崩溃很可能是由一些 memory 泄漏引起的,从发布的代码来看, listeners可以解释。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM