Map data with expansion tile and list tile flutter

huangapple go评论67阅读模式
英文:

Map data with expansion tile and list tile flutter

问题

// 代码部分不要翻译

以下是翻译好的部分:

我将这些数据插入到我的数据库中,我创建了一个表来存储类别,另一个表来存储问题和答案,通过引用类别表。

这是我的 JSON 数据的外观:

并且我在 Dart 文件中创建了这个 FAQ 模型类。

我创建了一个小部件来显示 ExpansionTile 和 ListTile,其中 ExpansionTile 按类别列出,而 ListTile 在问题列表中。

我希望它显示如下所示,但现在它显示如下所示,请帮助:Map data with expansion tile and list tile flutter

英文:

I insert these data in my db, I create ont table to store the category and one to store teh question and answer by refering the category table.

insert into faqcategory values
('General'),('HR'),('Account'),('Others');

 insert into faq (faqcategoryId, question, answer) values 
(1, 'Question 1', '[{"Step 1": "Here", "Step 2": "Heree", "Step 3": "Hereee"}]'),
(1, 'Question 2', 'Answer for question 2'),
(2, 'Question 3', 'abcdefhhk'),
(4, 'Question 4', 'Answer for question 4');

This is my json data look like

{
        "id": 1,
        "Category": "General",
        "question": "Question 1",
        "answer": "[{\"Step 1\": \"Here\", \"Step 2\": \"Heree\", \"Step 3\": \"Hereee\"}]",
        "image": null,
        "createdDate": "2023-06-14T09:33:47.953",
        "updateDate": null
    },

And I create this FAQ model class in dart file

List<FAQ> faqFromJson(String str) =>
    List<FAQ>.from(json.decode(str).map((x) => FAQ.fromJson(x)));

String faqToJson(List<FAQ> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class FAQ {
  final int? id;
  final String? question;
  final String? answer;
  final String? image;
  final DateTime? createdDate;
  final DateTime? updateDate;

  final FAQCategory? faqCategory;

  FAQ({
    this.id,
    this.question,
    this.answer,
    this.image,
    this.createdDate,
    this.updateDate,
    this.faqCategory,
  });

  factory FAQ.fromJson(Map<String, dynamic> json) => FAQ(
        id: json["id"],
        question: json["question"],
        answer: json["answer"],
        image: json["image"],
        createdDate: json["createdDate"] == null
            ? null
            : DateTime.parse(json["createdDate"]),
        updateDate: json["updateDate"] == null
            ? null
            : DateTime.parse(json["updateDate"]),
        faqCategory: FAQCategory.fromJson(json),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "question": question,
        "answer": answer,
        "image": image,
        "createdDate": createdDate?.toIso8601String(),
        "updateDate": updateDate?.toIso8601String(),
        "faqCategory": faqCategory?.toJson(),
      };
}

class FAQProvider extends ChangeNotifier {
  HttpService httpSer = HttpService();
  List<FAQ> faqlist = <FAQ>[];

  Future<List<FAQ>> getAll({String? query = "", String? category=""}) async {
    var response = await httpSer.get('faq/search?question=$query&categoryType=$category');
    if (response.statusCode == 200) {
      faqlist = faqFromJson(response.body);
      notifyListeners();
    }
    return faqlist;
  }
}

I create a widget to display the expansiontile and list tile, which expansion tile is list by category and list tile in list by question

Widget list(BuildContext context, Size size, List<dynamic> data) {
  Map<String, List<FAQ>> categorizedData = {};
  
  // Categorize the data based on FAQ category
  data.forEach((faq) {
    String category = faq.faqCategory?.name ?? 'Others';
    if (!categorizedData.containsKey(category)) {
      categorizedData[category] = [];
    }
    categorizedData[category]!.add(faq);
  });
  
  return SizedBox(
    child: ListView.builder(
      scrollDirection: Axis.vertical,
      itemCount: categorizedData.length,
      shrinkWrap: true,
      itemBuilder: (BuildContext context, int index) {
        String category = categorizedData.keys.elementAt(index);
        List<FAQ> faqs = categorizedData[category]!;
        
        return ExpansionTile(
          title: Text(category),
          children: faqs.map((faq) {
            return ListTile(
              title: Text(faq.question ?? ''),
              subtitle: Text(faq.answer ?? ''),
            );
          }).toList(),
        );
      },
    ),
  );
}

I want it display like this <br>
Map data with expansion tile and list tile flutter <br>
but now it show like this <br> Map data with expansion tile and list tile flutter <br> PLEASE HELP

答案1

得分: 0

Here is the translated code portion:

如果需要以不同方式显示答案(在这种情况下:"answer": "[{\&quot;Step 1\&quot;: \&quot;Here\&quot;, \&quot;Step 2\&quot;: \&quot;Heree\&quot;, \&quot;Step 3\&quot;: \&quot;Hereee\&quot;}]&quot;),那么您需要为此创建一个新表格,就像您为类别和数据模型一样。

就目前而言,我已经为您使用trycatch和jsonDecoder来管理了它,但这不是一个好的做法。

Widget _list(BuildContext context, List<FAQ> dataList) {
  Map<String, List<FAQ>> categorizedData = {};

  // 根据FAQ类别对数据进行分类
  for (var faq in dataList) {
    String category = faq.faqCategory?.name ?? 'Others';
    if (!categorizedData.containsKey(category)) {
      categorizedData[category] = [];
    }
    categorizedData[category]!.add(faq);
  }

  return ListView.builder(
    itemCount: categorizedData.length,
    itemBuilder: (context, index) {
      return ExpansionTile(
        title: Text(categorizedData.keys.toList()[index] ?? ''),
        childrenPadding: const EdgeInsets.all(16.0),
        children: [
          ListView.builder(
            itemCount: categorizedData.values.toList()[index].length,
            itemBuilder: (cc, ii) {
              FAQ faq = categorizedData.values.toList()[index][ii];
              List<dynamic>? answer;
              try {
                answer = jsonDecode(faq.answer ?? '');
              } catch (e) {
                debugPrint(e.toString());
              }
              return ListTile(
                title: Text(faq.question ?? ''),
                subtitle: answer != null
                    ? ListView.builder(
                        itemCount: answer.first.keys.length,
                        itemBuilder: (c, i) => Text(
                            '${answer?.first.keys.toList()[i]}: ${answer?.first.values.toList()[i]}'),
                        shrinkWrap: true,
                      )
                    : Text(faq.answer ?? ''),
              );
            },
            shrinkWrap: true,
          )
        ],
      );
    },
  );
}

Please note that the code comments have been translated as well.

英文:

If there is requirement of showing answers diffrently (in this kind of case: "answer": "[{&quot;Step 1&quot;: &quot;Here&quot;, &quot;Step 2&quot;: &quot;Heree&quot;, &quot;Step 3&quot;: &quot;Hereee&quot;}]") then you need to make a new table for that, as you made for the category and a datamodel too.

As of now i do managed it for you with using try, catch and jsonDecoder, but it is not good practice.

Widget _list(BuildContext context, List&lt;FAQ&gt; dataList) {
Map&lt;String, List&lt;FAQ&gt;&gt; categorizedData = {};
// Categorize the data based on FAQ category
for (var faq in dataList) {
String category = faq.faqCategory?.name ?? &#39;Others&#39;;
if (!categorizedData.containsKey(category)) {
categorizedData[category] = [];
}
categorizedData[category]!.add(faq);
}
return ListView.builder(
itemCount: categorizedData.length,
itemBuilder: (context, index) {
return ExpansionTile(
title: Text(categorizedData.keys.toList()[index] ?? &#39;&#39;),
childrenPadding: const EdgeInsets.all(16.0),
children: [
ListView.builder(
itemCount: categorizedData.values.toList()[index].length,
itemBuilder: (cc, ii) {
FAQ faq = categorizedData.values.toList()[index][ii];
List&lt;dynamic&gt;? answer;
try {
answer = jsonDecode(faq.answer ?? &#39;&#39;);
} catch (e) {
debugPrint(e.toString());
}
return ListTile(
title: Text(faq.question ?? &#39;&#39;),
subtitle: answer != null
? ListView.builder(
itemCount: answer.first.keys.length,
itemBuilder: (c, i) =&gt; Text(
&#39;${answer?.first.keys.toList()[i]}: ${answer?.first.values.toList()[i]}&#39;),
shrinkWrap: true,
)
: Text(faq.answer ?? &#39;&#39;),
);
},
shrinkWrap: true,
)
],
);
},
);}

And it will look like this.

enter image description here

huangapple
  • 本文由 发表于 2023年6月15日 11:47:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76478959.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定