我在显示数据时遇到问题,所有数据都是从
Get
方法正确接收的,但我无法处理它来显示值。
在
getDataLadder
中成功接收了response.body
中的数据,我可以通过print('Response Body : ${response.body}');
看到结果
在本节中,我将数据存储在
stringResponse
值中,但我无法在本节中显示 json 数据:
Widget getBody() {
var size = MediaQuery.of(context).size;
return Container(
width: size.width,
height: size.height,
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10)),
color: Colors.white),
child: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Flexible(
child: Container(
height: 1,
decoration:
BoxDecoration(color: Colors.grey.withOpacity(0.2)),
),
),
SizedBox(
width: 10,
),
Text(
stringResponse.toString(),
style: TextStyle(color: Colors.black54),
),
SizedBox(
width: 10,
),
Flexible(
child: Container(
height: 1,
decoration:
BoxDecoration(color: Colors.grey.withOpacity(0.2)),
),
),
],
),
SizedBox(
height: 15,
),
Column(
children: List.generate(nardeban_data.length, (index) {
return Column(
children: [
Padding(
padding: const EdgeInsets.only(right: 5, left: 5),
child: Container(
decoration: new BoxDecoration(
image: new DecorationImage(
image: new AssetImage("assets/images/bg.png"),
fit: BoxFit.fill,
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
height: 90,
// width: (size.width - 20) * 0.68,
child: Row(
children: [
SizedBox(width: 20), // give it width
Container(
width: 40,
decoration: BoxDecoration(
color: Colors.blue,
border:
Border.all(color: Colors.blue),
borderRadius:
BorderRadius.circular(40.0)),
child: Padding(
padding: EdgeInsets.all(10.0),
child: Text("14",
style: TextStyle(
fontSize: 13.0,
fontWeight: FontWeight.bold,
color: Colors.white)))),
SizedBox(
width: 10,
),
Container(
child: Column(
mainAxisAlignment:
MainAxisAlignment.center,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(
nardeban_data[index]['name'],
style: TextStyle(
fontSize: 14,
color: Colors.black54,
fontWeight: FontWeight.w400),
overflow: TextOverflow.ellipsis,
),
],
),
)
],
),
),
Container(
width: (size.width - 120) * 0.32,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
border: Border.all(color: Colors.blue)),
child: Padding(
padding: const EdgeInsets.only(
right: 10,
bottom: 4,
left: 10,
top: 4),
child: Row(
children: [
SizedBox(
width: 25,
height: 25,
child: TextField(
textAlign: TextAlign.center,
keyboardType:
TextInputType.number,
decoration: InputDecoration(
hintText: '4%',
border: InputBorder.none,
contentPadding: EdgeInsets.only(
bottom: 8,
top: 3,
),
),
),
)
],
),
),
),
// Icon(
// Icons.notifications,
// size: 22,
// color: Colors.blue.withOpacity(0.7),
// )
],
),
)
],
),
)),
],
);
})),
],
),
),
);
}
这是我从 API 调用中获取的 json:
{
"pellekan": [
{
"name": "1",
"form": null,
"to": "1000000",
"percent": 1
},
{
"name": "2",
"form": "1000000",
"to": 1100000,
"percent": 2.89
},
{
"name": "3",
"form": "1000000",
"to": 1200000,
"percent": 4.79
},
]
}
这也是我的课程,我从中定义
stringResponse
值
var stringResponse = [];
class ResultLadder extends StatefulWidget implements PreferredSizeWidget {
@override
Size get preferredSize => const Size.fromHeight(100);
const ResultLadder({Key? key}) : super(key: key);
@override
_ResultLadderState createState() => _ResultLadderState();
}
Future<String> getToken() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString('login')!;
}
class _ResultLadderState extends State<ResultLadder> {
String token = "";
@override
void initState() {
// getInfo();
getDataLadder();
super.initState();
}
一般来说,例如我如何在 json 数据中显示
name
而不是 "14"
,如下所示:代码:
child: Text("14",
style: TextStyle(
fontSize: 13.0,
fontWeight: FontWeight.bold,
color: Colors.white))
这是
getDataLadder
代码:
Future getDataLadder() async {
print('bye');
String token = await getToken();
var response = await http.get(
Uri.parse('https://mylocalapiurl.com/backend/api/v1/pellekan/main/active'),
headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
});
print('Token : ${token}');
print('Response Body : ${response.body}');
if (response.statusCode == 200) {
setState(() {
stringResponse = json.decode(response.body);
});
}
}
nardebanladder 是数据文件夹中的一个文件,我添加此值以显示数据演示(这是有效的):
const List nardeban_data = [
{
"img":
"https://images.unsplash.com/image.jpg",
"name": "mark wiliams",
"takhfif": "description item"
},
{
"img":
"https://images.unsplash.com/photo-1610859923380-c8e5a13165d1?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80",
"name": "joe mark",
"takhfif": "description item"
},
];```
所以现在使用您的 stringResponse 因为它已经被解码为 JSON,我将创建一个小的 PODO(普通 Ol' Dart 对象)将我的 JSON 映射到您正在接收的数据,如下所示:
class NardebanData {
String? name;
String? form;
String? to;
double? percent;
NardebanData({ this.name, this.form, this.to, this.percent });
factory NardebanData.fromJson(Map<String, dynamic> json) {
return NardebanData(
name: json['name'],
form: json['form'],
to: json['to'],
percent: json['percent']
);
}
}
在您的 setState() 调用中,然后将其映射为这样:
setState(() {
stringResponse = json.decode(response.body);
nardeban_data = (stringResponse['pellekan'] as List<dynamic>).map((d) => NardebanData.fromJson(d)).toList();
});
因此,使您的 nardeban_data 不再是 const ,而是 NardebanData 对象列表:
List<NardebanData> narbeban_data = [];
当您使用它时(在 List.generate 内部),您可以在迭代中获取当前对象,如下所示:
children: List.generate(nardeban_data.length, (index) {
// fetch the item in the collection by the index provided
NardebanData dataItem = nardeban_data[index];
// ALL YOUR WIDGET STRUCTURE HERE
// LIKE YOUR TEXT WIDGETS AS IN:
Text(
dataItem.name!, // pull the data out of the dataItem using the provided properties
style: TextStyle(
fontSize: 14,
color: Colors.black54,
fontWeight: FontWeight.w400),
overflow: TextOverflow.ellipsis,
),
}
还要确保来自 API 的 JSON 数据与每个字段中的数据类型一致,否则解码将失败(即确保 name、form、to 是字符串,百分比是字符串)是一个双)。
看看这是否适合您。