gpt4 book ai didi

android - 如何仅打印 json 映射中值的特定部分?

转载 作者:行者123 更新时间:2023-12-03 18:57:17 24 4
gpt4 key购买 nike

我是 Flutter 的新手,我关注了 StackOverflow 上关于从 json 映射中检索数据的另一篇文章。它有效,但现在我只想从 map 中访问我需要的数据。我也无法从 map 中删除多余的数据,因为我需要相同的 map 用于应用程序的另一部分。
这就是代码的样子。

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return CupertinoApp(
localizationsDelegates: <LocalizationsDelegate<dynamic>>[
DefaultMaterialLocalizations.delegate,
DefaultWidgetsLocalizations.delegate,
DefaultCupertinoLocalizations.delegate,
],
theme: CupertinoThemeData(
primaryColor: Color(0xffffffff),
),
home: TransactionHistoryScreen(),
);
}
}

class TransactionHistoryScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
child: Scaffold(body: Container(child: MakeList(),),),
);
}
}

class MakeList extends StatelessWidget {
final List<Map<String, String>> json = [
{"branch": "B1", "xyz": "0", "ABC": "2", "MN": "2"},
{"branch": "B2", "xyz": "0", "ABC": "0", "MN": "0"},
{"branch": "B3", "xyz": "1", "ABC": "1", "MN": "42"},
{"branch": "B4", "xyz": "0", "ABC": "5", "MN": "69"},
];

@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: json.length,
itemBuilder: (BuildContext context, int index) {
return ListTileClass(jsonObject: json[index]);
},
);
}
}

class ListTileClass extends StatefulWidget {
final Map<String, String> jsonObject;

ListTileClass({this.jsonObject});

@override
_ListTileClassState createState() => _ListTileClassState();
}

class _ListTileClassState extends State<ListTileClass> {
@override
Widget build(BuildContext context) {
return ListTile(
title: Container(
child: Row(
children: makeWidgetChildren(widget.jsonObject),
),
),
);
}

List<Widget> makeWidgetChildren(jsonObject) {
List<Widget> children = [];
jsonObject.keys.forEach(
(key) => {
children.add(
Padding(
child: Text('${jsonObject[key]}'), padding: EdgeInsets.all(8.0)),
),
},
);
return children;
}
}
使用此代码,我可以打印 map 每个键的值。如何访问特定 key ?例如,如何仅打印“分支”和“xyz”值?

最佳答案

在许多情况下,您可以在 dart 中使用 forEach:

void main() {
final List<Map<String, String>> json = [
{"branch": "B1", "xyz": "0", "ABC": "2", "MN": "2"},
{"branch": "B2", "xyz": "0", "ABC": "0", "MN": "0"},
{"branch": "B3", "xyz": "1", "ABC": "1", "MN": "42"},
{"branch": "B4", "xyz": "0", "ABC": "5", "MN": "69"},
];
json.forEach((item) => print("Branch : ${item['branch']}, xyz : ${item['xyz']}"));
}
输出 :
Branch : B1, xyz : 0
Branch : B2, xyz : 0
Branch : B3, xyz : 1
Branch : B4, xyz : 0

关于android - 如何仅打印 json 映射中值的特定部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65624524/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com