0

I tried to used google map autocomplete, but I got the this error LateInitializationError: Field 'searchResults' has not been initialized.

How can solve it problem?

I still tried to used this way, but still falue.

void initState() {
searchResults;
}

This is my code

late List<PlaceSearch> searchResults;
  final placeService = PlaceSerive();

  searchPlaces(String searchTerm) async {
    searchResults = await placeService.getAutoComplete(searchTerm);
  }
...
...
void initState() {
searchResults;
}
...
...
...

 child: ListView.builder(
                            itemCount: searchResults.length,
                            itemBuilder: (context, index) {
                              return ListTile(
                                title: Text(searchResults[index].description,
                                    style: TextStyle(color: Colors.black)),
                              );
                            },
                          ),
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
Stanley
  • 311
  • 5
  • 15
  • Does this answer your question? [LateInitializationError: Field 'data' has not been initialized, got error](https://stackoverflow.com/questions/67401385/lateinitializationerror-field-data-has-not-been-initialized-got-error) – MendelG Jul 03 '22 at 14:57
  • @MendelG it's not can solve, I had tried it before. – Stanley Jul 03 '22 at 15:01
  • Did you mean to call searchPlaces() inside initState()? searchResults; doesn't do anything. You can also initialize it with an empty list [] and remove the late keyword. – Colin Jul 03 '22 at 15:14

2 Answers2

0

While searchResults will get data from future it is better to use FutureBuilder for statelesswidget or nullabe data.

On state class

  List<PlaceSearch>? searchResults;

  @override
  void initState() {
    super.initState();
    searchPlaces("yourSearchTerm")
  }

 searchPlaces(String searchTerm) async {
    searchResults = await placeService.getAutoComplete(searchTerm);
    setState((){});
  }

Now you can check whether list is null or not.

child: searchResults==null? Text("loading") :ListView.builder(...)
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
0

You are not calling the searchPlaces function in the init function so it can't initialize the searchResults variable. To solve it do this:

@override
initState(){
  super.initState();
  searchPlaces();  
}

and remember to set state in searchPlaces function.

Just a Person
  • 1,276
  • 1
  • 5
  • 23