Flutter中如何向有状态类(Stateful Class)传递参数?
向Flutter有状态组件传递参数的实现方案
步骤1:修改Thkr有状态组件,添加参数
首先在Thkr类中定义需要接收的tH参数,用final修饰并通过构造函数传入:
class Thkr extends StatefulWidget { // 定义需要传递的文本参数 final String tH; // 构造函数,要求必须传入tH参数 const Thkr({super.key, required this.tH}); @override State<Thkr> createState() => _ThkrState(); }
步骤2:在State类中访问传递的参数
在_ThkrState类里,通过widget.tH即可拿到父组件传递的文本数据,替换原代码中的占位符:
class _ThkrState extends State<Thkr> { int thkrCount = 3; void _incrementCounter() { setState(() { thkrCount--; }); } @override Widget build(BuildContext context) { return Column( children: [ Container( padding: const EdgeInsets.all(35), margin: const EdgeInsets.all(20), decoration: BoxDecoration( border: Border.all(color: Colors.black, width: 3), borderRadius: BorderRadius.circular(8), boxShadow: const [ BoxShadow( color: Colors.lightGreen, offset: Offset(6.0, 6.0), ), ], ), // 使用widget.tH获取传递的文本 child: Text( widget.tH, style: TextStyle(fontSize: textSize, color: themeli[themei]), ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Card( child: SizedBox( width: 100, height: 30, child: Center( child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.lightGreen, minimumSize: const Size.fromHeight(40), ), onPressed: _incrementCounter, child: Text( 'Count', style: TextStyle(color: themeli[themei]), ), ), ), ), ), Card( child: SizedBox( width: 100, height: 30, child: Center( child: Text( "$thkrCount left", style: const TextStyle( backgroundColor: Colors.white12, ), ), ), ), ), ], ) ], ); } }
步骤3:从列表数据批量创建Thkr组件
假设你有一个文本列表,比如:
final List<String> thkrTexts = [ "感恩祝福1", "感恩祝福2", "感恩祝福3", ];
可以通过ListView.builder循环生成多个Thkr组件:
ListView.builder( itemCount: thkrTexts.length, itemBuilder: (context, index) { return Thkr(tH: thkrTexts[index]); }, )
关键说明
- 有状态组件的参数必须定义在
StatefulWidget类中,用final修饰保证不可变 - 在State类中通过
widget.参数名访问传递的数据 - 构造函数中使用
required确保调用组件时必须传入参数,避免遗漏
内容的提问来源于stack exchange,提问作者Abood Osili
相关产品推荐
相关产品推荐

