将卡添加到ListView [英] Adding Card to ListView

查看:60
本文介绍了将卡添加到ListView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取



如果我删除了 Expanded 输出变为:



解决方案

我知道了,整个问题出在 ListView.builder上使用 itemExtent:25.0, code>删除它后,默认情况下所有内容都可以扩展并运行平稳。



在寻找解决方案时,我遇到了


I'm trying to get list of Cards, and trying using the Expanded widget, but got overflow error

My code:

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: () { /* ... */ },
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                    ),
                    );
                });
          })),

The error I got is: Incorrect use of ParentDataWidget.

Full error:

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
Here is the output screen I got:

If I removed the Expanded the output became like this:

解决方案

I figured it out, the whole problem was in using itemExtent: 25.0, at ListView.builder by removing it, everything became expandable by default and run smoothly.

While searching for the solution, I came across this and this and this, that helped me rebuilding the app in a cleaner code, below it is for who is interested:

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

And the output is:

这篇关于将卡添加到ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆