如何将数据传递给有状态的小部件

时间:2019-08-25 11:32:24

标签: flutter dart

当我尝试将数据传递给有状态的小部件时,出现此错误:

[State]对象的配置是相应的[StatefulWidget]实例。此属性由框架在调用[initState]之前初始化。 在初始化器中只能访问静态成员。

基本上,我正在尝试将数据从detail.dart传递到about.dart

detail.dart:

class PokemonDetail extends StatefulWidget {
PokemonDetail({this.pokemon});

@override
_PokemonDetailState createState() => _PokemonDetailState();
}

class _PokemonDetailState extends State<PokemonDetail> with SingleTickerProviderStateMixin{
final List<TabData> _tabs = [
TabData("About", PokemonAbout(pokemon: widget.pokemon)),
....];


@override
_PokemonAboutState createState() => _PokemonAboutState();
}


Widget _buildTabContent() {
return Expanded(
  child: TabBarView(
    children: _tabs.map((tab) => tab.child).toList(),
  ),
);
}

about.dart:

class PokemonAbout extends StatefulWidget {
final Pokemon pokemon;

const PokemonAbout({this.pokemon, key}) : super(key: key);

2 个答案:

答案 0 :(得分:0)

此行_PokemonAboutState createState() => _PokemonAboutState();不应在State类内调用。它已经在StatefulWidget类中定义。尝试删除它,看看会发生什么。

答案 1 :(得分:0)

'widget.pokemon'不能在类级字段初始化中使用。尝试在initState内部移动制表符声明:

class _PokemonDetailState extends State<PokemonDetail> with SingleTickerProviderStateMixin{
List<TabData> _tabs = [];

@override
void initState(){
   super.initState();
   _tabs = [ TabData("About", PokemonAbout(pokemon: widget.pokemon)), ....];
}

我希望这会有所帮助!