更新listView.builder

时间:2020-03-21 11:06:03

标签: android flutter dart flutter-layout

如何使用位于listview构建器下的longPress更新动画容器

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),)).......

上面的代码是我创建列表的方式,下面的代码是我在listView.builder上实现它的方式

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

);

在此处长按容器上的列表中的所有项目将更新。我只需要按下容器即可

The container before longpress Container after longpress

1 个答案:

答案 0 :(得分:2)

我认为您的height变量是此状态的一部分,该状态已在_meetingList变量中的所有小部件之间共享。这就是为什么它们全部都被更新的原因。尝试将GestureDetector小部件提取到其自己的有状态小部件中,并在各个小部件中分别处理高度。

可以使用实时飞镖here

示例

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