there is something wrong with my code, i have a function with an http request to retrieve datas of my users and display it, but each time i call it i have a pause on my app, and this message :Sends an HTTP POST request with the given headers and body to the given URL.
[body] sets the body of the request. It can be a [String], a [List] or a [Map<String, String>]. If it’s a String, it’s encoded using [encoding] and used as the body of the request. The content-type of the request will default to "text/plain".If [body] is a List, it’s used as a list of bytes for the body of the request.
But i use similar function somewhere else in my code and it works well, i don’t know is going on
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
class Navbar extends StatefulWidget {
const Navbar({
super.key,
required this.mail,
required this.password,
});
final String mail;
final String password;
@override
State<Navbar> createState() => _NavbarState();
}
class _NavbarState extends State<Navbar> {
String left = '';
String amail = "";
String apseudo = "";
//login() is the function that paused the app anytime i call it
Future<void> login() async {
var url = Uri.parse('https://konamicash.com/solde_app');
var response = await http.post(url, headers: {
"Accept": "application/json",
"Access-Control-Allow-Origin": "*"
}, body: {
"adresse_mail": '[email protected]',
});
var reponse = jsonDecode(response.body);
print(reponse);
setState(() {
left = reponse['account'];
apseudo = reponse['pseudo'];
amail = reponse['mail'];
});
}
@override
Widget build(BuildContext context) {
login();
return Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: [
UserAccountsDrawerHeader(
accountName: Text(apseudo),
accountEmail: Text(amail),
currentAccountPicture: CircleAvatar(
child:
ClipOval(child: Image.asset("assets/images/capture-arene.png")),
),
decoration: const BoxDecoration(
color: Colors.redAccent,
// image: DecorationImage(
// image: AssetImage('assets/images/capture-arene.png'),
// fit: BoxFit.cover)
),
//currentAccountPicture: , cicle)
),
],
),
);
2
Answers
You should call login function inside initState.
use on of the two solutions:
1-Use Future builder
use the future builder widget, which allows you to call a future function and change the content based on the future status or result.
2- Or use initState, which runs once you build the widget (not recommended for such things like futures.)