Jessen Jie
Jessen Jie

Reputation: 377

initialize Future<QuerySnapshot> in the setState Flutter

i have a function called handleSearch, inside i make querysnapshot from user document from firestore and i want to input it into setState.

this is my code


final usersRef = FirebaseFirestore.instance.collection('users');

late Future<QuerySnapshot> searchResultsFuture; // this is the line of error

handleSearch(String query) {
    Future<QuerySnapshot> users =
        usersRef.where("name", isGreaterThanOrEqualTo: query).get();
    setState(() {
      searchResultsFuture = users;
    });
  }

this is the textFormField

AppBar(
      backgroundColor: Colors.white,
      title: TextFormField(
        controller: searchController,
        decoration: InputDecoration(
          hintText: "Search for user...",
          filled: true,
          prefixIcon: Icon(
            Icons.account_box,
            size: 28.0,
          ),
          suffixIcon: IconButton(
            icon: Icon(Icons.clear),
            onPressed: clearSearch,
          ),
        ),
        onFieldSubmitted: handleSearch,
      ),
    );

The error suggest me to add late modifier

got this error

but after i add it

if i add late modifier

any suggestion what should i do?

Upvotes: 0

Views: 108

Answers (1)

Sujan Gainju
Sujan Gainju

Reputation: 4769

When you use late keyword, it is expected to be initialized in the initState({}) method.

or

You can set the value to nullable type

Future<QuerySnapshot>? searchResultsFuture;

Upvotes: 2

Related Questions