flutter LateError (LateInitializationError: Field 'user Data' has not been initialized.)

Viewed 168

Below is the code I wrote to extract data from MySQL database with flutter rest API. However, I am getting the following error while printing the data I received to the mobile screen. How can I fix it?

LateError (LateInitializationError: Field 'user Data' has not been initialized.)

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material App',
      home: main1(),
    );
  }
}

class main1 extends StatefulWidget {
  main1({Key? key}) : super(key: key);

  @override
  State<main1> createState() => _main1State();
}

class _main1State extends State<main1> {
  late List userData;
  late Map data;
  @override
  void initState() {
    // TODO: implement initState
    loaddata();

    super.initState();
  }

  void loaddata() async {
    var url = "http://192.168.1.106/server/data.php";
    var res = await http.get(Uri.parse(url));
    data = json.decode(res.body);
    userData = data["data"];
    print(userData);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Fake Friends"),
        backgroundColor: Colors.green,
      ),
      body: ListView.builder(
          itemCount: userData == null ? 0 : userData.length,
          itemBuilder: (BuildContext context, int index) {
            return Container(
              child: Text(userData[index]["projename"]),
            );
          }),
    );
  }
}


<?php
require_once("dbconfig.php");
$json["error"] = false;
$json["errmsg"] = "";
$json["data"] = array();
//Fetch 3 rows from actor table
$sql = "SELECT * FROM projeinfo";
$res = mysqli_query($db, $sql);
$numrows = mysqli_num_rows($res);
if($numrows > 0){
   //check if there is any data
   $namelist = array();

   while($array = mysqli_fetch_assoc($res)){
       array_push($json["data"], $array);
       //push fetched array to $json["data"] 
   }
}else{
    $json["error"] = true;
    $json["errmsg"] = "No any data to show.";
}

mysqli_close($db);

header('Content-Type: application/json');
// tell browser that its a json data
echo json_encode($json);
?>

enter image description here

1 Answers

If you set a variable to late it cannot be null. So in your build function it assumes, that it is initialized, but it isn't, because load data is a future and the result is ready after the build function gets called first.

2 possible ways.

1.

  List? userData;
  Map? data;
  1. Use a FutureBuilder

And: You don't call setState in your loadData(), so it does not get rebuild if the data is available. For the first approach, this is necessary!

Related