How do I fetch API Data immediately after login in flutter?

1.4k views Asked by At

I am creating a flutter app with laravel back-end. When a user successfully logs in, they are given a token that they use to interact with the back-end. I am trying to fetch data immediately the home screen loads after login but I am receiving an authentication error saying unauthenticated. Below is the code to fetch the data.

Method to fetch the data

  Future<Package> fetchPackages() async {
final response = await http.get(
  Uri.parse(_url),
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': 'Bearer $token',
  },
);
print(token);
print(response.statusCode);
print(response.body);

if (response.statusCode == 201) {
  return Package.fromJson(jsonDecode(response.body));
} else {
  throw Exception('Failed to load packages');
}

}

late Future<Package> futurePackage;
@override
 void initState() {
// TODO: implement initState
super.initState();
getUserToken();
futurePackage = fetchPackages();

}

Future Builder

FutureBuilder(
                future: futurePackage,
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  if (snapshot.data == null) {
                    print(packages);
                    return Container(
                      child: Center(
                        child: CircularProgressIndicator(),
                      ),
                    );
                  } else {
                    return ListView.builder(
                      itemCount: snapshot.data.length,
                      itemBuilder: (BuildContext context, int id) {
                        return ListTile(
                          title: Text(snapshot.data.length),
                        );
                      },
                    );
                  }
                },
              ),

Immediately I log in, I receive a token that when fetching data return error code 401 but when I use the same token in postman it works well. I decided to add a button to the home screen ElevatedButton(onPressed: fetchPackages,child: Text("Fetch Packages"),), and when I press the button, data is fetched as it should be using the same token. How do I fetch the data on screen loading instead of using the button?

2

There are 2 answers

0
Ashwini Kumar On

You can just make your api call here

  @override
  void initState() {
    //api call here
  }

initState() is called only once and we use it for one time initializations.

0
Robert Sudec On

Future builder needs a method that returns a Future with a value. You have that method - > fetchPackages() , just reference that method in the builder (without parenthesis).

Also for handling futures and displaying a state. Use snapshot.connectionState for displaying a circular progress indicator. If snapshot.data IS null, that means the call was succesfull and the returned data really is null. Thats when you want to inform the user no information is available.

Sorry for unformatted text, writing on a smartphone.