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

Time:01-02

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?

CodePudding user response:

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.

CodePudding user response:

you can read about fetching data via API in flutter here :

https://docs.flutter.dev/cookbook/networking/fetch-data

  • Related