Home > Net >  The return type 'Object' isn't a 'Future<Iterable<Suggestion>>'
The return type 'Object' isn't a 'Future<Iterable<Suggestion>>'

Time:11-07

I'm using the new dart version <2.18.1> with null safety enabled. And I'm using the android studio to code this.

This is maps_screen.dart

`

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_typeahead/flutter_typeahead.dart';
import 'package:geolocator/geolocator.dart';
import 'package:gmapsdemo/places_api.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class MapsScreen extends StatefulWidget {
  MapsScreen({Key? key}) : super(key : key);

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

class _MapsScreenState extends State<MapsScreen> {

  final Completer<GoogleMapController> _controller = Completer();

  static const LatLng _initialPosition = LatLng(6.8747747, 79.8645194);

  final Set<Marker> _markers = {};

  late LatLng user_current_position;

  MapType currentMapType = MapType.normal;

  TextEditingController _addressController = TextEditingController();

  void _onMapCreate(GoogleMapController controller)
  {
    _controller.complete(controller);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Map Screen'),
      ),
      body: Stack(
        children: [
          Container(
            child: GoogleMap(
              onMapCreated: _onMapCreate,
              initialCameraPosition:
              CameraPosition(target: _initialPosition, zoom: 9),
              markers: _markers,
              onTap: (latLng){

                _onAddMaker(latLng);
              },
              mapType: currentMapType,
              ),
            ),
          Positioned(
            child: Container(
              margin: EdgeInsets.only(top: 10, left: 10, right: 10),
              height: 50,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.2),
                    spreadRadius: 3,
                    blurRadius: 2,)
                ]),

              child: TypeAheadField<Suggestion>(
                textFieldConfiguration: TextFieldConfiguration(
                    controller: _addressController,
                    decoration: InputDecoration(
                      alignLabelWithHint: true,
                      hintText: 'Type Address',
                      border: InputBorder.none,
                      hintStyle: TextStyle(fontSize: 20),
                      isCollapsed: true),
                ),
                hideOnEmpty: true,
                hideOnLoading: true,
                suggestionsCallback: (pattern) async {
                  return //await PlacesAPIProvider('23456')
                      .fetchSuggestions(pattern);//
                },
                itemBuilder: (context, suggestion) {
                  return GestureDetector(
                    onTap: (){},
                    child: ListTile(
                      title: Text(suggestion.description,
                      style: TextStyle(color: Colors.black)),
                    ),
                  );
                },
                onSuggestionSelected: (selectedSuggestion) {},
              ),
            ),
          ),
          Positioned(
            bottom: 8,
            left: 8,
            child: FloatingActionButton(
              child: Icon(
                Icons.my_location,
                color: Colors.white,
              ),
              onPressed: () async{

                await getUserCurrentPosition().then((value) async{
                  await _navigateCameraToPosition(value);
                });

              },
            )),
          Positioned(
              bottom: 8,
              left: 80,
              child: FloatingActionButton(
                child: Icon(
                  Icons.map,
                  color: Colors.white,
                ),
                onPressed: (){
                  setState(() {

                    currentMapType = (currentMapType == MapType) ?
                    MapType.satellite : MapType.normal;
                  });
                },
              ))
        ],
      ),
    );
  }

  void _onAddMaker(LatLng position)
  {
    setState(() {

      _markers.add(
          Marker(
              icon: BitmapDescriptor.defaultMarker,
              markerId: MarkerId(position.longitude.toString()),
              position: position,
              infoWindow: InfoWindow(
                  title: "Maker",
                  snippet: position.toString())
          )
      );
    });
  }

  Future<LatLng> getUserCurrentPosition() async
  {

    var position = await  Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.best
    );

    setState(() {
      user_current_position = LatLng(position.latitude, position.longitude);
    });

    return user_current_position;
  }

  Future _navigateCameraToPosition(LatLng position) async
  {
    final controller = await _controller.future;
    
    await controller.animateCamera(CameraUpdate.newCameraPosition(
      CameraPosition(target: position , zoom: 12)
    ));

  }
}

`

This is places_api.dart

import 'dart:convert';

import 'package:http/http.dart' as http;

class PlacesAPIProvider{

  final sessionToken;

  PlacesAPIProvider(this.sessionToken);

  final apiKey = 'AIzaSyCSmS579erjjuZFo3WB8vSL_d5T6nGzFA0';

  Future<Object> fetchSuggestions(String query)
  async {
    if( query.isNotEmpty){

      final request = 'https://maps.googleapis.com/maps/api/place/autocomplete/json'
          'input=$query&types=address&language=en&components=cpuntry:sl'
          '&key=$apiKey&sessointoken=$sessionToken';

      final response = await http.get(Uri.parse(request));

      if(response.statusCode == 200)
      {
        final result = json.decode(response.body);

        if (result['status'] == 'ok')
          {
            return result['predications']
                .map<Suggestion>(
                    (p) => Suggestion( p['place_id'], p['description']))
                .toList();
          }else{

          return [];
        }
      }
      else{
        return [];
      }
    }
    else{
      return [];
    }
    return '';
  }
}

class Suggestion{

  final String placeId;
  final String description;

  Suggestion( this.placeId , this.description);
}

I'm getting this error

The return type 'Object' isn't a 'Future<Iterable<Suggestion>>', as required by the closure's context.

This is where the error is. i put // where the red underline is.

hideOnEmpty: true,
                hideOnLoading: true,
                suggestionsCallback: (pattern) async {
                  return //await PlacesAPIProvider('23456')
                      .fetchSuggestions(pattern);//
                },

and this error in the Run log:

lib/maps_screen.dart:84:26: Error: A value of type 'Object' can't be returned from an async function with return type 'Future<Iterable<Suggestion>>'.
 - 'Object' is from 'dart:core'.
 - 'Future' is from 'dart:async'.
 - 'Iterable' is from 'dart:core'.
 - 'Suggestion' is from 'package:gmapsdemo/places_api.dart' ('lib/places_api.dart').
                  return await PlacesAPIProvider('23456')
                         ^


FAILURE: Build failed with an exception.

* Where:
Script 'C:\Users\induw\Documents\flutter\Flutter\flutter_windows_3.3.2-stable\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1159

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\Users\induw\Documents\flutter\Flutter\flutter_windows_3.3.2-stable\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1m 42s
Exception: Gradle task assembleDebug failed with exit code 1

Please help me I'm a beginner.

I tried google but I couldn't find a similar error.

CodePudding user response:

The return type of fetchSuggestions is List<Suggestion> and not Object. So, change this line.

/// replace Object with Future<Iterable<Suggestion>>
Future<Iterable<Suggestion>> fetchSuggestions(String query) async{}

More optimal way:

    Future<List<Suggestion>> fetchSuggestions(String query) async{}
  • Related