Home > Enterprise >  LateInitializationError: Field 'check' has not been initialized
LateInitializationError: Field 'check' has not been initialized

Time:11-12

I'm trying to Use data that I fetched from database and i got an error : "LateInitializationError: Field 'check' has not been initialized. " , i tried to remove the late word and adding " ? " and it gives another error "Expected a value of type 'num', but got one of type 'Null' "


class _letterssState extends State<letterss> {
  late var check;
  Future getData() async{
    var url = 'http://ip/getSpell.php';
    http.Response response = await http.get(Uri.parse(url));
    var data = jsonDecode(response.body);
    check=data;
    print(data.toString());

  }
  bool searchRes  (String s){
    int x=0;
    for ( var i=0 ; i<check.length;i   )
    {
      if (check[i]['letter']==s){
        x=i;
      }
    }
    if (check[x]['result']=='true')
    {
      return true;
    }
    else
    {
      return true;
    }
  }

  initState()
  {
    getData();
  }

CodePudding user response:

It will take some frame to get data from getData future method and assigning on check.

It would better to use FutureBuilder for future methods. Follow this doc example

 Future<List<yourDataType>?> getData() async {
    var url = 'http://ip/getSpell.php';
    http.Response response = await http.get(Uri.parse(url));
    var data = jsonDecode(response.body);
    return data;
  }
  late final future = getData();
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<YourDataType>?>(
      future: future,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          //todo:
        }
        return CircularProgressIndicator();
      },
    );
  }
  • Related