卡的颤振布局问题

时间:2021-01-31 14:12:02

标签: flutter listview dart

为什么用 Card 替换 Text 会报错?

return Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                        child: ListView.builder(
                      shrinkWrap: true,
                      scrollDirection: Axis.horizontal,
                      itemCount: snapshot.data.entity.workforce.length,
                      itemBuilder: (context, index) {
                        var item = snapshot.data.entity.workforce[index];
                        return Text(item['work_force_name']);
                      },
                    ))
                  ]);

以上代码有效。但是,如果我将 Text 更改为 Card,则会出现错误

  return Card(
        elevation: 2,
        child: ListTile(
        dense: true,
        title: Text(item['work_force_name'].toString()),
        subtitle: Text(item['no_work_force'].toString()),
     ));

错误

RenderBox was not laid out: RenderRepaintBoundary#88567 relayoutBoundary=up15 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1785 pos 12: 'hasSize'
The relevant error-causing widget was
    ListView 
lib/ui/edit_status_esite_diary.dart:74
════════════════════════════════════════════════════════════════════════════════

════════ 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/ui/edit_status_esite_diary.dart:74
════════════════════════════════════════════════════════════════════════════════
Reloaded 194 of 1766 libraries in 10,279ms.

1 个答案:

答案 0 :(得分:0)

由于您使用的是水平 ListView(无宽度限制)并且 Card 默认采用最大宽度,因此您应该限制 widthCard .

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        body: MyWidget(),
      ),
    ),
  );
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final List<Map<String, String>> items = List.generate(10, (index) {
      return {
        'work_force_name': 'Work Force $index',
        'no_work_force': 'x00000$index',
      };
    }).toList();
    return SizedBox(
      height: 100,
      child: ListView.builder(
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
        itemCount: items.length,
        itemBuilder: (context, index) {
          var item = items[index];
          return SizedBox(
            width: 150,
            child: Card(
              elevation: 2,
              child: ListTile(
                dense: true,
                title: Text(item['work_force_name'].toString()),
                subtitle: Text(item['no_work_force'].toString()),
              ),
            ),
          );
        },
      ),
    );
  }
}