Search code examples
flutterlistviewconditional-statementsflutter-layoutbuilder

ListView Builder using If Condition return statement needed for blank space


The ListView looks the way I was hoping but I haven't found an option for the else statement that will let me end it there. Right now I can put a Text widget there but it continues to generate these infinite times when the user scrolls vertically. I'd like to be able to stop the ListView after the singleChildScrollView.

Have tried empty Container, SizedBox.shrink. and SizedBox with height and width of 0.0.

 child: ListView.builder(itemBuilder: (context, index) {
            if (index == 0) {
              return Container(
                margin: EdgeInsets.all(20.0),
                alignment: Alignment.center,
                child: Image.file(photos[0].name),
              );
            }
            else if (index == 1) {
              var singleChildScrollView = SingleChildScrollView(
                child: Row(
                  children: pics,
                ),
                scrollDirection: Axis.horizontal,
              );
              return singleChildScrollView;
            }
            else {
              return Text('empty space');
            }
          }),

Solution

  • try adding to the listview an itemCount, for example:

    child: ListView.builder(
                itemCount: 3, 
                itemBuilder: (context, index) {
                if (index == 0) {
                  return Container(
                    margin: EdgeInsets.all(20.0),
                    alignment: Alignment.center,
                    child: Image.file(photos[0].name),
                  );
                }
                else if (index == 1) {
                  var singleChildScrollView = SingleChildScrollView(
                    child: Row(
                      children: pics,
                    ),
                    scrollDirection: Axis.horizontal,
                  );
                  return singleChildScrollView;
                }
                else {
                  return Text('empty space');
                }
              }),