Home > OS >  Flutter - Why is Future returning "Instance of Future<String>" and not the data from
Flutter - Why is Future returning "Instance of Future<String>" and not the data from

Time:06-21

Here is the Future function that should return the data in my php file

    Future displayLg_name() async {
        var url = Uri.http(
            "192.168.68.216", '/ump_attendance_2/username.php', {'q': '{http}'});
        var response = await http.post(url, body: {
          "lg_username": username.lg_username,
        });
        if (response.body.isNotEmpty){
          return (json.decode(response.body));
        };

I'm trying to display it in my container

   Container(
          alignment: Alignment.centerLeft,
          child: Text(
            displayLg_name().toString(),
            style: TextStyle(
              color: Colors.black54,
              fontFamily: "Ubuntu",
              fontWeight: FontWeight.bold,
              fontSize: scrwidth / 18,
            ),
          ),
        ),

And here is my php file

            <?php
            include ("config.php");
            session_start();
            $lg_username = $_REQUEST['lg_username'];

            $sql = "SELECT lg_name FROM hr_login WHERE lg_username = '$lg_username'";

            $res = mysqli_query($conn,$sql);

            if (mysqli_num_rows($res)>0){
                while($row = mysqli_fetch_assoc($res)){
                    echo json_encode($row['lg_name']);
                }
            }
            ?>

I'm guessing there's nothing wrong with my php file but somewhere in flutter .dart

Thanks in advance

CodePudding user response:

Try to do something like this instead:

var text = await displayLg_name();
/* ... */
Container(
  alignment: Alignment.centerLeft,
  child: Text(
    text ?? '',
    style: TextStyle(
      color: Colors.black54,
      fontFamily: "Ubuntu",
      fontWeight: FontWeight.bold,
      fontSize: scrwidth / 18,
    ),
  ),
), 

Edited
If your class is statefull, you can declare it inside initState() like this:

var text;

void _init() async {
  await displayLg_name().then((value) => setState(() => text = value));
}

@override
void initState() {
  super.initState();
  _init();
}
  • Related