menu

Questions & Answers

length() is giving errors

hey guys i have some error in this code whin i open this page it show this error

this error

i know becuse the table there is no data in the table but i want to escape this error how i do it?

i tried everything in the code but nothing work i tried to put inNotEmpty but when i tried to add data in the table still nothing show this is my code:

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

class sections_KSU extends StatefulWidget {
  @override
  State<sections_KSU> createState() => _sections_KSUState();
}
List<String> disciplines = [
  'الهندسة',
  'العلوم الطبيعية',
  'العلوم الاجتماعية',
  'العلوم الإنسانية',
  'العلوم الإدارية',
  'التربية',
  'الطب والعلوم الصحية',
  'القانون',
  'الفن والتصميم',
  'الزراعة والدراسات البيئية',
];
List list = [];
class _sections_KSUState extends State<sections_KSU> {
  get controller => null;

  var pr1;
   Future ReadData() async {
    var url = "https://***.***.***.**/getksu.php";
    var res = await http.get(Uri.parse(url));

    if (res.statusCode == 200) {
      var red = jsonDecode(res.body);

      setState(() {
        list = red;
      });
    } else {
      Text("No ads right now");
    }
  }
  @override
  void initState() {
    super.initState();

    GetData();
  }

  GetData() async {
    await ReadData();
  }
  Widget build(BuildContext context) {
    return Scaffold(
      body:SafeArea(
        child: Column(
          children: [
      
            Container(
              margin: EdgeInsets.only(left: 70, right: 60),
              height: 56.0,
              width: 245.0,
              child: Container(
                  decoration: BoxDecoration(
                      border: Border.all(color: Color(0xffF4AC47), width: 5),
                      color: Color(0xff42A9D2),
                      borderRadius: BorderRadius.only(
                          bottomLeft: Radius.circular(40),
                          bottomRight: Radius.circular(40))),
                  child: new Center(
                    child: new Text(
                      "جامعة الملك سعود",
                      style: TextStyle(
                          fontSize: 25,
                          color: Color(0xff072A52),
                          fontFamily: 'Cairo'),
                      textAlign: TextAlign.center,
                    ),
                    ///end logo
                  )),
            ),
            SizedBox(
              height: 35,
            ),
            ///Search
            Container(
                width: 390,
                height: 69,
                decoration: BoxDecoration(
                    border: Border.all(color: Color(0xff072A52), width: 5),
                    borderRadius: BorderRadius.only(
                        bottomLeft: Radius.circular(15),
                        bottomRight: Radius.circular(15),
                        topLeft: Radius.circular(15),
                        topRight: Radius.circular(15))),
                child: Column(
                  children: [
                    Container(
                      child: (TextField(
                        controller: controller,
                        decoration: InputDecoration(
                            prefixIcon: const Icon(Icons.search),
                            hintText: 'Search',
                            border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(5))),
                      )),
                    ),
                  ],
                )),
            ///search end
            SizedBox(
              height: 10,
            ),
            /// icon filter
            Row(
              children: [
                TextButton(onPressed: (){dd();}, child:dd())
              ],
            ),
            /// icon filter end
            ///start Section
            /// 
            Expanded( 
              child:  ListView.builder(
                itemCount:list.length,
                itemBuilder: ((cts, i) {
                  return Column(
                    children: [
                      Container(
                        margin: const EdgeInsets.symmetric(horizontal: 10),
                        height: 160.0,
                        child: Container(
                          decoration: BoxDecoration(
                              border: Border.all(
                                  color:  Colors.blueGrey, width:2),
                              borderRadius: BorderRadius.circular(8)),
                          child:TextButton(///
                            onPressed: (){},
                            child:Container(
                              child: Column(
                                children: [
                                  Row(
                                    children: [
                                      const Expanded(
                                        flex: 3,
                                        child: Image(
                                          image: AssetImage("assets/book.jpg"),height:130,
                                        ),
                                      ),
                                      Expanded(
                                        flex: 9,
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.end,
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: [
                                            Text(
                                              "${list[i]["book_name"]}",
                                              style: TextStyle(
                                                  fontSize: 25, color: Colors.green),
                                            ),
                                            const SizedBox(height: 65),
                                            Row(
                                              mainAxisAlignment: MainAxisAlignment.end,
                                              children: [
                                                Text("${list[i]["collage"]}",style:TextStyle(fontSize:16)),SizedBox(width:10,),
                                                const Icon(Icons.perm_identity_rounded,color:Colors.teal,),
                                                SizedBox(width:60,),
                                                Text("${list[i]["loc"]}",style:TextStyle(fontSize:15),),SizedBox(width:10,),
                                                const Icon(Icons.person_pin_circle,color:Colors.teal,),SizedBox(width: 10,)
                                              ],
                                            ),
                                          ],
                                        ),
                                      )
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          )
                        ),
                      ),
                      const SizedBox(height: 26),
                    ],
                  );
                }),
              ),
            ),
      
          ],
        ),
      )
    );
  }
}



///flter


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

  @override
  State<dd> createState() => _ddState();
}

class _ddState extends State<dd> {
  List<String> disciplines = [
    'الهندسة',
    'العلوم الطبيعية',
    'العلوم الاجتماعية',
    'العلوم الإنسانية',
    'العلوم الإدارية',
    'التربية',
    'الطب والعلوم الصحية',
    'القانون',
    'الفن والتصميم',
    'الزراعة والدراسات البيئية',
  ];

  get TitleName => "التخصصات";
///يطبع التخصص المختار
  set UnaverNAME(String UnaverNAME) {print(UnaverNAME);}

  set selectItem(String selectItem) {}

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: 168,height:60,
      child: Padding(
        padding: const EdgeInsets.only(left:8),
        child: Center(
          child: DropdownButtonFormField<String>(
            decoration: InputDecoration(
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(40),
                  borderSide: BorderSide(color: Color(0xff072A52), width: 2),
                ),
                enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(40),
                    borderSide: BorderSide(width: 2, color: Color(0xff072A52)))),
            hint: Center(
                child: Text(
                  "       $TitleName",
                  // "   اسم الجامعة",
                  style: TextStyle(
                      fontWeight: FontWeight.w800,
                      fontSize: 16,
                      color: Color.fromRGBO(244, 172, 71, 1)),

                )),
            // value: selectItem,
            items: disciplines
                .map((item) => DropdownMenuItem(
                value: item,
                child: Text(item,
                    style: TextStyle(
                        fontSize: 12,
                        color: Color.fromRGBO(244, 172, 71, 1),
                        fontWeight: FontWeight.w900))))
                .toList(),
            onChanged: (value) {
              setState(() {
                selectItem = value!;
                UnaverNAME = value;
              });
            },
          ),
        ),
      ),
    );
  }
}

and this is my php code:

<?php
include("config.php");

$sql = "SELECT book_name,loc,com,spe,collage FROM ads where collage = 'جامعة الملك سعود' ";
$res = $connect->query($sql);


if ($res >= 1) {
    while($row = $res -> fetch_assoc()) {
        $data[]=$row;
    }
    echo json_encode($data);
} else {
    echo json_encode("sorry this is no ads know");
}




$mysqli_connect-> close();
?>
Comments:
2023-01-19 23:01:05
Your PHP code produces ambiguous output. Sometimes it produces an array, other times it produces a string. Stick to a single data type. Let it always return an array, an empty array if it cannot find any data in the database. Return the error in the HTTP status code (http_response_code(404);).
2023-01-19 23:01:05
Assuming that the type of $connect is mysqli (it is not clear from your code), the value returned by $connect->query() is either an object of type mysqli_result() or false. Comparing any of these with 1 is not the right way to check it. Use if ($res !== false). When $res is false there is a problem with your query and the PHP script should return 500 Server Error, not 200 OK.
Answers(1) :

I believe its coming from this line: itemCount:list.length,

And its because at this point of the code your list is null. It doesn't have any data.

I think you need to swap these around:

List list = [];
List<String> disciplines = [
  'الهندسة',
  'العلوم الطبيعية',
  'العلوم الاجتماعية',
  'العلوم الإنسانية',
  'العلوم الإدارية',
  'التربية',
  'الطب والعلوم الصحية',
  'القانون',
  'الفن والتصميم',
  'الزراعة والدراسات البيئية',
];

It looks like you are defining list then you are instantly setting it to a blank array.

If you call .length on a blank array it will throw this error you are getting.