将卡添加到ListView

时间:2018-06-23 14:25:17

标签: dart flutter

我正在尝试获取Cards的列表,并尝试使用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.

完整错误:

  

执行热重装...   I / flutter(9119):W小工具库引起的异常CA ═════════════════════════   I / flutter(9119):构建DefaultTextStyle(debugLabel:(englishLike   I / flutter(9119):body1).merge(blackMountainView body1),继承:false,颜色:Color(0xdd000000),家庭:Roboto,   I / flutter(9119):大小:14.0,重量:400,基线:字母,装饰:TextDecoration.none,softWrap:包装   I /颤振(9119):在盒子宽度处,溢出:剪辑):   I / flutter(9119):不正确使用ParentDataWidget。   I / flutter(9119):扩展的窗口小部件必须直接放在Flex窗口小部件内。   I / flutter(9119):Expanded(无深度,flex:1,脏)具有Flex祖先,但它们之间还有其他小部件:   I / Flutter(9119):-_InkFeatures- [GlobalKey#93e52墨水渲染器]   I / Flutter(9119):-CustomPaint   I / flutter(9119):-PhysicalShape(clipper:ShapeBorderClipper,高程:1.0,颜色:Color(0xffffffff),shadowColor:   I /颤振(9119):颜色(0xff000000))   I / Flutter(9119):-填充(padding:EdgeInsets.all(4.0))   I / flutter(9119):-语义(容器:true,属性:SemanticsProperties,标签:空,值:空,提示:空)   I / flutter(9119):-RepaintBoundary-[<0>]   I / flutter(9119):-KeepAlive(keepAlive:false)   I / flutter(9119):-SliverFixedExtentList(委托:SliverChildBuilderDelegate#b334e(估计子计数:3))   I / Flutter(9119):-SliverPadding(填充:EdgeInsets(0.0,10.0,0.0,0.0))   I / flutter(9119):-视口(axisDirection:向下,锚点:0.0,偏移量:ScrollPositionWithSingleContext#bebad(偏移量:   I / flutter(9119):0.0,范围:0.0..0.0,视口:380.0,ScrollableState,AlwaysScrollableScrollPhysics->   I / flutter(9119):ClampingScrollPhysics,IdleScrollActivity#7b3a8,ScrollDirection.idle))   I / flutter(9119):-IgnorePointer- [GlobalKey#4c7f9](忽略:false,忽略语义:false)   I / flutter(9119):-语义(容器:否,属性:SemanticsProperties,标签:空,值:空,提示:空)   I / flutter(9119):-侦听器(侦听器:[向下],行为:不透明)   I /颤振(9119):-_手势语义   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):违规扩展版的父级的所有权链为:   I / flutter(9119):DefaultTextStyle←AnimatedDefaultTextStyle←_InkFeatures- [GlobalKey#93e52墨水渲染器]←   I / flutter(9119):NotificationListener←CustomPaint←__ShapeBorderPaint←PhysicalShape   I / flutter(9119):←_MaterialInterior←材质←填充←⋯   I /颤振(9119):   ══════════════════════════════════════════════════ ══════════════════════════════════════════════════   I / flutter(9119):引发了另一个异常:不正确使用ParentDataWidget。   I /聊天(9119):uid = 10096(com.example.flutterapp)线程3相同的3行   I / flutter(9119):引发了另一个异常:不正确使用ParentDataWidget。

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

enter image description here

如果我删除了Expanded,输出将如下所示:

enter image description here

3 个答案:

答案 0 :(得分:4)

我发现了这个问题,整个问题是通过删除itemExtent: 25.0,上的ListView.builder,默认情况下所有内容都可以扩展并且运行平稳。

在寻找解决方案时,我遇到了thisthisthis,这有助于我以更简洁的代码重建应用程序,下面是谁感兴趣的应用程序:< / p>

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

答案 1 :(得分:1)

在此示例中,我们使用卡片样式列表视图构建了using assembly。这是为了帮助实现特定的样式。这种System.Windows.Forms样式已广泛用于显示列表样式项。

使用ListView属性。您可以通过调整card来更改阴影。另外尝试更改Card和边距。

此示例的最后一行显示了如何创建可以点击的elevation小部件。轻按此卡的shape,将显示“墨水飞溅”,并填满整个卡。

Card

这是运行时的样子:

enter image description here

答案 2 :(得分:0)

您可以在手机屏幕上打印问题吗?

我放置了您的代码,并且没有扩展的小部件及其完善的功能, 您要更改什么?

Print mobile