Caramel
Caramel

Reputation: 121

Flutter Screen Auto Pop off when the data is empty but not null

So Im trying to make a Screen which it will close when the return from api is empty

here's the code i've been trying to

FutureBuilder(
              future: GetOrga(),
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                if(snapshot.data == null){
                  return Container(
                      child: Center(
                          child: CircularProgressIndicator(
                            color: Colors.red,
                          )
                      )
                  );
                }
                return ListView.builder(
                  itemCount: snapshot.data == null ? 0 : snapshot.data.length,
                  itemBuilder: (BuildContext context, int index) {
                    if (snapshot.data == ""){
                      Navigator.pop(context);
                    }
                    return GestureDetector()

but it doesn't seem to work, It load and when the loading finished it just show empty screen.

here's the Flutter Output

flutter: []

Upvotes: 0

Views: 135

Answers (1)

mddg
mddg

Reputation: 705

I would recommend you used the method hasData of the AsyncSnapshot class which corresponds to your snapshot:

if (!snapshot.hasData) {
  Navigator.pop(context)
}

I would also recommend you checked the snapshot.connectionState prop before accessing the data, as there may be an error or it may still be waiting for the response.

Update

Now that you've posted your API response, the condition snapshot.data == '' will never be true as it returns a list. You should use snapshot.data == [] or cast it to a list and use the isEmpty operator.

Upvotes: 1

Related Questions