(共556篇)
全部分类

flutter跳坑-State子类获取不到StateFullWidget或者StateLessWidget的实例属性
[ Flutter ] 

state子类中使用实例属state子类中使用实例属性

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Product{
	final String name = '';
    Product({this.name});
}
class ShoppingList extends StateFull{
	List<Product> products = [
    	Product(name:'loki'),
        Product(name:'lily'),
    ];
    
	@override
    createState => _ShoppingListState();
}
class _ShoppingListState extends State{
	@override
    Widget build(Context context){
    	return Scafold(
        	apBar: AppBar(
            	title:'app bar',
            ),
            body:Center(
            	Row(
                	children: products.map((Product product){
                    	retrun Text('${product.name}');
                    }).toList()
                )
            )
        )
    }
}

这段代码中,原意是遍历products产生一组Text组件,但编辑器中直接报错了,说是没有找到变量products,也就是说_ShoppingListState的实例中访问不到ShoppingList中的products属性.

这是因为_ShoppingListState在继承State类的时候,没有对State类做说明,

class _ShoppingListState extends State改为class _ShoppingListState extends State<ShoppingList>即可,但是记得在调用products时,改为widget.products

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Product{
	final String name = '';
    Product({this.name});
}
class ShoppingList extends StateFull{
	List<Product> products = [
    	Product(name:'loki'),
        Product(name:'lily'),
    ];
    
	@override
    createState => _ShoppingListState();
}
class _ShoppingListState extends State<ShoppingList>{
	@override
    Widget build(Context context){
    	return Scafold(
        	apBar: AppBar(
            	title:'app bar',
            ),
            body:Center(
            	Row(
                	children: widget.products.map((Product product){
                    	retrun Text('${product.name}');
                    }).toList()
                )
            )
        )
    }
}

第二种方案是,调用_ShoppingListState时,把products当做参数传递进去,比如:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Product{
	final String name = '';
    Product({this.name});
}
class ShoppingList extends StateFull{
	List<Product> products = [
    		Product(name:'loki'),
        	Product(name:'lily'),
    	];
    
	@override
    createState => _ShoppingListState(products:products);
}
class _ShoppingListState extends State<ShoppingList>{
    List<Product> products = [];
    _ShoppingListState({this.products});
    
    
	@override
    Widget build(Context context){
    	return Scafold(
        	apBar: AppBar(
            	title:'app bar',
            ),
            body:Center(
            	Row(
                	children: products.map((Product product){
                    	retrun Text('${product.name}');
                    }).toList()
                )
            )
        )
    }
}