E / flutter(24673):[错误:flutter / lib / ui / ui_dart_state.cc(166)]未处理的异常:RangeError(索引):无效值:有效值范围为空:0

时间:2020-09-25 21:59:56

标签: flutter dart

早上好,我在模拟器屏幕上单击“添加地点”时收到此错误

      I/Choreographer(24673): Skipped 51 frames!  The application may be doing too much work on its main thread.
D/EGL_emulation(24673): eglMakeCurrent: 0xf30a1410: ver 3 0 (tinfo 0xf33f8610)
D/EGL_emulation(24673): eglMakeCurrent: 0xf30a1c60: ver 3 0 (tinfo 0xf33f72b0)
D/EGL_emulation(24673): eglMakeCurrent: 0xf30a1410: ver 3 0 (tinfo 0xf33f8610)
D/MediaScannerConnection(24673): Scanned /storage/emulated/0/Android/data/com.example.GPApp/files/Pictures/4e6213df-df84-4741-b6ad-aa38b67021915812601528792428377.jpg to null
D/EGL_emulation(24673): eglMakeCurrent: 0xf30a1c60: ver 3 0 (tinfo 0xf33f72b0)
I/Choreographer(24673): Skipped 119 frames!  The application may be doing too much work on its main thread.
D/EGL_emulation(24673): eglMakeCurrent: 0xf30a1410: ver 3 0 (tinfo 0xf33f8610)
I/m.example.GPAp(24673): Background young concurrent copying GC freed 2638(291KB) AllocSpace objects, 7(756KB) LOS objects, 49% free, 3269KB/6512KB, paused 3.107ms total 646.067ms
E/flutter (24673): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 0
E/flutter (24673): #0      List.[]  (dart:core-patch/growable_array.dart:166:60)
E/flutter (24673): #1      LocationHelper.getPlaceAddress 
package:GPApp/helpers/location_helper.dart:17
E/flutter (24673): <asynchronous suspension>
E/flutter (24673): #2      GreatPlaces.addPlace 
package:GPApp/providers/great_places.dart:21
E/flutter (24673): #3      _AddPlaceScreenState._savePlace 
package:GPApp/screens/add_place_screen.dart:38
E/flutter (24673): #4      _InkResponseState._handleTap 
package:flutter/…/material/ink_well.dart:992
E/flutter (24673): #5      _InkResponseState.build.<anonymous closure> 
package:flutter/…/material/ink_well.dart:1098
E/flutter (24673): #6      GestureRecognizer.invokeCallback 
package:flutter/…/gestures/recognizer.dart:184
E/flutter (24673): #7      TapGestureRecognizer.handleTapUp 
package:flutter/…/gestures/tap.dart:524
E/flutter (24673): #8      BaseTapGestureRecognizer._checkUp 
package:flutter/…/gestures/tap.dart:284
E/flutter (24673): #9      BaseTapGestureRecognizer.handlePrimaryPointer 
package:flutter/…/gestures/tap.dart:219
E/flutter (24673): #10     PrimaryPointerGestureRecognizer.handleEvent 
package:flutter/…/gestures/recognizer.dart:477
E/flutter (24673): #11     PointerRouter._dispatch 
package:flutter/…/gestures/pointer_router.dart:78
E/flutter (24673): #12     PointerRouter._dispatchEventToRoutes.<anonymous closure> 
package:flutter/…/gestures/pointer_router.dart:124
E/flutter (24673): #13     _LinkedHashMapMixin.forEach  (dart:collection-patch/compact_hash.dart:377:8)
E/flutter (24673): #14     PointerRouter._dispatchEventToRoutes 
package:flutter/…/gestures/pointer_router.dart:122
E/flutter (24673): #15     PointerRouter.route 
package:flutter/…/gestures/pointer_router.dart:108
E/flutter (24673): #16     GestureBinding.handleEvent 
package:flutter/…/gestures/binding.dart:220
E/flutter (24673): #17     GestureBinding.dispatchEvent 
package:flutter/…/gestures/binding.dart:200
E/flutter (24673): #18     GestureBinding._handlePointerEvent 
package:flutter/…/gestures/binding.dart:158
E/flutter (24673): #19     GestureBinding._flushPointerEventQueue 
package:flutter/…/gestures/binding.dart:104
E/flutter (24673): #20     GestureBinding._handlePointerDataPacket 
package:flutter/…/gestures/binding.dart:88
E/flutter (24673): #21     _rootRunUnary  (dart:async/zone.dart:1206:13)
E/flutter (24673): #22     _CustomZone.runUnary  (dart:async/zone.dart:1100:19)
E/flutter (24673): #23     _CustomZone.runUnaryGuarded  (dart:async/zone.dart:1005:7)
E/flutter (24673): #24     _invoke1  (dart:ui/hooks.dart:267:10)
E/flutter (24673): #25     _dispatchPointerDataPacket  (dart:ui/hooks.dart:176:5)
E/flutter (24673):

这是我的“ location_input”页面,我在其中获取“用户当前位置”并选择一个位置。

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

import '../helpers/location_helper.dart';
import '../screens/map_screen.dart';

class LocationInput extends StatefulWidget {
final Function onSelectPlace;
 
 LocationInput(this.onSelectPlace);

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

class _LocationInputState extends State<LocationInput> {
  String _previewImageUrl;

  Future<void> _getCurrentUserLocation() async {
    final locData = await Location().getLocation();
    final staticMapImageUrl = LocationHelper.generateLocationPreviewImage(
      latitude: locData.latitude,
      longitude: locData.longitude,
    );
    setState(() {
      _previewImageUrl = staticMapImageUrl;
    });
    widget.onSelectPlace(locData.latitude, locData.longitude);
  }

  Future<void> _selectOnMap() async {
    final selectedLocation = await Navigator.of(context).push<LatLng>(
      MaterialPageRoute(
        builder: (peter) => MapScreen(
          isSelecting: true,
        ),
      ),
    );
    if(selectedLocation == null) {
      return;
    }
    widget.onSelectPlace(selectedLocation.latitude, selectedLocation.longitude);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          alignment: Alignment.center,
          height: 200,
          width: double.infinity,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(5),
            border: Border.all(
              width: 1,
              color: Colors.grey,
            ),
          ),
          child: _previewImageUrl == null
              ? Text(
                  "No location found",
                  textAlign: TextAlign.center,
                )
              : Image.network(_previewImageUrl,
                  fit: BoxFit.cover, width: double.infinity),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            FlatButton.icon(
              label: Text(
                "Current Location",
              ),
              textColor: Theme.of(context).primaryColor,
              icon: Icon(Icons.location_on),
              onPressed: _getCurrentUserLocation,
            ),
            FlatButton.icon(
              label: Text(
                "Select on Map",
              ),
              textColor: Theme.of(context).primaryColor,
              icon: Icon(Icons.map),
              onPressed: _selectOnMap,
            ),
          ],
        ),
      ],
    );
  }
}

这是我实现Google插件的“ map_screen”。

 import 'dart:async';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

import '../models/place.dart';

class MapScreen extends StatefulWidget {
  final PlaceLocation initialLocation;
  final bool isSelecting;

  MapScreen({
    this.initialLocation = const PlaceLocation(
      latitude: 37.422,
      longitude: -122.084,
    ),
    this.isSelecting = false,
  });

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

class _MapScreenState extends State<MapScreen> {
  Completer<GoogleMapController> _controller = Completer();
  LatLng _pickedLocation;

  void _selectLocation(LatLng position) {
    setState(() {
      _pickedLocation = position;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Your Map"),
        actions: <Widget>[
          if (widget.isSelecting)
            IconButton(
              icon: Icon(Icons.check_box),
              onPressed: _pickedLocation == null
                  ? null
                  : () {
                      Navigator.of(context).pop(_pickedLocation);
                    },
            )
        ],
      ),
      body: GoogleMap(
        mapType: MapType.hybrid,
        initialCameraPosition: CameraPosition(
          target: LatLng(
            widget.initialLocation.latitude,
            widget.initialLocation.longitude,
          ),
          zoom: 16,
        ),
        onTap: widget.isSelecting ? _selectLocation : null,
        markers: _pickedLocation == null
            ? null
            : {
                Marker(
                  markerId: MarkerId('m1'),
                  position: _pickedLocation,
                ),
              },
        onMapCreated: (GoogleMapController controller) {
          _controller.complete(controller);
        },
      ),
    );
  }
}

这是我的“ add_place_screen”,实际上是我在数据库中保存所选位置的地方(SQLite 1)。

    import 'dart:io';

import 'package:GPApp/models/place.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../widget/image_input.dart';
import '../providers/great_places.dart';
import '../widget/location_input.dart';
import '../models/place.dart';

class AddPlaceScreen extends StatefulWidget {
  static const routeName = "add-Place";

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

class _AddPlaceScreenState extends State<AddPlaceScreen> {
  final _titleController = TextEditingController();
  File _pickedImage;
  PlaceLocation _pickedLocation;

  void _selectImage(pickedImage) {
    _pickedImage = pickedImage;
  }

  void _selectPlace (double lat, double lng) {
  _pickedLocation = PlaceLocation(latitude: lat, longitude: lng);
  }

  void _savePlace() {
    if (_titleController.text.isEmpty ||
     _pickedImage == null ||
     _pickedLocation == null) {
      return;
    }
    Provider.of<GreatPlaces>(context, listen: false).addPlace(
      _titleController.text,
      _pickedImage,
      _pickedLocation,
    );
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Add a New Place",
          style: TextStyle(fontSize: 18.0),
        ),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Expanded(
            child: SingleChildScrollView(
              child: Padding(
                padding: const EdgeInsets.all(10),
                child: Column(
                  children: [
                    TextField(
                      decoration: InputDecoration(labelText: "Title"),
                      controller: _titleController,
                    ),
                    SizedBox(height: 10),
                    ImageInput(_selectImage),
                    SizedBox(height: 10),
                    LocationInput(_selectPlace),
                  ],
                ),
              ),
            ),
          ),
          RaisedButton.icon(
            elevation: 0,
            color: Theme.of(context).accentColor,
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
            onPressed: _savePlace,
            icon: Icon(Icons.add),
            label: Text(
              "Add Place",
              style: TextStyle(fontSize: 18.0),
            ),
          ),
        ],
      ),
    );
  }
}

0 个答案:

没有答案