在Flutter中如何在其他控件上显示列表视图顶层项数据

goqiplq2  于 2022-11-17  发布在  Flutter
关注(0)|答案(1)|浏览(180)

我刚刚创建了一个演示,用于说明我的需求
我有一个列表视图构建器和一个显示列表视图构建器的顶部值的容器,这里我不是指列表视图的0索引值...
当我向上或向下滚动时,第一个容器应该更改为listview

的topper项,这是我的代码

Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: [
            Container(
              height: 200,
              color: Colors.red,
              child:
                  Center(child: Text('show data of topper of shown listview',style: TextStyle(fontSize: 20),),
                  ),
            ),
            SizedBox(
              height: 10,
            ),
            Expanded(
              child: Container(
                color: Colors.blue,
                child: ListView.builder(
                    itemCount: mylist.length,
                    itemBuilder: (context, index) {
                      return Card(
                        child: ListTile(
                          title: Text(mylist[index]['name']),
                          subtitle: Text(mylist[index]['aboutme'],
                          overflow: TextOverflow.ellipsis,),
                        ),
                      );
                    }),
              ),
            ),
          ],
        ),
      ),
    );
  }
9jyewag0

9jyewag01#

首先定义此变量:

String topperValue = '';
GlobalKey itemKey = GlobalKey();
double itemHeight = 0.0;
ScrollController controller = ScrollController();

然后在initState中执行以下操作:

@override
  void initState() {
    super.initState();

    controller.addListener(() {
      setState(() {
        var index = (controller.position.pixels / itemHeight).floor();
        topperValue = index < 1 ? '' : mylist[index - 1];
      });
    });
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setState(() {
        final itemKeyContext = itemKey.currentContext;
        if (itemKeyContext != null) {
          final box = itemKeyContext.findRenderObject() as RenderBox;
          itemHeight = box.size.height;
        }
      });
    });
  }

然后按如下方式使用它:

Container(
    height: 200,
    color: Colors.red,
    child: Center(
      child: Text(
        topperValue,
        style: TextStyle(fontSize: 20),
      ),
    ),
  ),
  SizedBox(
    height: 10,
  ),
  Expanded(
    child: Container(
      color: Colors.blue,
      child: ListView.builder(
          controller: controller,
          itemCount: mylist.length,
          itemBuilder: (context, index) {
            return Card(
              key: index == 0 ? itemKey : null,
              child: ListTile(
                title: Text(mylist[index]),
                subtitle: Text(
                  mylist[index],
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            );
          }),
    ),
  )

相关问题