i'm trying to get the placename using the geocoding api but it doesn't work it says placename is null

426 views Asked by At

i created seperated files for the geolocator called helping methods and address class for placename and address attributes and included them in the search page this is the given error

======== Exception caught by widgets library ======================================================= The getter 'placename' was called on null. Receiver: null Tried calling: placename

this is the search page file


    import 'package:flutter/material.dart';
    import 'package:provider/provider.dart';
    import 'package:reviver_app/dataproviders/appdata.dart';
    import 'package:reviver_app/globalvariables.dart';
    import 'package:reviver_app/helpers/requesthelper.dart';
    class SearchPage extends StatefulWidget {
      @override
      _SearchPageState createState() => _SearchPageState();
    }
    
    
    
    
    class _SearchPageState extends State<SearchPage> {
      var pickupController = TextEditingController();
      var destinationController = TextEditingController();
      var focusDestination = FocusNode();
      bool focused = false;
      void setFocus() {
        if (!focused) {
          FocusScope.of(context).requestFocus(focusDestination);
          focused = true;
        }
      }
      void searchPlace(String placeName) async {
        if (placeName.length >1){
          String url = 'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=$placeName+Amphitheatre&key=$mapKey&sessiontoken=123456789';
          var response = await RequestHelper.getRequest(url);
          if (response == 'failed'){
            return;
          }
          print(response);
    
        }
    
      }
    
    
      @override
      Widget build(BuildContext context) {
        setFocus();
       String address = Provider.of<AppData>(context).pickupaddress.placename ?? ""; this is the error which is null
       pickupController.text = address;
    
        return Scaffold(
          body: Column(
            children: <Widget>[
              Container(
                height: 210,
                decoration: BoxDecoration(
                  color: Colors.white,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.redAccent,
                      blurRadius: 5.0,
                      spreadRadius: 0.5,
                      offset: Offset(
                        0.7,
                        0.7,
                      ),
                    ),
                  ]
                ),
                child:  Padding(
                  padding:  EdgeInsets.only(left: 24, top: 48, right:24, bottom: 20 ),
                  child: Column(
                    children: <Widget> [
                      SizedBox(height: 5),
                      Stack(
                        children: <Widget>[
                          GestureDetector(
                            onTap: (){
                              Navigator.pop(context);
                                      },
                              child: Icon(
                                Icons.arrow_back, color: Colors.redAccent,)
                          ),
                          Center(
                            child: Text('Set Booking', style:
                            TextStyle(fontSize: 20, fontFamily: 'Brand-Bold'),
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: 18,),
                      Row(
                        children: <Widget> [
                          Image.asset('images/pickicon.png', height:16, width: 16 ,),
    
                          SizedBox(width: 18,),
                          Expanded(
                            child: Container(
                              decoration: BoxDecoration(
                                color: Colors.redAccent,
                                borderRadius: BorderRadius.circular(4),
                              ),
                              child: Padding(
                                padding:  EdgeInsets.all(2.0),
                                child: TextField(
                                 controller: pickupController,
    
                                  decoration: InputDecoration(
                                    hintText: 'Your Location',
                                    fillColor: Colors.redAccent,
                                    filled: true,
                                    border: InputBorder.none,
                                    isDense: true,
                                    contentPadding: EdgeInsets.only(left: 10, top: 0, bottom: 0)
                                  ),
    
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: 10,),
    
                      Row(
                        children: <Widget> [
                          Image.asset('images/desticon.png', height:16, width: 16 ,),
    
                          SizedBox(width: 18,),
                          Expanded(
                            child: Container(
                              decoration: BoxDecoration(
                                color: Colors.redAccent,
                                borderRadius: BorderRadius.circular(4),
                              ),
                              child: Padding(
                                padding:  EdgeInsets.all(2.0),
                                child: TextField(
                                  //destination which will be removed
                                  onChanged: (value){
                                    searchPlace(value);
                                  },
                                 focusNode: focusDestination ,
                                  controller: destinationController,
    
                                  decoration: InputDecoration(
                                      hintText: 'this will be removed ',
                                      fillColor: Colors.redAccent,
                                      filled: true,
                                      border: InputBorder.none,
                                      isDense: true,
                                      contentPadding: EdgeInsets.only(left: 10, top: 0, bottom: 0)
                                  ),
    
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
    
    
                    ],
                  ),
                ),
              )
    
            ],
          ),
        );
      }
    }
    ```
this is where I included the geolocotor URL


import 'package:connectivity/connectivity.dart';
import 'package:geolocator/geolocator.dart';
import 'package:reviver_app/datamodels/address.dart';
import 'package:reviver_app/dataproviders/appdata.dart';
import 'package:reviver_app/globalvariables.dart';
import 'package:reviver_app/helpers/requesthelper.dart';
import 'package:provider/provider.dart';


class HelperMethods {
  static Future<String> findCordinateAddress(Position position, context) async {
    String placeaddress = '';
    var connectivityResult = await Connectivity().checkConnectivity();
    if (connectivityResult != ConnectivityResult.mobile &&
        connectivityResult != ConnectivityResult.wifi) {
      return placeaddress;
    }
    String url =
        'https://maps.googleapis.com/maps/api/geocode/json?latlng=${position.latitude},${position.longitude}&key=$mapKey';


    var response = await RequestHelper.getRequest(url);
    if (response == 'failed') {
      placeaddress = response['results'][0]['formatted_address'];

      Address pickupaddress = new Address();
      pickupaddress.longitude = position.longitude;
      pickupaddress.latitude = position.latitude;
      pickupaddress.placename = placeaddress;

      Provider.of<AppData>(context, listen: false)
          .updatePickupAddress(pickupaddress);
    }
    return placeaddress;
  }
}
```

this is the app data file


    
    import 'package:flutter/cupertino.dart';
    import 'package:reviver_app/datamodels/address.dart';
    
    class AppData extends ChangeNotifier{
      Address pickupaddress;
       void updatePickupAddress(Address pickup){
         pickupaddress = pickup;
         notifyListeners();
       }
    
    
    
    }

this is the address class from where I added place name

  
    class Address {
      String placename;
      double latitude;
      double longitude;
      String placeId;
      String placeformattedaddress;
    
      Address({
        this.placeId,
        this.latitude,
        this.placename,
        this.longitude,
        this.placeformattedaddress,
    
    });
    }

1

There are 1 answers

1
Rinku Moni Khanikar On

In your searchpage, update the url String of the searchPlace() method.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:reviver_app/dataproviders/appdata.dart';
import 'package:reviver_app/globalvariables.dart';
import 'package:reviver_app/helpers/requesthelper.dart';

class SearchPage extends StatefulWidget {
  @override
  _SearchPageState createState() => _SearchPageState();
}


class _SearchPageState extends State<SearchPage> {
  var pickupController = TextEditingController();
  var destinationController = TextEditingController();
  var focusDestination = FocusNode();
  bool focused = false;
  void setFocus() {
    if (!focused) {
      FocusScope.of(context).requestFocus(focusDestination);
      focused = true;
    }
  }
  void searchPlace(String placeName) async {
    if (placeName.length >1){
      String url = 'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=$placeName&key=$mapKey&sessiontoken=123456789';
      var response = await RequestHelper.getRequest(url);
      if (response == 'failed'){
        return;
      }
      print(response);

    }

  }


  @override
  Widget build(BuildContext context) {
    setFocus();
   String address = Provider.of<AppData>(context).pickupaddress.placename ?? ""; this is the error which is null
   pickupController.text = address;

    return Scaffold(
      body: Column(
        children: <Widget>[
          Container(
            height: 210,
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.redAccent,
                  blurRadius: 5.0,
                  spreadRadius: 0.5,
                  offset: Offset(
                    0.7,
                    0.7,
                  ),
                ),
              ]
            ),
            child:  Padding(
              padding:  EdgeInsets.only(left: 24, top: 48, right:24, bottom: 20 ),
              child: Column(
                children: <Widget> [
                  SizedBox(height: 5),
                  Stack(
                    children: <Widget>[
                      GestureDetector(
                        onTap: (){
                          Navigator.pop(context);
                                  },
                          child: Icon(
                            Icons.arrow_back, color: Colors.redAccent,)
                      ),
                      Center(
                        child: Text('Set Booking', style:
                        TextStyle(fontSize: 20, fontFamily: 'Brand-Bold'),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 18,),
                  Row(
                    children: <Widget> [
                      Image.asset('images/pickicon.png', height:16, width: 16 ,),

                      SizedBox(width: 18,),
                      Expanded(
                        child: Container(
                          decoration: BoxDecoration(
                            color: Colors.redAccent,
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: Padding(
                            padding:  EdgeInsets.all(2.0),
                            child: TextField(
                             controller: pickupController,

                              decoration: InputDecoration(
                                hintText: 'Your Location',
                                fillColor: Colors.redAccent,
                                filled: true,
                                border: InputBorder.none,
                                isDense: true,
                                contentPadding: EdgeInsets.only(left: 10, top: 0, bottom: 0)
                              ),

                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 10,),

                  Row(
                    children: <Widget> [
                      Image.asset('images/desticon.png', height:16, width: 16 ,),

                      SizedBox(width: 18,),
                      Expanded(
                        child: Container(
                          decoration: BoxDecoration(
                            color: Colors.redAccent,
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: Padding(
                            padding:  EdgeInsets.all(2.0),
                            child: TextField(
                              onChanged: (value){
                                searchPlace(value);
                              },
                             focusNode: focusDestination ,
                              controller: destinationController,

                              decoration: InputDecoration(
                                  hintText: 'this will be removed ',
                                  fillColor: Colors.redAccent,
                                  filled: true,
                                  border: InputBorder.none,
                                  isDense: true,
                                  contentPadding: EdgeInsets.only(left: 10, top: 0, bottom: 0)
                              ),

                            ),
                          ),
                        ),
                      ),
                    ],
                  ),


                ],
              ),
            ),
          )

        ],
      ),
    );
  }
}

You have used a placeholder for the placeName, hence you don't have to add the +Amphitheatre as it is considered as a raw string.