Home > Back-end >  LateInitializationError: Field 'searchResults' has not been initialized
LateInitializationError: Field 'searchResults' has not been initialized

Time:07-04

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)),
                              );
                            },
                          ),

CodePudding user response:

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(...)

CodePudding user response:

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.

  • Related