首页 > 解决方案 > Flutter 应用程序错误“NoSuchMethodError:在 null 上调用了 getter 'length'”

问题描述

收到此错误并且找不到原因,该应用程序显示从谷歌地图位置 API 调用医院的谷歌地图,在 chrome 中使用时 API 调用返回正常,但应用程序无法构建显示“NoSuchMethodError:getter 'length ' 在 null 上调用”错误。谢谢你的帮助。


class Search extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final currentPosition = Provider.of<Position>(context);
    final placesProvider = Provider.of<Future<List<Place>>>(context);

    return FutureProvider(
      create: (context) => placesProvider,
      child: Scaffold(
        body: (currentPosition != null)
            ? Consumer<List<Place>>(
                builder: (_, places, __) {
                  return Column(
                    children: <Widget>[
                      Container(
                        height: MediaQuery.of(context).size.height / 3,
                        width: MediaQuery.of(context).size.width,
                        child: GoogleMap(
                          initialCameraPosition: CameraPosition(
                              target: LatLng(currentPosition.latitude,
                                  currentPosition.longitude),
                              zoom: 16.0),
                          zoomGesturesEnabled: true,
                          mapToolbarEnabled: true,
                          myLocationEnabled: true,
                          scrollGesturesEnabled: true,
                        ),
                      ),
                      SizedBox(
                        height: 10.0,
                      ),
                      Expanded(
                        child: ListView.builder(
                            itemCount: places.length,
                            itemBuilder: (context, index) {
                              return Card(
                                child: ListTile(
                                  title: Text(places[index]?.name),
                                ),
                              );
                            }),
                      )
                    ],
                  );
                },
              )
            : Center(
                child: CircularProgressIndicator(),
              ),
      ),
    );
  }
}

在 chrome 中调用 api 请求时工作正常,问题是在构建应用程序时。这是我的 places_service.dart 文件:


class PlacesService {
  final key = 'xxxxxxxxxxxxxxxxxxxxx-ttttttttttttttttt';

  Future<List<Place>> getPlaces(double lat, double lng) async {
    var response = await http.get('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$lng&type=hospital&rankby=distance&key=$key');
    var json = convert.jsonDecode(response.body);
    var jsonResults = json['results'] as List;
    return jsonResults.map((place) => Place.fromJson(place)).toList();
  }

}

问题是这一行:

itemCount: places.length,

标签: apigoogle-mapsflutterdart

解决方案


推荐阅读