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);
?>
