Yugene
Yugene

Reputation: 3222

I want to get a widget height with fixed width before build

I have a problem to get a widget estimated height before the build. The problem is like this; When content is short it needs to be in one card, but if the content is some long it needs to be shown in 2 or more cards. Cards will be like Tinder swiping cards, so I must calculate the cards amount before the build.

ListView.builder(
    itemCount: 1 // count needs to be based on text length
    itemBuilder: (BuildContext context, int index) =>
        Card(child: Text('Some long message'))
)

I made it simple for Card chile as a Text, but actually it is a complex widget with several texts and image so that I need to calculate how many fixed height cards are needed to display all.

Upvotes: 0

Views: 211

Answers (1)

LonelyWolf
LonelyWolf

Reputation: 4392

From your example this is one of the solution.. I split long text at space and create a list of strings and then populate Listview with that list

  String text = 'Very very long text';
  @override
  Widget build(BuildContext context) {
    List<String> list = (text.split(' '));
    return Scaffold(
        body: ListView.builder(
      itemCount: list.length,
      itemBuilder: (BuildContext context, int index) => Card(
        child: Text(list[index]),
      ),
    ));
  } 

OUTPUT

enter image description here

Upvotes: 1

Related Questions