Jeremi
Jeremi

Reputation: 1474

Flutter - How to implement scrollable ListView inside a row

Adding a horizontal ListView inside a row throws this exception:

════════ Exception caught by rendering library ═════════════════════════════════ 'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 545 pos 12: 'child.hasSize': is not true. The relevant error-causing widget was ListView lib/…/pages/home_page.dart:68

How can you have a label on the left side, and horizontally scrollable widgets on the right side of the label?

This is my current code:

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Testing"),
        ),
        body: Row(
          children: [
            Text(
              "All Bookings",
              style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.w600,
                  color: Colors.brown[700]),
            ),
            Expanded(
              child: Container(
                margin: EdgeInsets.only(top: 24),
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: 30,
                  itemBuilder: (BuildContext context, int index) => ListTile(
                    title: Text("List Item ${index + 1}"),
                  ),
                ),
              ),
            ),
          ],
        ),
    );
  }

Upvotes: 0

Views: 132

Answers (1)

Stewie Griffin
Stewie Griffin

Reputation: 5608

ListTile is a row that expands to fill the available horizontal space. If you try to use it inside an horizontal list which is indefinite, it throws an error because it doesn't know how much it will expand. So, you should define its width using a Container or SizedBox:

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text("Testing"),
    ),
    body: Row(
      children: [
        Text(
          "All Bookings",
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.w600,
            color: Colors.brown[700]),
        ),
        Expanded(
          child: Container(
            margin: EdgeInsets.only(top: 24),
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: 30,
              itemBuilder: (BuildContext context, int index) => Container(
                width: 100,
                child: ListTile(
                  title: Text("List Item ${index + 1}"),
                ),
              ),
            ),
          ),
        ),
      ],
    ),
  );
}

Upvotes: 1

Related Questions