1

Hi i am new to flutter and i use the the code from below question answers and expand/collps works but i am facing 1 issue.

Issue:

When there's long list then few ExpansionTile automatically getting closed on scroll.

below is the updated code.

void main() => runApp(
    const MaterialApp(
        home: MyApp(),
    ));

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  MyAppState createState() {
    return new MyAppState();
  }
}

class Days {
  var outlateName;
  var outletAddress;
  var ratings;
  var url;
  Days(this.outlateName, this.outletAddress, this.ratings, this.url);
}

class MyAppState extends State<MyApp> with AutomaticKeepAliveClientMixin {
  List<Days> arrMondayOutlet = [
    Days(
        'Icy Pik Frozen Foods',
        'Shop No 3/4, Shyam Gokul Complex, Navrangpura, Ahmedabad - 380009, Near Vijay Cross Road',
        '184',
        'https://content.jdmagicbox.com/comp/ahmedabad/t4/079pxx79.xx79.110915203656.d8t4/catalogue/icy-pik-frozen-foods-navrangpura-ahmedabad-fast-food-3uvhb6w.jpg'),
    Days(
        'Binharif Dabeli Gandhidham',
        'A/2, Ground Floor, Mohini Complex, Bodakdev, Ahmedabad - 380054, Beside Atithi Dinning Hall',
        '138',
        'https://content.jdmagicbox.com/comp/ahmedabad/p5/079pxx79.xx79.181022120412.y8p5/catalogue/binharif-dabeli-gandhidham-wala-bodakdev-ahmedabad-fast-food-lfkv5vq2m7.jpg'),
    Days(
        'A Little Bakers',
        'Gf 5 Avadh Pride, Near Metro Pillar 142, Vastral, Ahmedabad - 382418, Near Nirant Chokdi Vastral',
        '10',
        'https://content.jdmagicbox.com/comp/ahmedabad/q4/079pxx79.xx79.191211134900.g5q4/catalogue/a-little-baker-s-vastral-ahmedabad-cake-shops-iq3rlbq8hi.jpg'),
  ];

  List<Days> arrTuesdayOutlet = [
    Days(
        'MD The Snacks Club',
        'Shop No 12, BGF Swaminarayan Avenue, Naranpura Vistar, Ahmedabad - 380013, Near Torrent Power Ltd',
        '2',
        'https://content3.jdmagicbox.com/comp/ahmedabad/p8/079pxx79.xx79.210109120039.s4p8/catalogue/md-the-snacks-club-naranpura-vistar-ahmedabad-fast-food-xg9ousws4a.jpg'),
    Days(
        'Al Baik',
        '13, Abad Arcade, Al Asbab Park, 100 Feet Road Makarba Road Near Essar Pump, Makarba, Ahmedabad - 380051, Opposite Al Burooj',
        '8',
        'https://content.jdmagicbox.com/comp/ahmedabad/k1/079pxx79.xx79.191127122120.d5k1/catalogue/al-baik-ahmedabad-df40ilybtb.jpg'),
  ];

  List<Days> arrWednesdayOutlet = [
    Days(
        'Food Juction',
        'B/12,13 ,Krishna Heights Ground Floor, Godrej Garden City Road, Jagatpur, Ahmedabad - 382470, Never.ganesh Genises',
        '1641',
        'https://content.jdmagicbox.com/comp/ahmedabad/q2/079pxx79.xx79.170628132059.u6q2/catalogue/food-junction-ahmedabad-ptui2.jpg'),
    Days(
        'Mangal Murti Garden Restaurant',
        'Mangal Murti Dhaba, Vishat- Koba Highway, Chandkheda, Ahmedabad - 382424, Nr Tapovan Circle , Opp Jain Merudham Mandir, Amiyapur',
        '793',
        'https://content.jdmagicbox.com/comp/ahmedabad/l4/079pxx79.xx79.171213152347.f6l4/catalogue/mangal-murti-garden-restaurant-chandkheda-ahmedabad-rajasthani-restaurants-ayw0tpnmmb.jpg'),
    Days(
        'Puffizza',
        '103, First Floor, Kairos, Drive In Road, Gurukul, Ahmedabad - 380052, Near Manav Mandir, Opposite Mahatma Gandhi Labour Institute',
        '1743',
        'https://content.jdmagicbox.com/comp/ahmedabad/b7/079pxx79.xx79.150124191031.l5b7/catalogue/puffizza-gurukul-ahmedabad-pizza-outlets-bucktrweom.jpg'),
  ];

  List<Days> arrThursdayOutlet = [
    Days(
        'Jay Ambe Fastfood & Tiffin',
        'Bhatt Mevada Boys Canteen, Mithakali Cross Road, Navrangpura, Ahmedabad - 380009, Behind Sardar Patel Seva Samaj',
        '43',
        'https://content.jdmagicbox.com/comp/ahmedabad/x9/079pxx79.xx79.160506105153.t6x9/catalogue/jay-ambey-fastfood-and-tiffin-service-navrangpura-ahmedabad-tiffin-services-0y3yalteny.jpg'),
    Days(
        'Re Younion Cafe Restaurant',
        'Swagat Plaza,opposite Axis Bank, Ambli Bopal Road, Bopal, Ahmedabad - 380058, Opposite TVS Showroom,near Mercedes Show Room',
        '17',
        'https://content.jdmagicbox.com/comp/ahmedabad/j8/079pxx79.xx79.210821161817.z6j8/catalogue/-h3eh2un1s8.jpg'),
  ];

  List<Days> arrFridayOutlet = [
    Days(
        'Anchor Food Plaza',
        'Sh 6, Bhavnagar Pipali Highway, Aambli, Pipali, Ahmedabad - 382465',
        '2730',
        'https://content.jdmagicbox.com/comp/ahmedabad/y2/079pxx79.xx79.170609200047.f9y2/catalogue/anchor-food-plaza-ahmedabad-restaurants-q67c3.jpg'),
    Days(
        'Purohit Restaurant & Dining',
        'Maninagar, Ahmedabad - 380008, Near Apsara Aradhana Theater Puspakunj Kankaria',
        '2306',
        'https://content.jdmagicbox.com/comp/ahmedabad/78/079p11678/catalogue/purohit-restaurant-and-dining-hall-maninagar-ahmedabad-restaurants-lhwyzx.jpg'),
    Days(
        'Kaka Ni Bhaji Pav And Fast',
        '160/161, Rameshwar Soci., Rajendrapark Cross Road, National Highway No 8, Odhav Gam, Ahmedabad - 382415',
        '1669',
        'https://content.jdmagicbox.com/comp/def_content/pav_bhaji_centres/default-pav-bhaji-centres-1.jpg'),
  ];

  List<Days> arrSaturdayOutlet = [
    Days(
        'Cafe Urbanyan',
        'A-301, 3rd Floor, Celebration City Centre, Gala Gymkhana Road, Bopal, South Bopal, Ahmedabad - 380058, Above Reliance Trends',
        '111',
        'https://content.jdmagicbox.com/comp/ahmedabad/d4/079pxx79.xx79.190306210037.q3d4/catalogue/cafe-urbanyan-south-bopal-ahmedabad-restaurants-mcreevefp6.jpg'),
    Days(
        'Prince Corner',
        'Shop No 17 to 20, Margine Millenium Plaza, Vastrapur, Ahmedabad - 380015, Near Swaminarayan Temple, Mansi Circle',
        '6',
        'https://content.jdmagicbox.com/comp/ahmedabad/q6/079pxx79.xx79.140424192006.y2q6/catalogue/prince-corner-vastrapur-ahmedabad-pav-bhaji-centres-8rgxm.jpg'),
  ];

  List<Widget> _getChildren(int count, List<Days> arrData) =>
      List<Widget>.generate(
        arrData.length,
        (i) => Card(
          child: ListTile(
            //**** IMAGE LOADING WITH PLACEHOLDER ****/
            leading: ClipRRect(
              child: FadeInImage.assetNetwork(
                placeholder: 'assets/loading.gif',
                image: arrData[i].url,
                fit: BoxFit.cover,
                height: 60,
                width: 60,
              ),
            ),
            title: Text(arrData[i].outlateName,
                style: const TextStyle(fontWeight: FontWeight.w500)),
            subtitle: Text(arrData[i].outletAddress),
            trailing: const Icon(
              Icons.arrow_forward_ios,
              size: 16,
              color: Colors.black,
            ),
          ),
        ),
      );

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return MaterialApp(
      builder: (context, child) => Scaffold(
        appBar: AppBar(
          title: const Text('Outlet List'),
          actions: <Widget>[
            Padding(
              padding: const EdgeInsets.only(right: 20.0),
              child: GestureDetector(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) => Products()),
                  );
                },
                child: const Icon(Icons.production_quantity_limits_sharp),
              ),
            ),
          ],
        ),
        body: SafeArea(
          child: ListView(
            children: [
              Theme(
                data: Theme.of(context)
                    .copyWith(dividerColor: Colors.transparent),
                child: ExpansionTile(
                  title: const Text(
                    'Monday',
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  children: _getChildren(4, arrMondayOutlet),
                ),
              ),
              Theme(
                data: Theme.of(context)
                    .copyWith(dividerColor: Colors.transparent),
                child: ExpansionTile(
                  title: const Text(
                    'Tuesday',
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  children: _getChildren(3, arrTuesdayOutlet),
                ),
              ),
              Theme(
                data: Theme.of(context)
                    .copyWith(dividerColor: Colors.transparent),
                child: ExpansionTile(
                  title: const Text(
                    'Wednesday',
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  children: _getChildren(3, arrWednesdayOutlet),
                ),
              ),
              Theme(
                data: Theme.of(context)
                    .copyWith(dividerColor: Colors.transparent),
                child: ExpansionTile(
                  title: const Text(
                    'Thursday',
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  children: _getChildren(3, arrThursdayOutlet),
                ),
              ),
              Theme(
                data: Theme.of(context)
                    .copyWith(dividerColor: Colors.transparent),
                child: ExpansionTile(
                  title: const Text(
                    'Friday',
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  children: _getChildren(3, arrFridayOutlet),
                ),
              ),
              Theme(
                data: Theme.of(context)
                    .copyWith(dividerColor: Colors.transparent),
                child: ExpansionTile(
                  title: const Text(
                    'Saturday',
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  children: _getChildren(3, arrSaturdayOutlet),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

Can you please let me know what am i missing or is there anything else?

Thanks

Kuldeep
  • 4,466
  • 8
  • 32
  • 59

3 Answers3

1

In this case you like to make the children alive even if it is out of view.

replacing ListView with SingleChildScrollView <Column> like

 body: SafeArea(
          child: SingleChildScrollView(
            child: Column(
              children: [
                Theme(........

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
1

Simply set maintainState to true in ExpansionTile

ExpansionTile(
          title: const Text(
            'Monday',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          children: _getChildren(4, arrMondayOutlet),
          maintainState: true,  // <------ add this
        ),
  • 1
    I added `maintainState: true` but it wasn't work for me. still list got collapsed while scrolling. – Kuldeep Sep 21 '21 at 04:56
1

This will work if your ExpansionTile are inside ListView

ListView.separated(
  shrinkWrap: true,
  itemCount: 10,
  separatorBuilder: (_ctx, _index) {
    return const SizedBox(height: 20);
  },
  itemBuilder: (_ctx, _index) {
    return WidgetItem(index: _index);
  },
)

widget_item.dart

class WidgetItem extends StatelessWidget {
  final int? index;
  const WidgetItem({Key? key, this.index}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ExpansionTile(
        key: PageStorageKey(index.toString()), // This line solved issue
        maintainState: true,
        tilePadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
        childrenPadding: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
        title: Text('Title'),
        children: [
          // Children
        ],
        onExpansionChanged: (isExpanded) {},
      );
  }
}
Ketan Ramani
  • 4,874
  • 37
  • 42