我正在try 获取Cards个列表,并try 使用Expanded小部件,但得到overflow个错误

我的代码:

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.

完全错误:

Performing hot reload... I/flutter ( 9119): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ I/flutter ( 9119): The following assertion was thrown building DefaultTextStyle(debugLabel: (englishLike I/flutter ( 9119): body1).merge(blackMountainView body1), inherit: false, color: Color(0xdd000000), family: Roboto, I/flutter ( 9119): size: 14.0, weight: 400, baseline: alphabetic, decoration: TextDecoration.none, softWrap: wrapping I/flutter ( 9119): at box width, overflow: clip): I/flutter ( 9119): Incorrect use of ParentDataWidget. I/flutter ( 9119): Expanded widgets must be placed directly inside Flex widgets. I/flutter ( 9119): Expanded(no depth, flex: 1, dirty) has a Flex ancestor, but there are other widgets between them: 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: I/flutter ( 9119): 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: I/flutter ( 9119): 0.0, range: 0.0..0.0, viewport: 380.0, ScrollableState, AlwaysScrollableScrollPhysics -> I/flutter ( 9119): 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) (this is a different Expanded than the one with the problem) I/flutter ( 9119): These widgets cannot come between a Expanded and its Flex. I/flutter ( 9119): The ownership chain for the parent of the offending Expanded was: I/flutter ( 9119): DefaultTextStyle ← AnimatedDefaultTextStyle ← _InkFeatures-[GlobalKey#93e52 ink renderer] ← I/flutter ( 9119): NotificationListener ← CustomPaint ← _ShapeBorderPaint ← PhysicalShape I/flutter ( 9119): ← _MaterialInterior ← Material ← Padding ← ⋯ I/flutter ( 9119): ════════════════════════════════════════════════════════════════════════════════════════════════════ I/flutter ( 9119): Another exception was thrown: Incorrect use of ParentDataWidget. I/chatty ( 9119): uid=10096(com.example.flutterapp) Thread-3 identical 3 lines I/flutter ( 9119): Another exception was thrown: Incorrect use of ParentDataWidget.

UPDATE
下面是我得到的输出屏幕:

enter image description here

如果我go 掉Expanded,输出会变成这样:

enter image description here

推荐答案

我明白了,整个问题是在ListView.builder使用itemExtent: 25.0,时go 掉它,默认情况下一切都是可扩展的,并且运行得很流畅.

在寻找解决方案的过程中,我遇到了thisthisthis,它们帮助我用更干净的代码重新构建了这款应用,下面是针对感兴趣的人的代码:

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,
        );
  }
}

结果是:

enter image description here

Dart相关问答推荐

Flutter - 对 Cloud Firestore 进行排序

带有字符串键的 Dart Map,与忽略大小写进行比较

在`lib`文件夹中使用`src`子文件夹有什么好处吗

运行时出现Flutter错误:Error waiting for a debug connection: Bad state: No element

如何从 Flutter App 连接 Ms SQL?

在 Dart 中,List.unmodifiable() 和 UnmodifiableListView 有什么不同?

如何用 Flutter 在同屏路由上制作英雄风格的动画?

结合freezed和hive

无法将小部件标记为需要构建,因为框架已经在构建小部件的过程中

如何在Flutter中返回异步函数的值?

如何在flatter中使用SQFlite更新数据库表

使用Flutter/dart的NTLM身份验证

如何使用工厂构造函数扩展抽象类?

在 Dart 中将类类型作为变量传递

Dart 中的构造函数和初始化列表有什么区别?

是什么使它成为 Dart 中的固定长度列表?

可以在 Dart 中的抽象类中声明静态方法吗?

Dart 的Expando功能是什么,它有什么作用?

在 Dart 中,List.from 和 .of 以及 Map.from 和 .of 有什么区别?

dart中的动态和对象有什么区别?