Asbah Riyas
Asbah Riyas

Reputation: 986

Update animated container in a listView.builder

How to update animated container with longPress which lies under the listview builder

widget.meetingdetails.forEach((tasks) {
  if (tasks['task'] == 'Meeting') {
    _meetinglist.add(GestureDetector(
      onLongPress: () {
        setState(() {
          heightChange = heightChange == 130 ? 150 : 130;

        });
      },
      child: AnimatedContainer(
        duration: new Duration(milliseconds: 500),
        height: heightChange,
        padding: EdgeInsets.symmetric(horizontal: 30, vertical: 10),)).......

above code is the way i make the list and below code is how i implement it on the listView.builder

return ListView.builder(
  itemCount: _meetinglist.length,
  itemBuilder: (BuildContext context, int index) => _meetinglist[index],
  padding: EdgeInsets.only(bottom: 60), physics: BouncingScrollPhysics(),

);

Here when i longPress on the container all the items in the list updates. I need only the pressed container to update

The container before longpress Container after longpress

Upvotes: 2

Views: 1953

Answers (1)

Abhilash Chandran
Abhilash Chandran

Reputation: 7509

I think your height variable is part of this state which is being shared across all the widgets in the _meetingList variable. Thats why all of them are updated. Try extracting the GestureDetector widget into its own Stateful widget and handle the heights individually in the respective widget.

A live dartpad is available here.

example

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  final List<MeetingCard> _meetingCards = [
          MeetingCard(title: 'standup meeitng'),
          MeetingCard(title: 'weekely meeting'),          
          MeetingCard(title: 'Status Meeting'),
          MeetingCard(title: 'Another meeting'),

  ];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Adjustable height card.',
      home: ListView.builder(
        itemCount: _meetingCards.length,
        itemBuilder: (context, index){
          return _meetingCards[index];
        }
      ),
    );
  }
}

// Define a custom Form widget.
class MeetingCard extends StatefulWidget {
  final String title;

  MeetingCard({this.title});
  @override
  _MeetingCardState createState() => _MeetingCardState();
}

// Define a corresponding State class.
class _MeetingCardState extends State<MeetingCard> {

  // this height is specific to this widget.
  double height = 130;

  @override
  Widget build(context) {
    return GestureDetector(
      onLongPress: (){
        setState((){
          height = height == 130 ? 150 : 130;
        });
      },
      child: AnimatedContainer(
        duration: new Duration(milliseconds: 500),
        height: height,
        child: Card(child: Center(child: Text(widget.title),),),
      ),
    );
  }
}


Upvotes: 1

Related Questions