Home > Software design >  Listview builder is constantly giving me null
Listview builder is constantly giving me null

Time:11-07

I have this:

class HonPage extends StatefulWidget {
  final Status? status;

  HonPage({Key? key, this.status}) : super(key: key);

  @override
  _HonPageState createState() {
    return _HonPageState();
  }
}

class _HonPageState extends State<HonPage> {

  @override
  void initState() {
    super.initState();
  }


  Widget build(BuildContext context) {
    return new ListView.builder(
        itemCount: 10,
        itemBuilder: (context, index) {
          return new ListTile(
            title: new Text("${widget.status.title ?? ""}"),
          );
        }
    );
  }
}

My result:

NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL

Whatever I do, I seem not to be able to fetch the items from JSON.

The JSON and API URL works on all other screens, so that can not be wrong. What am I doing wrong here? It's just that I have created a new tab and want to show the information.

Edit: In Status.dart, I have this:

Status(Map<String, dynamic> json) : super(json) {
    status = json["status"];
    title = json["title"];
    ....
}

JSON:

[{"title": "NAME ME", "status": "publish"}]

CodePudding user response:

You should use FutureBuilder when building a ListView to show results from an API call:

Widget _buildBody(BuildContext context) {
  return FutureBuilder<List<Status>>(
    future: fetchStatus(), // async API call that returns List<Status>
    builder: (BuildContext context, AsyncSnapshot snapshot) {
      if (snapshot.hasError) {
        return const Text("some error");
      }
      if (snapshot.connectionState != ConnectionState.done) {
        return const Center(child: CircularProgressIndicator());
      }
      if (!snapshot.hasData) {
        return const Text("some error");
      }
      final list = snapshot.data as List<Status>;
      return ListView.builder(
        itemCount: list.length,
        itemBuilder: (BuildContext context, int index) {
          return ListTile(
            title: Text('${list[index].title ?? ""}'),
          );
        },
      );
    },
  );
}

Updated:

You have to create the following class:

class Status {
  final String title;
  final String status;

  const Status({
    this.title = '',
    this.status = '',
  });

  factory Status.fromJson(Map<String, dynamic> json) => Status(
      title: json['title'] as String? ?? '',
      status: json['status'] as String? ?? '',
    );

  Map<String, dynamic> toJson() => <String, dynamic>{
      'title': title,
      'status': status,
    };
}

You have to write the method fetchStatus to call the API and return List<Status>.

Updated 2

return ListTile(
  title: Text('${places[index].title ?? ""}'),
  onTap: () {
    Navigator.pushNamed(
      context,
      '/detail_page',
      arguments: places[index],
    );
  },
);
  • Related