how to handle FutureBuilder when no value in database? flutter

Issue

i am trying to create a screen which uses future builder and when there is data in the database it works great but when there is no data found its shows error:

FormatException: Unexpected end of input (at character 2)

and here is my code:

 FutureBuilder(
            future: allCars(),
            builder: (context, AsyncSnapshot snapshot){
              if(!snapshot.hasError){
  
                    return Center(child: Text("No Cars"));
                }

              else {
                if (snapshot.hasError) print(snapshot.error);
                return snapshot.hasData ? ListView.builder(
                    itemCount: snapshot.data!.length,
                    itemBuilder: (context, index) {
                      List list = snapshot.data;
                      return SingleChildScrollView()
                    }

it must show : Text("No Cars")) on the screen . but it keeps reloading when there is no data found?
Thanks in advance <3 .

Solution

Use if(snapshot.hasData) to check if there is data or not.

    FutureBuilder(
                future: allCars(),
                builder: (context, AsyncSnapshot snapshot){
                  if(!snapshot.error){
      
                        return Center(child: Text("No Cars"));
                    }
    
                  else {
                    if (snapshot.hasdata) {

                    return  ListView.builder(
                        itemCount: snapshot.data!.length,
                        itemBuilder: (context, index) {
                          List list = snapshot.data;
                          return SingleChildScrollView()
                        }else{
return Text("No cars")}

Answered By – Nbn

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.