我正在尝试构建附近的应用程序,但我几乎完成了该应用程序,但是此错误开始出现。该应用有时可能运行良好,但有时会出现编译时错误,而有时会出现运行时错误。而且我也在Google上搜索了此问题,但似乎没有任何解决方案 编辑:我发现了问题。每当我更改Slider的值时,该值就会以秒为单位改变,并且API在那一秒内不返回任何内容,因此返回的结果为零。现在我需要知道如何解决此问题。
有些Github问题与同一个问题有关,而且我也尝试了flutter clean命令,但这似乎也无法解决问题。
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:clima/services/location.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var lat;
var lng;
var _sliderValue = 1500.0;
LatLng latlng = LatLng(
-33.8670522,
151.1957362,
);
Iterable markers = [];
@override
void initState() {
super.initState();
getData(_sliderValue);
}
getData(double radius) async {
Location location = Location();
await location.getCurrentLocation();
lat = location.latitude;
lng = location.longitude;
try {
http.Response response = await http.get(
'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${latlng.latitude},${latlng.longitude}&radius=${radius.toInt()}&type=restaurant&key=API_KEY_HERE');
final int statusCode = response.statusCode;
if (statusCode == 201 || statusCode == 200) {
Map responseBody = json.decode(response.body);
List results = responseBody["results"];
Iterable _markers = Iterable.generate(20, (index) {
Map result = results[index];
Map location = result["geometry"]["location"];
LatLng latLngMarker = LatLng(location["lat"], location["lng"]);
String name = result["name"];
return Marker(
markerId: MarkerId("marker$index"),
position: latLngMarker,
infoWindow: InfoWindow(title: name));
});
setState(() {
markers = _markers;
});
} else {
throw Exception('Error');
}
} catch (e) {
print(e.toString());
}
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
children: <Widget>[
Container(
height: 100.0,
width: MediaQuery.of(context).size.width,
child: Slider(
value: _sliderValue,
min: 1000.0,
max: 2000.0,
divisions: 10,
label: '${_sliderValue.round()}',
onChanged: (double value) {
_sliderValue = value;
try {
setState(() {
getData(_sliderValue);
});
} catch (e) {
print(e.toString());
}
},
),
),
Expanded(
child: GoogleMap(
markers: Set.from(
markers,
),
initialCameraPosition: CameraPosition(target: latlng, zoom: 15.0),
onMapCreated: (GoogleMapController controller) {},
),
),
],
),
);
}
}
这是错误的日志。
Performing hot restart...
Syncing files to device Android SDK built for x86...
Restarted application in 3,346ms.
I/Google Maps Android API(17370): Google Play services package version: 16089022
I/ppbrewery.clim(17370): NativeAlloc concurrent copying GC freed 3574(288KB) AllocSpace objects, 0(0B) LOS objects, 42% free, 8MB/14MB, paused 1.619ms total 344.118ms
W/System (17370): A resource failed to call release.
I/Choreographer(17370): Skipped 34 frames! The application may be doing too much work on its main thread.
D/ (17370): HostConnection::get() New Host Connection established 0xbac40a80, tid 17764
D/EGL_emulation(17370): eglMakeCurrent: 0xee97e560: ver 2 0 (tinfo 0xee9318d0)
D/EGL_emulation(17370): eglCreateContext: 0xbfc3f820: maj 1 min 0 rcv 1
D/EGL_emulation(17370): eglMakeCurrent: 0xbfc3f820: ver 1 0 (tinfo 0xc8b39ce0)
I/flutter (17370): Lat: 37.4219983, Long: -122.084
I/ppbrewery.clim(17370): NativeAlloc concurrent copying GC freed 61451(2MB) AllocSpace objects, 16(372KB) LOS objects, 41% free, 8MB/14MB, paused 4.277ms total 249.993ms
I/flutter (17370): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (17370): The following RangeError was thrown building MyHomePage(dirty, dependencies: [MediaQuery], state:
I/flutter (17370): _MyHomePageState#dfce2):
I/flutter (17370): RangeError (index): Invalid value: Valid value range is empty: 0
I/flutter (17370):
I/flutter (17370): When the exception was thrown, this was the stack:
I/flutter (17370): #0 List.[] (dart:core-patch/growable_array.dart:145:60)
I/flutter (17370): #1 _MyHomePageState.getData.<anonymous closure> (package:clima/main.dart:79:31)
I/flutter (17370): #2 _GeneratorIterable.elementAt (dart:core/iterable.dart:689:12)
I/flutter (17370): #3 ListIterator.moveNext (dart:_internal/iterable.dart:343:26)
I/flutter (17370): #4 new LinkedHashSet.from (dart:collection/linked_hash_set.dart:100:27)
I/flutter (17370): #5 _MyHomePageState.build (package:clima/main.dart:136:28)
I/flutter (17370): #6 StatefulElement.build (package:flutter/src/widgets/framework.dart:3825:27)
I/flutter (17370): #7 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3739:15)
I/flutter (17370): #8 Element.rebuild (package:flutter/src/widgets/framework.dart:3565:5)
I/flutter (17370): #9 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2278:33)
I/flutter (17370): #10 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:700:20)
I/flutter (17370): #11 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:286:5)
I/flutter (17370): #12 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1012:15)
I/flutter (17370): #13 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:952:9)
I/flutter (17370): #14 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:864:5)
I/flutter (17370): #18 _invoke (dart:ui/hooks.dart:219:10)
I/flutter (17370): #19 _drawFrame (dart:ui/hooks.dart:178:3)
I/flutter (17370): (elided 3 frames from package dart:async)
I/flutter (17370): ════════════════════════════════════════════════════════════════════════════════════════════════════
E/BufferQueueProducer(17370): [SurfaceTexture-0-17370-9] cancelBuffer: BufferQueue has been abandoned
E/Surface (17370): queueBuffer: error queuing buffer to SurfaceTexture, -19
E/EGL_emulation(17370): tid 17412: swapBuffers(552): error 0x300d (EGL_BAD_SURFACE)
W/OpenGLRenderer(17370): swapBuffers encountered EGL error 12301 on 0xee97f2e0, halting rendering...
D/EGL_emulation(17370): eglMakeCurrent: 0xee97e560: ver 2 0 (tinfo 0xee9318d0)
答案 0 :(得分:0)
我将Iterable markers = [];
更改为var markers = <Marker>[];
(即请注意,它是List
)
然后更改处理方式:
var _markers = results.take(20).map<Marker>((result) {
Map location = result['geometry']['location'];
LatLng latLngMarker = LatLng(location['lat'], location['lng']);
String name = result['name'];
return Marker(
markerId: MarkerId('marker$index'),
position: latLngMarker,
infoWindow: InfoWindow(title: name));
}).toList();
这允许结果列表的长度小于20。它将前20个结果(如果有更少,则更少)映射到Marker
,然后将它们形成一个列表。