向ListView中添加卡片

9

我正在尝试获取一组卡片,并尝试使用Expanded小部件,但出现了溢出错误。

我的代码:

new Expanded(
      child: StreamBuilder(
          stream: Firestore.instance.collection('baby').snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) return const Text('Loading...');
            return ListView.builder(
                itemCount: snapshot.data.documents.length,
                padding: const EdgeInsets.only(top: 10.0),
                itemExtent: 25.0,
                itemBuilder: (context, index) {
                  DocumentSnapshot ds = snapshot.data.documents[index];
                  return //Text(" ${ds['name']} ${ds['vote']}");
                    Card(
                      child: Expanded(
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            const ListTile(
                              leading: const Icon(Icons.album),
                              title: const Text('The Enchanted Nightingale'),
                              subtitle: const Text('Music by Julie Gable. Lyrics by Sidney Stein.'),
                            ),
                            new ButtonTheme.bar( // make buttons use the appropriate styles for cards
                              child: ButtonBar(
                                children: <Widget>[
                                   FlatButton(
                                    child: const Text('BUY TICKETS'),
                                    onPressed: () { /* ... */ },
                                  ),
                                   FlatButton(
                                    child: const Text('LISTEN'),
                                    onPressed: () { /* ... */ },
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                    ),
                    );
                });
          })),

我得到的错误是:Incorrect use of ParentDataWidget. 完整的错误信息:
执行热重载... I/flutter (9119): ══╡ WIDGETS LIBRARY 抛出的异常 ╞═══════════════════════════════════════════════════════════ I/flutter (9119): 在构建 DefaultTextStyle(debugLabel: (englishLike body1).merge(blackMountainView body1), inherit: false, color: Color(0xdd000000), family: Roboto, size: 14.0, weight: 400, baseline: alphabetic, decoration: TextDecoration.none, softWrap: wrapping at box width, overflow: clip) 时发生了以下断言: I/flutter (9119): 父数据组件使用不正确。 I/flutter (9119): Expanded widgets 必须直接放置在 Flex widgets 内部。 I/flutter (9119): Expanded(没有深度,flex: 1,dirty)有一个 Flex 祖先,但它们之间还有其他小部件: I/flutter (9119): - _InkFeatures-[GlobalKey#93e52 ink renderer] I/flutter (9119): - CustomPaint I/flutter (9119): - PhysicalShape(clipper: ShapeBorderClipper, elevation: 1.0, color: Color(0xffffffff), shadowColor: Color(0xff000000)) I/flutter (9119): - Padding(padding: EdgeInsets.all(4.0)) I/flutter (9119): - Semantics(container: true, properties: SemanticsProperties, label: null, value: null, hint: null) I/flutter (9119): - RepaintBoundary-[<0>] I/flutter (9119): - KeepAlive(keepAlive: false) I/flutter (9119): - SliverFixedExtentList(delegate: SliverChildBuilderDelegate#b334e(estimated child count: 3)) I/flutter (9119): - SliverPadding(padding: EdgeInsets(0.0, 10.0, 0.0, 0.0)) I/flutter (9119): - Viewport(axisDirection: down, anchor: 0.0, offset: ScrollPositionWithSingleContext#bebad(offset: 0.0, range: 0.0..0.0, viewport: 380.0, ScrollableState, AlwaysScrollableScrollPhysics -> ClampingScrollPhysics, IdleScrollActivity#7b3a8, ScrollDirection.idle)) I/flutter (9119): - IgnorePointer-[GlobalKey#4c7f9](ignoring: false, ignoringSemantics: false) I/flutter (9119): - Semantics(container: false, properties: SemanticsProperties, label: null, value: null, hint: null) I/flutter (9119): - Listener(listeners: [down], behavior: opaque) I/flutter (9119): - _GestureSemantics I/flutter (9119): - _ExcludableScrollSemantics-[GlobalKey#22165] I/flutter (9119): - RepaintBoundary I/flutter (9119): - CustomPaint I/flutter (9119): - RepaintBoundary I/flutter (9119): - Expanded(flex: 1)(这是与问题不同的其他 Expanded) I/flutter (9119): 这些小部件不能出现在 Expanded 和其 Flex 之间。 I/flutter (9119): 拥有父级的 Expanded 的所有权链是: I/flutter (9119): DefaultTextStyle ← AnimatedDefaultTextStyle ← _InkFeatures-[GlobalKey#93e52 ink renderer] ← NotificationListener ← CustomPaint ← _ShapeBorderPaint ← PhysicalShape I/flutter (9119): ← _MaterialInterior ← Material ← Padding ← ⋯ I/flutter (9119): I/flutter (9119): ══════════════════════════════════════════════════════════════════════════════════════════════════ I/flutter (9119): 另一个异常被抛出:父数据组件使用不正确。

更新
这是我得到的输出屏幕:

输入图像描述

如果我移除了Expanded,输出就变成了这样:

输入图像描述


我认为你不需要将其展开在那里。 - Bostrot
@Bostrot 没有展开的话就太糟糕了 :( - Hasan A Yousef
错误实际上是扩展小部件必须直接放置在弹性小部件内。 弹性小部件就像行、列、Flex等。 - Jacob Phillips
@JacobPhillips,我已经在我的问题中更新了屏幕上所看到的内容。 - Hasan A Yousef
2个回答

18

我找到了问题所在,原因是在ListView.builder使用itemExtent: 25.0,将其删除后,一切都可以默认扩展并且运行顺畅。

在寻找解决方案时,我遇到了这个网站这个答案以及这个网站,它们帮助我用更干净的代码重构了应用程序,下面是给有兴趣的人:

main.dart

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'BabyModel.dart';
import 'BabyCard.dart';

void main() => runApp(MyApp(
  textInput: Text("Text Widget"),
));

class MyApp extends StatefulWidget {
  final Widget textInput;
  MyApp({this.textInput});

  @override
  State<StatefulWidget> createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  bool checkBoxValue = false;

  @override
  Widget build(BuildContext ctxt) {
    return StreamBuilder(
      stream: Firestore.instance.collection('baby').snapshots(),
      builder: (_, AsyncSnapshot<QuerySnapshot> snapshot) {
        var documents = snapshot.data?.documents ?? [];
        var baby =
        documents.map((snapshot) => BabyData.from(snapshot)).toList();
        return BabyPage(baby);
      },
    );
  }
}

class BabyPage extends StatefulWidget {
  final List<BabyData> allBaby;

  BabyPage(this.allBaby);

  @override
  State<StatefulWidget> createState() {
    return BabyPageState();
  }
}


class BabyPageState extends State<BabyPage> {
  @override
  Widget build(BuildContext context) {

  //  var filteredBaby = widget.allFish.where((BabyData data) {
  //    data.name = 'Dana';
  //  }).toList();

    return MaterialApp(
        home: SafeArea(
        child: Scaffold(
        body: Container(
        child: ListView.builder(
            itemCount: widget.allBaby.length,
            padding: const EdgeInsets.only(top: 10.0),
            itemBuilder: (context, index) {
              return BabyCard(widget.allBaby[index]);
            })
      ),
    )));
  }
}

BabyModel.dart:

import 'package:cloud_firestore/cloud_firestore.dart';

class BabyData {
  final DocumentReference reference;
  String name;
  int vote;

  BabyData.data(this.reference,
      [this.name,
        this.vote]) {
    // Set these rather than using the default value because Firebase returns
    // null if the value is not specified.
    this.name ??= 'Frank';
    this.vote ??= 7;
  }

  factory BabyData.from(DocumentSnapshot document) => BabyData.data(
      document.reference,
      document.data['name'],
      document.data['vote']);

  void save() {
    reference.setData(toMap());
  }

  Map<String, dynamic> toMap() {
    return {
      'name': name,
      'vote': vote,
    };
  }
}

BabyCard.dart

import 'package:flutter/material.dart';
import 'BabyModel.dart';

class BabyCard extends StatefulWidget {
  final BabyData baby;

  BabyCard(this.baby);

  @override
  State<StatefulWidget> createState() {
    return BabyCardState(baby);
  }
}

class BabyCardState extends State<BabyCard> {
  BabyData baby;
  String renderUrl;

  BabyCardState(this.baby);

  Widget get babyCard {
    return
      new Card(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            ListTile(
              leading: const Icon(Icons.album),
              title: Text('The ${baby.name} is having:'),
              subtitle: Text('${baby.vote} Votes.'),
            ),
            new ButtonTheme.bar( // make buttons use the appropriate styles for cards
              child: new ButtonBar(
                children: <Widget>[
                  new FlatButton(
                    child: const Text('Thumb up'),
                    onPressed: () { /* ... */ },
                  ),
                  new FlatButton(
                    child: const Text('Thumb down'),
                    onPressed: () { /* ... */ },
                  )]))]));
  }

  @override
  Widget build(BuildContext context) {
    return new Container(
          child:  babyCard,
        );
  }
}

输出结果如下:

在此输入图片描述


1
@CrsCaballero 我使用的所有代码都出现在上面。 - Hasan A Yousef

0

你能在问题中放置移动屏幕的截图吗?

我使用了你的代码,没有使用扩展小部件,一切都很完美,你想要改变什么?

Print mobile


我更新了我的问题,并附上了屏幕上所见的内容。你是否将你的应用连接到 Firebase? - Hasan A Yousef

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接