flutterdartflutter-http

Flutter http request get null


I'm new to flutter and dart. While learning about get on http request I encounter some error. These are my code

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as ziraHttp;
class getHttp extends StatefulWidget {
  const getHttp({super.key});
  @override
  State<getHttp> createState() => _getHttpState();
}
class _getHttpState extends State<getHttp> {
  late String id;
  late String email;
  late String name;
  @override
  void initState() {
    id = '';
    email = '';
    name = '';
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Get Tutorial"),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              "ID:$id ",
              style: TextStyle(fontSize: 20),
            ),
            Text(
              "email:$email ",
              style: TextStyle(fontSize: 20),
            ),
            Text(
              "Name:$name ",
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(
              height: 12,
            ),
            ElevatedButton(
connection )
                onPressed: () async {
                  var serverResponse = await ziraHttp
                      .get(Uri.parse('https://reqres.in/api/users/2'));
                  if (serverResponse.statusCode == 200) {
                    Map<String, dynamic> dataResp =
                        json.decode(serverResponse.body);
                    setState(() {
                      id = dataResp["id"].toString();
                      email = dataResp["email"].toString();
                      name =
                          "${dataResp["first_name"]} ${dataResp["last_name"]}";
                    });
                  } else {
                    print("ERROR CODE: ${serverResponse.statusCode}");
                  }
                },
                child: Text("Get Data"))
          ],
        ),
      ),
    );
  }
}

when I click the button null shows up instead of the data enter image description here

I might did some error since I'm new to this language, and this is my first time posting here. Thanks in advance!


Solution

  • You just need to add dataResp = dataResp['data']; before

    `setState(() {
                 id = dataResp["id"].toString();
                 email = dataResp["email"].toString();
                 name ="${dataResp["first_name"]} ${dataResp["last_name"]}";
                        });`
    

    because the values are saved inside the 'data' key in https://reqres.in/api/users/2 response