Murali Krishnan
Murali Krishnan

Reputation: 312

Flutter Null Safety Error in snapshot.data.length

I'm getting this error when I changed my project from without null safety to null safety. The error I got is:

"The property 'length' can't be unconditionally accessed because the receiver can be 'null'.Try making the access conditional (using '?.') or adding a null check to the target ('!')"

in the line itemCount: snapshot.data.length, so I changed the line to itemCount: snapshot.data!.length. Now I'm getting the error

The getter 'length' isn't defined for the type 'Object'. Try importing the library that defines 'length', correcting the name to the name of an existing getter, or defining a getter or field named 'length'.

My code is this:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:movie_app/constants/myUrl.dart';

class SearchPost extends SearchDelegate<String?> {
  List<dynamic>? list;
  SearchPost({this.list});

  Future showAllPost() async {
    var url = "$baseUrl/searchPost.php";
    var response = await http.post(
      Uri.parse(url),
      body: {'title': query},
    );
    if (response.statusCode == 200) {
      var jsonData = json.decode(response.body);
      print(jsonData);
      return jsonData;
    }
  }

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        onPressed: () {
          query = "";
          showSuggestions(context);
        },
        icon: Icon(
          Icons.close,
        ),
      ),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: Icon(Icons.arrow_back),
      onPressed: () {
        close(context, null);
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    return FutureBuilder(
      future: showAllPost(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return ListView.builder(
          itemCount: snapshot.data!.length,
          itemBuilder: (context, index) {
          var list = snapshot.data[index];
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.all(8.0),
                    child: Text(
                      list['title'],
                      style: TextStyle(
                        fontSize: 22,
                        fontFamily: 'Nasalization',
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  Center(
                    child: Container(
                      child: Image.network(
                        '$baseUrl/uploads/${list['image']}',
                        height: 250,
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.all(8),
                    child: Text(
                      list['body'] == null ? "" : list['body'],
                      style: TextStyle(
                        fontSize: 20,
                      ),
                    ),
                  ),
                  Row(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.all(8),
                        child: Text(
                          "by " + list['author'],
                          style: TextStyle(
                            fontSize: 16,
                            color: Colors.grey,
                          ),
                        ),
                      ),
                      SizedBox(
                        width: 5,
                      ),
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          "Posted on : " + list['post_date'],
                          style: TextStyle(
                            fontSize: 16,
                            color: Colors.grey,
                          ),
                        ),
                      ),
                    ],
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                      "Comments Area",
                      style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                          fontFamily: 'Nasalization'),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: TextField(
                      decoration: InputDecoration(
                        labelText: "Enter Comments",
                      ),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Center(
                      child: MaterialButton(
                        color: Colors.blue,
                        child: Text("Publish"),
                        onPressed: () {
                          //Code to publish comment
                        },
                      ),
                    ),
                  ),
                ],
              );
            },
          );
        }
        return CircularProgressIndicator();
      },
    );
  }

The response from the jsonData is this:

[{id: 18, title: Movie Title, body: Movie Body, author: Murali, post_date: 28/09/2021 08:46, category_name: Movies, image: image_picker4111148115016181882.jpg, create_date: 27/09/2021, comments: 4, total_like: 4, movie_url: https://www.testmovie.com/movie.mp4}]

This works fine in the project without null safety. How to solve this error?

Upvotes: 0

Views: 1101

Answers (1)

Bigfoot
Bigfoot

Reputation: 357

try replacing snapshot.data!.length with this snapshot.data?.length ??0 it should work

Upvotes: 1

Related Questions