Flutter Auto Collapse ExpansionTile After Choosing an Item

📅️ Published:

🔄 Updated:

🕔 3 min read ∙ 615 words

Membuat beberapa ExpansionTile ketika di klik salah satu item maka item yang di klik tersebut akan melihat bagian detail, sebaliknya item yang lain maka akan menciut/menutup bagian detailnya.

Di Flutter ketika Widget tersebut ada perubahan Key maka widget tersebut akan rebuild. Ini bisa kita manfaatkan seperti tujuan kita.

Mari langsung ke studi kasus pada kodenya.

1
int _selectedCode = 0;

Variable tersebut kita gunakan sebagai value/intial item yang item nya tersebut dan mode detail.

Kemudian buat Widget ListView.builder sebagai widget yang menampung daftar/list item ExpansionTile berikut codenya:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
ListView.builder(
  key: Key('selected $_selectedItem'),
  itemBuilder: (context, index) {
    return ExpansionTile(
      key: Key(index.toString()), //attention
      initiallyExpanded: index == _selectedItem, //attention
      title: Text('Item $index'),
      children: <Widget>[
        Padding(
          padding: EdgeInsets.all(25.0),
          child: Text(
            'DETAÄ°L $index \n' +
            'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.',
          ))
      ],
      onExpansionChanged: (isOpen) {
        if (isOpen) {
          setState(() {
            _selectedItem = index;
          });
        }
      },
    );
  },
  itemCount: 20,
),

Key yang ada di Widget ListView.builder berfungsi ketika ada perubahan item yang di klik sekarang maka akan rebuild widget. Dan untuk Key di ExpansionTile untuk menandakan unik itemnya tersebut.

Dan untuk callback method onExpansionChanged berfungsi jika ada perubahan di Widget ExpansionTile akan melakukan fungis apa, dalam kasus ini saya menggunakannya untuk merubahan state selectedItem jadi yang di klik sekarang.

Untuk full contoh kodenya bisa lihat di sini:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;
  MyHomePage({Key? key, required this.title}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _selectedItem = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: 
      ListView.builder(
        key: Key('selected $_selectedItem'),
        itemBuilder: (context, index) {
          return ExpansionTile(
            key: Key(index.toString()), //attention
            initiallyExpanded: index == _selectedItem, //attention
            title: Text('Item $index'),
            children: <Widget>[
              Padding(
                padding: EdgeInsets.all(25.0),
                child: Text(
                  'DETAÄ°L $index \n' +
                  'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.',
                ))
            ],
            onExpansionChanged: (isOpen) {
              if (isOpen) {
                setState(() {
                  _selectedItem = index;
                });
              }
            },
          );
        },
        itemCount: 20,
      ),
    );
  }
}

Demo:



Terdapat kesalahan penulisan, typo, ataupun juga kurang sesuai dalam penulisan, bantu Saya Edit on Github.


💬 Comment: