我正在尝试将 json 列表映射到选项卡栏,并希望选项卡栏标题为“JSON1”
API response :"data": [{"JSON1": {"key1": "val1","key2": "val2"}}],
我的代码:
List dataResponse = [{JSON1: {key1: val1, key2: val2}}]; TabBar( tabAlignment: TabAlignment.start, indicatorSize: TabBarIndicatorSize.tab, dividerColor: Theme.of(context).dividerColor, controller: _tabController, indicatorColor: Theme.of(context).colorScheme.primary, labelColor: Theme.of(context).colorScheme.primary, unselectedLabelColor: Theme.of(context).primaryColorDark.withOpacity(0.8), isScrollable: Responsive.isDesktop(context) ? true : true, tabs: dataResponse.map((e) => Text(e)).toList(), );
`
出现错误:需要“String”类型的值,但得到 JsonMap 类型的值
您收到错误:预期为“String”类型的值,但得到了 JsonMap 类型的值,因为您在 dataResponse.map((e) => Text(e) 的文本小部件中发送整个 json ).toList()
其中 e = ({"JSON1": {"key1": "val1","key2": "val2"}})
相反,仅发送
“Json1”
要解决上述问题,请将代码替换为
dataResponse.map((e) => Text(e)).toList()
选项卡中包含以下内容:
dataResponse.map((e) => Text(e.keys.first)).toList()
此代码迭代列表并从列表的每个 json 映射中找到第一个键。这里的第一个键是 Json1,因此您将收到预期的输出。
List dataResponse = [{"JSON1": {"key1": "val1", "key2": "val2"}}];
TabBar(
tabAlignment: TabAlignment.start,
indicatorSize: TabBarIndicatorSize.tab,
dividerColor: Theme.of(context).dividerColor,
controller: _tabController,
indicatorColor: Theme.of(context).colorScheme.primary,
labelColor: Theme.of(context).colorScheme.primary,
unselectedLabelColor: Theme.of(context).primaryColorDark.withOpacity(0.8),
isScrollable: Responsive.isDesktop(context) ? true : true,
tabs: dataResponse.map((e) {
// Extract the title (assuming there's only one key in the JSON map)
String title = e.keys.first;
return Tab(text: title);
}).toList(),
);