Flutter ScrollablePositionedList无法跳转指定索引问题求助
问题排查与修复方案
核心问题1:跳转索引参数错误
点击按钮时调用controller.jumpTo(index: index),但此处的index未定义——循环变量是i,应该传入i作为目标索引。
核心问题2:列表项数量配置错误
ScrollablePositionedList的itemCount写成了totalItems.length,但从循环逻辑看totalItems是一个整数(代表总条目数),而非列表,直接使用totalItems即可。
顶部按钮上滑隐藏的实现
要实现顶部数字列表上滑隐藏,需要将顶部区域与滚动列表结合,用NestedScrollView配合SliverAppBar来实现滚动时的隐藏效果。
修正后的完整代码
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter_widgets/flutter_widgets.dart'; class ScrollableListDemo extends StatelessWidget { final int totalItems = 20; final ItemScrollController controller = ItemScrollController(); ScrollableListDemo({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: NestedScrollView( headerSliverBuilder: (context, innerBoxIsScrolled) { return [ SliverAppBar( pinned: false, floating: false, expandedHeight: 100, flexibleSpace: FlexibleSpaceBar( centerTitle: true, title: const Text("Click the number below to jump to Index"), background: Wrap( alignment: WrapAlignment.center, children: [ for (int i = 0; i < totalItems; i++) InkWell( onTap: () { controller.jumpTo(index: i); }, child: Padding( padding: const EdgeInsets.all(8.0), child: Text( (i).toString(), style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold), ), ), ) ], ), ), ) ]; }, body: ScrollablePositionedList.builder( itemScrollController: controller, itemCount: totalItems, itemBuilder: (context, index) { return ConstrainedBox( constraints: const BoxConstraints(minHeight: 50, maxHeight: 200), child: Container( color: Color.fromARGB( 255, Random().nextInt(255), Random().nextInt(255), Random().nextInt(255)), height: 100.0 * index * 0.1, child: ListTile( title: Text( "Item $index", style: const TextStyle( fontSize: 24, fontWeight: FontWeight.bold), ), ), ), ); }, ), ), ); } }
内容的提问来源于stack exchange,提问作者Joven Dev
相关产品推荐
相关产品推荐

