Adding Card to ListView

8

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:

enter image description here

If I removed the Expanded the output became like this:

enter image description here

dart
flutter
asked on Stack Overflow Jun 23, 2018 by Hasan A Yousef • edited Jun 24, 2018 by Hasan A Yousef

3 Answers

14

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:

enter image description here

answered on Stack Overflow Jun 24, 2018 by Hasan A Yousef
1

In this example we build an ListView with card style list view. This is to help achieve a specific styling. This card style is being popularly used to display list style items.

Play around with the Card attributes. You can change the shadow by adjusting the elevation. Also try changing the shape and margin.

This example at last row shows creation of a Card widget that can be tapped. When tapped this Card's InkWell displays an "ink splash" that fills the entire card.

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',
              ),
            ),
          ),
        )),
  ],
)

This is what it looks like when run:

enter image description here

answered on Stack Overflow Oct 7, 2020 by Paresh Mangukiya
0

Can you put the print of mobile screen in your question ?

I put your code and without expanded widget and its perfect, what you want to change?

Print mobile

answered on Stack Overflow Jun 23, 2018 by lucas britto

User contributions licensed under CC BY-SA 3.0