Flutter中如何通过GestureDetector将列表索引传递到另一个页面
Flutter列表项索引传递错误的解决方案
问题原因
- 字符串转换写法错误:你使用了
toString(index),这不是Dart中整数转字符串的正确方式。正确写法是调用整数对象的toString()方法,即index.toString()。toString(index)会被视为调用一个未定义的全局函数,返回值为Null,这就是错误提示里"A value of type Null can't be assigned to a parameter of type String"的直接原因。 - const构造器使用不当:你用
const Portfolio(...)创建页面,但index.toString()是运行时动态生成的值,而const构造器要求所有参数必须是编译时常量,动态值无法满足这个要求,因此必须去掉const修饰符。
修正后的代码
将onTap部分的代码修改如下:
onTap: () => Navigator.push( context, MaterialPageRoute( builder: (context) => Portfolio(title: 'Portfolio', index: index.toString()), ) ),
完整的build方法修正后代码:
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: ListView.builder( itemCount: totalItems, itemBuilder: (context, index) { return GestureDetector( child: Container( // This is the back container which will show next cell colour on the rounded edge color: index == totalItems-1 ? Colors.transparent : colours[(index+1)%2], child: Container( height: 180, decoration: BoxDecoration( borderRadius: const BorderRadius.only(bottomLeft: Radius.circular(85.0)), color: colours[index%2], ), child: Center( child: Text( index.toString(), style: const TextStyle(color: Colors.white, fontSize: 50), ), ), ), ), onTap: () => Navigator.push( context, MaterialPageRoute( builder: (context) => Portfolio(title: 'Portfolio', index: index.toString()), ) ), ); }, ), ); }
额外优化建议
如果你的Portfolio页面的index参数可以接收整数类型,直接传递index(整数)会更高效,只要确保Portfolio的构造器参数类型匹配即可:
// 假设Portfolio的构造器定义为: class Portfolio extends StatelessWidget { final String title; final int index; const Portfolio({super.key, required this.title, required this.index}); // ...页面其他代码 } // 此时onTap里的代码可以改为: onTap: () => Navigator.push( context, MaterialPageRoute( builder: (context) => Portfolio(title: 'Portfolio', index: index), ) ),
内容的提问来源于stack exchange,提问作者sandycheeks
相关产品推荐
相关产品推荐

