dart 在Flutter中编程扩展ExpansionTile

h9a6wy2h  于 2023-06-19  发布在  Flutter
关注(0)|答案(6)|浏览(183)

我只是想在Flutter中使用ExpansionTile,从我修改的示例中变成这样:

我想隐藏箭头并使用Switch来展开图块,可以吗?或者我需要自定义的小部件,以编程方式呈现儿童?基本上,我只需要显示/隐藏孩子们
下面是我的代码:

import 'package:flutter/material.dart';

void main() {
  runApp(ExpansionTileSample());
}
class ExpansionTileSample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('ExpansionTile'),
        ),
        body: ListView.builder(
          itemBuilder: (BuildContext context, int index) =>
              EntryItem(data[index]),
          itemCount: data.length,
        ),
      ),
    );
  }
}

// One entry in the multilevel list displayed by this app.
class Entry {
  Entry(this.title,[this.question='',this.children = const <Entry>[]]);

  final String title;
  final String question;
  final List<Entry> children;
}

// The entire multilevel list displayed by this app.
final List<Entry> data = <Entry>[
  Entry(
    'Chapter A',
    '',
    <Entry>[
      Entry(
        'Section A0',
        '',
        <Entry>[
          Entry('Item A0.1'),
          Entry('Item A0.2'),
          Entry('Item A0.3'),
        ],
      ),
      Entry('Section A1','text'),
      Entry('Section A2'),
    ],
  ),
  Entry(
    'Chapter B',
    '',
    <Entry>[
      Entry('Section B0'),
      Entry('Section B1'),
    ],
  ),
  Entry(
    'Chapter C',
    '',
    <Entry>[
      Entry('Section C0'),
      Entry('Section C1')
    ],
  ),
];

// Displays one Entry. If the entry has children then it's displayed
// with an ExpansionTile.
class EntryItem extends StatelessWidget {
  const EntryItem(this.entry);

  final Entry entry;

  Widget _buildTiles(Entry root) {
    if (root.children.isEmpty) return  Container(
        child:Padding(
          padding: const EdgeInsets.symmetric(
            vertical: 8.0,
            horizontal: 32.0,
          ),
          child:Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children:[
                  Text(root.title),
                  Divider(height: 10.0,),
                  root.question=='text'?Container(
                      width: 100.0,
                      child:TextField(
                        decoration: const InputDecoration(helperText: "question")
                      ),
                  ):Divider()
              ]
          )
        )
    );
    return ExpansionTile(
      //key: PageStorageKey<Entry>(root),
      title: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children:[
          Text(root.title),
          Switch(
            value:false,
            onChanged: (_){},
          )
        ]
      ),
      children: root.children.map(_buildTiles).toList(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return _buildTiles(entry);
  }
}
oxcyiej7

oxcyiej71#

@diegoveloper的回答几乎可以,一个没有涉及的小问题是:它不会将单击Switch进一步传播到ExpansionTile,因此如果您单击外部开关,它会扩展,而单击Switch则不会执行任何操作。用IgnorePointer Package 它,并在扩展事件中设置switch的值。这是一个有点落后的逻辑,但工作得很好。

...
        return ExpansionTile(
          onExpansionChanged: _onExpansionChanged,
          // IgnorePointeer propogates touch down to tile
          trailing: IgnorePointer(
            child: Switch(
                value: isExpanded,
                onChanged: (_) {},
             ),
          ),
          title: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
            Text(root.title),
          ]),
          children: root.children.map((entry) => EntryItem(entry)).toList(),
        );
...
3htmauhk

3htmauhk2#

  • 我认为这将帮助你*initiallyExpanded:真实
itemBuilder: (context, index) {                        
                    return Column(
                      children: <Widget>[
                        Divider(
                          height: 17.0,
                          color: Colors.white,
                        ), 
                              ExpansionTile(  

                                    key: Key(index.toString()), //attention                                                                  
                                    initiallyExpanded : true,
                                    leading: Icon(Icons.person, size: 50.0, color: Colors.black,),
                                    title: Text('Faruk AYDIN ${index}',style: TextStyle(color: Color(0xFF09216B), fontSize: 17.0, fontWeight: FontWeight.bold)), 
                                    subtitle: Text('Software Engineer', style: TextStyle(color: Colors.black, fontSize: 13.0, fontWeight: FontWeight.bold),),
                                    children: <Widget>[                                       
                                      Padding(padding: EdgeInsets.all(25.0), 
                                                  child : Text('DETAİL ${index} \n' + 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using "Content here, content here", making it look like readable English.',)
                                                  ) 
                                    ],
                                    onExpansionChanged: ((newState){
                                        if(newState)
                                            setState(() {
                                              Duration(seconds:  20000);
                                              selected = index; 
                                            });
                                            else setState(() {
                                              selected = -1; 
                                            });        
                                    })
                                  ),
                             
                          ]
                        );
0tdrvxhp

0tdrvxhp3#

是的,这是可能的,我修改了你的代码一点:

class EntryItem extends StatefulWidget {
          const EntryItem(this.entry);
          final Entry entry;

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

        class EntryItemState extends State<EntryItem> {
          var isExpanded = false;

          _onExpansionChanged(bool val) {
            setState(() {
              isExpanded = val;
            });
          }

          Widget _buildTiles(Entry root) {
            if (root.children.isEmpty)
              return Container(
                  child: Padding(
                      padding: const EdgeInsets.symmetric(
                        vertical: 8.0,
                        horizontal: 32.0,
                      ),
                      child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(root.title),
                            Divider(
                              height: 10.0,
                            ),
                            root.question == 'text'
                                ? Container(
                                    width: 100.0,
                                    child: TextField(
                                        decoration: const InputDecoration(
                                            helperText: "question")),
                                  )
                                : Divider()
                          ])));
            return ExpansionTile(
              onExpansionChanged: _onExpansionChanged,
              trailing: Switch(
                value: isExpanded,
                onChanged: (_) {},
              ),
              //key: PageStorageKey<Entry>(root),
              title: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                Text(root.title),
              ]),
              children: root.children.map((entry) => EntryItem(entry)).toList(),
            );
          }

          @override
          Widget build(BuildContext context) {
            return _buildTiles(widget.entry);
          }
        }

基本上,我从Stateless改为Stateful,因为您需要处理Switch小部件的状态。
ExpansionTile中有一个trailing属性,我在其中放置了Switch,以默认删除arrow小部件。
收听onExpansionChanged: _onExpansionChanged,,以更改交换机的状态。
最后将子组件构建为新的widget:

children: root.children.map((entry) => EntryItem(entry)).toList(),
5ktev3wc

5ktev3wc4#

**简答:**设置initiallyExpanded为true或false,相应的可以借助onExpansionChanged。但请记住initiallyExpanded仅适用于初始状态,因此应更改小部件的键以应用更改。现在要更改关键点,解决方法是:

ExpansionTile(
     key: PageStorageKey("${DateTime.now().millisecondsSinceEpoch}"),
     initiallyExpanded: ....
     onExpansionChanged: ....
     .
     .
     .
)
nzkunb0c

nzkunb0c5#

initiallyExpanded = true,这个答案是正确的,但是如果我们在ExpansionTile的子元素中有一个TextFiled,那么键盘会自动隐藏(bug)。所以我的解决方案是用Visibilitywidget和控件visibilty Package 孩子。初始声明**bool _expansionVisibility = false;**

ExpansionTile(
            onExpansionChanged: (changed) {
              setState(() {
                print("changed $changed");
                if (changed) {
                  _expansionVisibility = true;
                } else {
                  _expansionVisibility = false;
                }
              });
            },
            title: Text(
              "Change Password",
            ),
            children: <Widget>[
              Visibility(
                visible: _expansionVisibility,
                child: Container(),
              ),
            ],
          ),
d7v8vwbk

d7v8vwbk6#

现在有一个ExpansionTileController,它可以用编程方式关闭切片,如docs中所解释的。

相关问题