dart 具有扩展图块和列表图块 Flutter 的Map数据

5vf7fwbs  于 2023-06-19  发布在  Flutter
关注(0)|答案(1)|浏览(125)

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

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');

这是我的json数据的样子

{
        "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
    },

我在dart文件中创建了这个FAQ模型类

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;
  }
}

我创建了一个小部件来显示ExpansionTile和List Tile,其中ExpansionTile是按类别列出的,List Tile是按问题列出的

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(),
        );
      },
    ),
  );
}
    • 我希望它显示为这样**

    • 但现在却变成这样**

请帮忙

qnzebej0

qnzebej01#

如果需要以不同方式显示答案(在这种情况下:“answer”:“[{“步骤1”:“这里”,“步骤2”:“Heree”,“Step 3”:“Hereee”}]”),然后你需要为它创建一个新表,就像你为类别和数据模型创建的一样。
到目前为止,我确实使用try,catch和jsonDecoder为您管理它,但这不是好的做法。

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

// Categorize the data based on FAQ category
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,
        )
      ],
    );
  },
);}

它看起来像这样。
enter image description here

相关问题