如何在flutter中将具有相同值的查询结果连接到单个Widget中

iszxjhcz  于 2023-03-09  发布在  Flutter
关注(0)|答案(1)|浏览(128)

我正在从本地数据库(sqflite)获取一个使用内部连接的查询,如下所示:

[
{title: First Title, subtitle: First Subtitle, content_title: A_Content Title, text: First text, color: null, warning: 0}, 
{title: First Title, subtitle: First Subtitle, content_title: B_Content Title, text: Second Text, color: null, warning: 0}, 
{title: First Title, subtitle: Second Subtitle, content_title: A_Content Title, text: Third text, color: yellow, warning: 0}, 
{title: First Title, subtitle: Second Subtitle, content_title: B_Content, text: Fourth text, color: null, warning: 0}
]

我需要一种方法来转换它,这样我就可以有一个小部件列表,我可以使用这种模型。

class Category {
  String? subtitle;
  List<Content> content;

Category({
  required this.subtitle,
  required this.content
  });
}

class Content {
  String? title;
  String? text;
  String? color;
  Int? warning;

Content({
  required this.title,
  required this.text,
  required this.color,
  required this.warning
  })
}

实现这一目标的最佳途径是什么?

bkhjykvo

bkhjykvo1#

我认为最好的方法是使用Map作为第三方来链接带有字幕的内容:

List yourDataList = [...];
Map _map = {};

for(int index = 0; index < yourDataList.length; index++) {

 final currentElement = yourDataList[index];

 final currentContent = Content(
      title: currentElement["title"], 
      text: currentElement["text"], 
      color: currentElement["color"], 
      warning: currentElement["warning"],
 );

 // if the subtitle will be used the first time, it will not be registered in the Map, so we initialize it with an empty list, for the next iterations with the same subtitle, this line will just be ignored.
_map[current[subtitle]] ??= [];

// now we can push elements to that List
_map[current[subtitle]]!.add(currentContent);    
}

// for getting now categories that match your model
List<Category> categories = _map.entries.map((entry) => Category(subtitle: entry.key, content: entry.value),
 ),
);

您可以复制此代码并在函数中使用它,接下来您应该能够将catgeories用作List<Category>

相关问题