I'm trying to call HTTP API to show the information of products on the Pageview.builder but it gets the error The following NoSuchMethodError was thrown building: '[]' Dynamic call of null. Receiver: null Arguments: ["data"], I've tried many ways to solve it but it still get an error and can't display the data of HTTP API on app screen Anyone can solve it, many thanks!
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<Information> postList = [];
int currentIndex = 0;
late PageController _controller;
@override
void initState() {
_controller = PageController(initialPage: 0);
super.initState();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
var data;
Future<void> getData() async {
final response = await http
.get(Uri.parse('https://berequirement.herokuapp.com/products'));
if (response.statusCode == 200) {
data = jsonDecode(response.body.toString());
} else {}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
Expanded(
child: Container(
height: 500,
width: 300,
child: FutureBuilder(
future: getData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: Text('Loading ...'));
} else {
return PageView.builder(
controller: _controller,
itemCount: data.length,
onPageChanged: (int index) {
setState(() {
currentIndex = index;
});
},
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(40),
child: Column(
children: [
Text(
data[index]['data']['name'],
style: GoogleFonts.poppins(
fontWeight: FontWeight.bold,
fontSize: 22,
),
),
const SizedBox(height: 20),
Text(
data[index]['data']['code'],
textAlign: TextAlign.center,
style: GoogleFonts.poppins(
fontWeight: FontWeight.bold,
fontSize: 14,
color: Colors.grey),
)
],
));
},
);
}
}),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List.generate(
postList.length,
(index) => buildDot(index, context),
),
),
])}
CodePudding user response:
The problem might be located around here:
Text(
data[index]['data']['name'],
...
)
I've tried sending a GET request to your URL and the following was given:
{
"success": true,
"message": "Products found",
"data": [
{
"name": "Shadow Witch",
...
},
{
"name": "Sadness Mummy",
...
},
{
"name": "Candy Witch",
...
}
]
}
Given this, your Text()
doesn't have the correct parameters. It should look like this:
Text(
data['data'][index]['name'],
...
)
Also, this might be redundant, but in your getData()
you don't need to call the toString()
method on response.body
:
...
if (response.statusCode == 200) {
data = jsonDecode(response.body);
} else {}
...