【问题标题】:Adding Card to ListView将卡片添加到 ListView
【发布时间】:2018-12-02 18:26:14
【问题描述】:

我正在尝试获取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.

完全错误:

正在执行热重载... 我/颤振(9119):══╡小部件库发现异常╞═════════════════════════════════════════════ ═════════════════════════ I/flutter (9119):在构建 DefaultTextStyle(debugLabel: (englishLike) 时抛出了以下断言 I/flutter (9119): body1).merge(blackMountainView body1), 继承: false, color: Color(0xdd000000), family: Roboto, I/flutter(9119):尺寸:14.0,重量:400,基线:字母,装饰:TextDecoration.none,softWrap:包装 I/flutter(9119):在框宽度,溢出:剪辑): I/flutter (9119):ParentDataWidget 使用不正确。 I/flutter (9119):扩展的小部件必须直接放置在 Flex 小部件中。 I/flutter (9119): Expanded(no depth, flex: 1, dirty) 有一个 Flex 祖先,但它们之间还有其他小部件: I/flutter (9119): - _InkFeatures-[GlobalKey#93e52 墨水渲染器] 我/颤振(9119):-CustomPaint I/flutter(9119):- PhysicalShape(剪裁器:ShapeBorderClipper,海拔:1.0,颜色:颜色(0xffffffff),shadowColor: I/颤动(9119):颜色(0xff000000)) 我/颤振(9119):-填充(填充:EdgeInsets.all(4.0)) I/flutter(9119):-语义(容器:true,属性:SemanticsProperties,标签:null,值:null,提示:null) 我/颤振(9119):-重绘边界-[] 我/颤振(9119):- KeepAlive(keepAlive:false) I/flutter(9119):-SliverFixedExtentList(委托:SliverChildBuilderDelegate#b334e(估计的孩子数:3)) I/颤振(9119):- SliverPadding(填充:EdgeInsets(0.0、10.0、0.0、0.0)) I/flutter (9119): - 视口(axisDirection: down, anchor: 0.0, offset: ScrollPositionWithSingleContext#bebad(offset: I/flutter (9119):0.0,范围:0.0..0.0,视口:380.0,ScrollableState,AlwaysScrollableScrollPhysics -> I/flutter (9119): ClampingScrollPhysics, IdleScrollActivity#7b3a8, ScrollDirection.idle)) 我/颤振(9119):-IgnorePointer-[GlobalKey#4c7f9](忽略:假,忽略语义:假) I/flutter(9119):-语义(容器:false,属性:SemanticsProperties,标签:null,值:null,提示:null) I/flutter(9119):- 侦听器(侦听器:[down],行为:不透明) 我/颤振(9119):-_GestureSemantics 我/颤振(9119):-_ExcludableScrollSemantics-[GlobalKey#22165] 我/颤振(9119):-重绘边界 我/颤振(9119):-CustomPaint 我/颤振(9119):-重绘边界 I/flutter (9119): - Expanded(flex: 1) (这是与有问题的扩展不同的扩展) I/flutter (9119):这些小部件不能介于 Expanded 和它的 Flex 之间。 I/flutter(9119):违规扩展的父级的所有权链是: I/flutter (9119): DefaultTextStyle ← AnimatedDefaultTextStyle ← _InkFeatures-[GlobalKey#93e52 ink renderer] ← I/flutter (9119): NotificationListener ← CustomPaint ← _ShapeBorderPaint ← PhysicalShape I/flutter (9119): ← _MaterialInterior ← Material ← Padding ← ⋯ 我/颤振(9119): ══════════════════════════════════════════════════ ══════════════════════════════════════════════════ I/flutter (9119):引发了另一个异常:ParentDataWidget 的使用不正确。 I/chatty (9119): uid=10096(com.example.flutterapp) Thread-3 相同的 3 行 I/flutter (9119): 另一个异常被抛出:ParentDataWidget 的使用不正确。

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

如果我删除了Expanded,输出会变成这样:

【问题讨论】:

  • 我认为你不需要在那里扩展。
  • @Bostrot 没有扩展它是最糟糕的:(
  • 错误其实是Expanded widgets must be placed directly inside Flex widgets.Flex widgets are like Row, Column, Flex, etc.
  • @JacobPhillips 我用我在屏幕上看到的内容更新了我的问题。

标签: dart flutter


【解决方案1】:

在此示例中,我们构建了一个带有卡片样式列表视图的 ListView。这是为了帮助实现特定的样式。这种card 样式被广泛用于显示列表样式项。

玩转Card 属性。您可以通过调整elevation 来更改阴影。还可以尝试更改shape 和边距。

最后一行的这个例子展示了一个可以点击的Card 小部件的创建。点按此卡片的 InkWell 时,会显示填满整张卡片的“墨水溅”。

ListView(
  children: <Widget>[
    Card(child: ListTile(title: Text('One-line ListTile'))),
    Card(
      child: ListTile(
        leading: FlutterLogo(),
        title: Text('One-line with leading widget'),
      ),
    ),
    Card(
      child: ListTile(
        title: Text('One-line with trailing widget'),
        trailing: Icon(Icons.more_vert),
      ),
    ),
    Card(
      child: ListTile(
        leading: FlutterLogo(),
        title: Text('One-line with both widgets'),
        trailing: Icon(Icons.more_vert),
      ),
    ),
    Card(
      child: ListTile(
        title: Text('One-line dense ListTile'),
        dense: true,
      ),
    ),
    Card(
      child: ListTile(
        leading: FlutterLogo(size: 56.0),
        title: Text('Two-line ListTile'),
        subtitle: Text('Here is a second line'),
        trailing: Icon(Icons.more_vert),
      ),
    ),
    Card(
      child: ListTile(
        leading: FlutterLogo(size: 72.0),
        title: Text('Three-line ListTile'),
        subtitle:
        Text('A sufficiently long subtitle warrants three lines.'),
        trailing: Icon(Icons.more_vert),
        isThreeLine: true,
      ),
    ),
    Card(
        child: InkWell(
          splashColor: Colors.blue.withAlpha(30),
          onTap: () {
            print('Card tapped.');
          },
          child: Container(
            width: 300,
            height: 100,
            child: Center(
              child: Text(
                'When tapped this Cards InkWell displays an ink splash that fills the entire card',
              ),
            ),
          ),
        )),
  ],
)

这是运行时的样子:

【讨论】:

    【解决方案2】:

    我想通了,整个问题是在 ListView.builder 使用 itemExtent: 25.0, 删除它,默认情况下一切都变得可扩展并且运行顺利。

    在寻找解决方案时,我遇到了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,
            );
      }
    }
    

    输出是:

    【讨论】:

    • @CrsCaballero 我使用的所有代码都出现在上面
    【解决方案3】:

    你能把手机屏幕的打印放在你的问题中吗?

    我把你的代码和没有扩展的小部件和它的完美, 你想改变什么?

    【讨论】:

    • 我用我在屏幕上看到的内容更新了我的问题。您是否已将您的应用连接到 Firebase!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2020-05-26
    • 2016-05-28
    • 1970-01-01
    相关资源
    最近更新 更多