List View Builder Flutter

Viewed 846

I am trying to fetch data from the global variable class and then show it in ListView builder but ListView returns null from the global variable array. But when I hot reload the page it shows the data in widgets but not showing in the initial state. Tried using init state, Future builder but the print is showing that global variable array is not empty but ListView builder is considering it as an empty array. I am new with flutter. Theoretically variable is not storing data from the global variable on the first run but when refreshes the page or come back from any other page it shows the data kindly help me.

import 'package:flutter/material.dart';
import 'package:food_express/classes/AllShefMold.dart';
import 'package:food_express/classes/TodaysLunch.dart';
import 'package:food_express/classes/menuClass.dart';
import 'package:food_express/constant/constant.dart';
import 'package:food_express/pages/restaurant/restaurant.dart';
import 'package:page_transition/page_transition.dart';
import '../../../constant/globals.dart' as global;

class FavouriteRestaurantsList extends StatefulWidget {
  FavouriteRestaurantsList({Key key}) : super(key: key);
  @override
  _FavouriteRestaurantsListState createState() =>
      _FavouriteRestaurantsListState();
}

class _FavouriteRestaurantsListState extends State<FavouriteRestaurantsList> {
  List<TodaysLunch> listDetails = [];
  var restaurantsList;
  @override
  initState() {
     restaurantsList = getItems();
    super.initState();
  }

 List<TodaysLunch> getItems() {
    List<TodaysLunch> listDetails = [];
    for (var shef in global.NearBy) {
      for (var lunch in shef.totalMenu) {
        if (lunch.type == "Todays Menu") {
          for (var item in lunch.menu) {
            TodaysLunch menu = TodaysLunch(shef, item.id, item.Category,
                item.Details, item.DishName, item.Price);
            listDetails.add(menu);
          }
        }
      }
    }
    return listDetails;
  }

  @override
  Widget build(BuildContext context) {
      double width = MediaQuery.of(context).size.width;
      return Column(
        children: [
          Padding(
            padding: EdgeInsets.all(fixPadding),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Text(
                  'Todays Lunch',
                  style: headingStyle,
                ),
                InkWell(
                  onTap: () {
                    // Navigator.push(context, PageTransition(type: PageTransitionType.downToUp, child: MoreList()));
                  },
                  child: Text('View all', style: moreStyle),
                ),
              ],
            ),
          ),
          Container(
              width: width,
              height: 170.0,
              child: ListView.builder(
                        itemCount: restaurantsList.length,
                        scrollDirection: Axis.horizontal,
                        physics: BouncingScrollPhysics(),
                        itemBuilder: (context, index) {
                          final item = restaurantsList[index];
                          return InkWell(
                            onTap: () {
                              // Navigator.push(context, MaterialPageRoute(builder: (context)=>Restaurant(item)));
                              Navigator.push(
                                  context,
                                  PageTransition(
                                      type: PageTransitionType.fade,
                                      child: Restaurant(item.mold)));
                            },
                            child: Container(
                              width: 130.0,
                              decoration: BoxDecoration(
                                color: whiteColor,
                                borderRadius: BorderRadius.circular(5.0),
                              ),
                              margin: (index != (restaurantsList.length - 1))
                                  ? EdgeInsets.only(left: fixPadding)
                                  : EdgeInsets.only(
                                      left: fixPadding, right: fixPadding),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: <Widget>[
                                  Container(
                                    height: 110.0,
                                    width: 130.0,
                                    alignment: Alignment.topRight,
                                    padding: EdgeInsets.all(fixPadding),
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.vertical(
                                          top: Radius.circular(5.0)),
                                      image: DecorationImage(
                                        image: NetworkImage(
                                            item.mold.DisplayImage),
                                        fit: BoxFit.cover,
                                      ),
                                    ),
                                    child: InkWell(),
                                  ),
                                  Container(
                                    width: 130.0,
                                    height: 50.0,
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: <Widget>[
                                        Padding(
                                          padding: EdgeInsets.all(5.0),
                                          child: Text(
                                            item.DishName,
                                            style: listItemTitleStyle,
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                        ),
                                        Padding(
                                          padding: EdgeInsets.only(
                                              left: 5.0, right: 5.0),
                                          child: Text(
                                            item.Details,
                                            style: listItemSubTitleStyle,
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                      ))]);
                    }



}

1 Answers

Tried using init state, Future builder but the print is showing that global variable array is not empty but ListView builder is considering it as an empty array.

This behavior is normal. Even though you updated your variable (in this case restaurantsList array is populated with data), The framework won't know that the restaurantsList array is changed; So, it won't update the view or widgets in your screen. This is the reason why your listview is populated when you hot reload, during hot reload framework checks the state of the variable and then rebuild the widgets.

To trigger a rebuild of ListView you should use built-in setState method or follow any state management tools.

@override
initState() {
  getItems();
  super.initState();
}

Future<void> getItems() async {
await Future.delayed(Duration(milliSeconds:500));
List<TodaysLunch> listDetails = [];
for (var shef in global.NearBy) {
  for (var lunch in shef.totalMenu) {
    if (lunch.type == "Todays Menu") {
      for (var item in lunch.menu) {
        TodaysLunch menu = TodaysLunch(shef, item.id, item.Category,
            item.Details, item.DishName, item.Price);
        listDetails.add(menu);
      }
    }
  }
}

setState(() {
    restaurantsList = listDetails;
});

} 
Related