无法从容器中的 API 显示数组列表 [英] Unable to display the list of array from an API in a container
问题描述
我试图在容器中显示从 API 接收到的数据,但最终出现了一些错误,所以我使用静态方法来显示收到的 API 数据,并在那里取得了成功.但我无法弄清楚我的流程出了什么问题.
I was trying to display the received data from API in the container but ended up with some errors, so I used the static method to display the API data received well-got success there. But I cannot figure out what is going wrong with my process.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class Ticket extends StatefulWidget {
@override
_TicketState createState() => _TicketState();
}
class _TicketState extends State<Ticket> {
var nos;
@override
void initState(){
super.initState();
_getNumbers();
}
_getNumbers() async{
var result = await http.post('https://tickets-qzd55332wa-de.a.run.app/generateTickets?ticketsRequired=1');
print(result.body);
}
//API RESPONSE(This is what I have made it locally but I want to fetch the same from the API itself)
List tick = [
// This is the exact output of the data fetched from the API
{
'tickets': [
[
[11, 5, 7, 10, 28, 9, 7, 74, 59],
[1, 15, 7, 10, 8, 79, 27, 74, 9],
[71, 5, 7, 20, 18, 9, 77, 74, 79],
],
[
[21, 5, 7, 80, 8, 9, 7, 74, 49],
[31, 15, 7, 10, 18, 79, 7, 74, 19],
[71, 5, 7, 20, 18, 79, 77, 74, 29],
],
]
},
];
@override
Widget build(BuildContext context) {
var h = MediaQuery.of(context).size.height;
var w = MediaQuery.of(context).size.width;
return Scaffold(
body: SafeArea(
child: Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
)),
child: ListView.builder(
itemCount: tick.length,
itemBuilder: (BuildContext context, index) {
List tripleNumbersList = [];
List<Widget> cells = [];
List<Widget> rows = [];
//Get the lenght of the list inside the 'tickets' map
int ticketsCount = tick[index]['tickets'].length;
//Iterates over the lists inside the 'tickets' map
for (int i = 0; i < ticketsCount; i++) {
//Get the lists of lists inside the 'tickets' map
tripleNumbersList = tick[index]['tickets'][i];
//Iterates over each list with other 3 lists
for (int j = 0; j < tripleNumbersList.length; j++) {
//Get one of the 3 lists
List<int> list = tripleNumbersList[j];
//Iterates over the list of numbers
for (int k = 0; k < list.length; k++) {
//Adds a Widget to 'cells; list for each number
cells.add(Container(
height: 40,
width: 40,
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
),
//color: Colors.pink
),
child: GestureDetector(
onTap: () {
print('Working');
},
child: Text(
' ${list[k]} ',
style: TextStyle(
fontSize: 22.0,
fontWeight: FontWeight.bold),
))));
}
//Adds the list of 'cells' in the 'rows' list
rows.add(Row(children: cells));
cells = [];
}
//Adds a empty row to make space
rows.add(Row(children: [
Container(
height: 20,
)
]));
}
return Center(
child: Container(
height: h,
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
),
//color: Colors.pink
),
child: Column(
//Adds the list of rows to the column
children: rows,
),
),
);
},
),
),
),
),
),
);
}
}
这是我使用 API 的响应制作的目标文件.
This is the object file that I made using the response of the API.
Tickets ticketsFromJson(String str) => Tickets.fromJson(json.decode(str));
String ticketsToJson(Tickets data) => json.encode(data.toJson());
class Tickets {
Tickets({
this.tickets,
});
List<List<List<int>>> tickets;
factory Tickets.fromJson(Map<String, dynamic> json) =>
Tickets(
tickets: List<List<List<int>>>.from(
json["tickets"].map((x) => List<List<int>>.from(
x.map((x) => List<int>.from(x.map((x) => x)))))),
);
Map<String, dynamic> toJson() =>
{
"tickets": List<dynamic>.from(tickets.map((x) => List<dynamic>.from(
x.map((x) => List<dynamic>.from(x.map((x) => x)))))),
};
}
请帮助我解决我的代码有什么问题以及如何将数字显示为 in这张照片
Please help me out with what is wrong with my code and how to display the number as in this picture
推荐答案
对于 API 请求,您需要等待结果,然后尝试解析结果.并且由于从 json 创建的模型返回一个带有嵌套列表的列表,因此迭代几乎与硬编码数据结构相同.我对代码进行了一些更改以使其正常工作,但有时您的 API 似乎无法用于请求.你需要检查这个.查看代码中的注释以了解所做的更改:
With an API request you need wait for the result and then try to parse the result. And since the model created from the json return a list with nested lists, the iteration is almost the same as the hardcoded data structure. I made some changes in the code to make it work, but sometimes your API doesn't seems not available to requests. You need check this. See the comments in the code to understand the changes made:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class Ticket {
Ticket({
this.tickets,
});
List<List<List<int>>> tickets;
factory Ticket.fromJson(Map<String, dynamic> json) => Ticket(
tickets: List<List<List<int>>>.from(json["tickets"].map((x) =>
List<List<int>>.from(
x.map((x) => List<int>.from(x.map((x) => x)))))),
);
Map<String, dynamic> toJson() => {
"tickets": List<dynamic>.from(tickets.map((x) => List<dynamic>.from(
x.map((x) => List<dynamic>.from(x.map((x) => x)))))),
};
}
class TicketPage extends StatefulWidget {
@override
_TicketPageState createState() => _TicketPageState();
}
class _TicketPageState extends State<TicketPage> {
var nos;
Ticket ticketList;
String apiResult;
@override
void initState() {
super.initState();
_getNumbers();
}
_getNumbers() async {
var result = await http
.post(
'https://tickets-qzd55332wa-de.a.run.app/generateTickets?ticketsRequired=2')
.then((result) {
//Waits for the API response and assigns to apiResult variable
setState(() {
apiResult = result.body;
});
});
}
// List tick = [
// {
// 'tickets': [
// [
// [11, 5, 7, 10, 28, 9, 7, 74, 59],
// [1, 15, 7, 10, 8, 79, 27, 74, 9],
// [71, 5, 7, 20, 18, 9, 77, 74, 79],
// ],
// [
// [21, 5, 7, 80, 8, 9, 7, 74, 49],
// [31, 15, 7, 10, 18, 79, 7, 74, 19],
// [71, 5, 7, 20, 18, 79, 77, 74, 29],
// ],
// ]
// },
// ];
@override
Widget build(BuildContext context) {
var h = MediaQuery.of(context).size.height;
var w = MediaQuery.of(context).size.width;
if (apiResult == null) {
return Center(child: CircularProgressIndicator());
} else {
//Get an instance of Ticket from the API assigned to apiResponse variable
ticketList = Ticket.fromJson(json.decode(apiResult));
print('Tickets: ${ticketList.tickets}');
return Scaffold(
body: SafeArea(
child: Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
)),
child: ListView.builder(
itemCount: ticketList.tickets.length,
itemBuilder: (BuildContext context, index) {
List tripleNumbersList = [];
List<Widget> cells = [];
List<Widget> rows = [];
//Get the lists of lists inside the 'tickets' list
tripleNumbersList = ticketList.tickets[index];
//Iterates over each list with other 3 lists
for (int j = 0; j < tripleNumbersList.length; j++) {
//Get one of the 3 lists
List<int> list = tripleNumbersList[j];
//Iterates over the list of numbers
for (int k = 0; k < list.length; k++) {
//Adds a Widget to 'cells; list for each number
cells.add(Container(
height: 35,
width: 35,
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
),
//color: Colors.pink
),
child: GestureDetector(
onTap: () {
print('Working');
},
child: list[k] != 0
? Text(
' ${list[k]} ',
style: TextStyle(
fontSize: 18.0,
fontWeight: FontWeight.bold),
)
: Text(''),
)));
}
//Adds the list of 'cells' in the 'rows' list
rows.add(Row(children: cells));
cells = [];
}
//Adds a empty row to make space
rows.add(Row(children: [
Container(
height: 10,
)
]));
return Center(
child: Container(
height: h / 3,
decoration: BoxDecoration(
border: Border.all(
color: Colors.black,
),
//color: Colors.pink
),
child: Column(
//Adds the list of rows to the column
children: rows,
),
),
);
},
),
),
),
),
),
);
}
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: TicketPage(),
);
}
}
这篇关于无法从容器中的 API 显示数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!