ExpansionPanelRadio

问题描述

如何为每个可扩展磁贴添加唯一值,使常见问题解答看起来像这样?

FAQ Example

从这个链接获取我的代码https://medium.com/aubergine-solutions/how-to-create-expansion-panel-list-in-flutter-2fba574366e8

我想添加我自己唯一的 headerValue 和 expandValue,而不是让它只占用像

这样的标准数字
 headerValue: 'Book $index',expandedValue: 'Details for Book $index goes here'

我可能会使用这个类而不是他们的:

class FAQ {
  FAQ({
    this.id,this.expandedValue,this.headerValue,});

  int id;
  String expandedValue;
  String headerValue;
}

解决方法

您可以创建可以返回问题列表的自定义类。在您的 Item 类中,您需要定义函数 Item.fromJson(dynamic json),它将返回您 Map 或您的项目。然后,您可以再创建一个函数,将实际数据传递给类 Item,它会返回 Map,以便您可以在小部件中使用。

这是完整的代码和工作

  class Item {
  final String id;
  final String expandedValue;
  final String headerValue;
  Item(
    this.id,this.expandedValue,this.headerValue,);

  factory Item.fromJson(dynamic json) {
    return Item(
        "${json['id']}","${json['expandedValue']}","${json['headerValue']}");
  }
}

var mylist = [
  {"id": "1","headerValue": "question 1","expandedValue": "answer 1"},{"id": "2","headerValue": "question 2","expandedValue": "answer 2"}
];

getFeedbackList() {
  return mylist.map((json) => Item.fromJson(json)).toList();
}

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

  @override
  State<ExpansionItems> createState() => _ExpansionItemsState();
}

class _ExpansionItemsState extends State<ExpansionItems> {
  final List<Item> _data = getFeedbackList();
  @override
  Widget build(BuildContext context) {
    print(_data);
    return SingleChildScrollView(
      child: Container(
        child: _buildPanel(),),);
  }

  Widget _buildPanel() {
    return ExpansionPanelList.radio(
      initialOpenPanelValue: 2,children: _data.map<ExpansionPanelRadio>(
        (Item item) {
          return ExpansionPanelRadio(
            value: item.id,headerBuilder: (BuildContext context,bool isExpanded) {
              return ListTile(
                title: Text(item.headerValue),);
            },body: ListTile(
              title: Text(item.expandedValue),);
        },).toList(),);
  }
}

你可以试试上面的代码here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...