首页 > 解决方案 > Flutter 无法为具有非最终字段的类定义 const 构造函数

问题描述

如果我使用它来显示,我需要在我的代码中使用 setState

The method 'setState' isn't defined for the type 'ProductDetailPage'.

我知道这是什么问题,因为我需要将 statelesswidget 更改为 statefullwidget。但是,如果我将无状态小部件更改为有状态小部件,则会出现另一个问题

Can't define a const constructor for a class with non-final fields.

我的代码

part of '../pages.dart';

class ProductDetailPage extends StatefulWidget {
  @override
  _ProductDetailPageState createState() => _ProductDetailPageState();
}

class _ProductDetailPageState extends State<ProductDetailPage> {

  final Product product;

  const ProductDetailPage({Key key, @required this.product}) : super(key: key); //showing error here


  @override
  Widget build(BuildContext context) {

    double stackWidth = MediaQuery.of(context).size.width;
    double stackHeight = MediaQuery.of(context).size.height;

    return Scaffold(
      body: Container(
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              buildCarousel(context),

            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () {
          //todo: Get.to(CartPage());
        },
        backgroundColor: kPrimaryColor,
        label: Text(
          'product.addtocart',
          style: Theme.of(context).textTheme.button,
        ).tr(),
      ),
    );
  }


  SideInAnimation buildCarousel(BuildContext context) {
    double stackWidth = MediaQuery.of(context).size.width;
    double stackHeight = MediaQuery.of(context).size.height;
    return SideInAnimation(
      1,
      child: Container(
        color: kCardImageBCColor,
        child: Column(
          children: [
            SizedBox(
              height: stackHeight * 0.3,
              child: Image.asset(product.images[0]),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ...List.generate(product.images.length,
                        (index) => buildSmallProductPreview(index, context)),
              ],
            ),
            SizedBox(height: stackHeight * 0.02,)
          ],
        ),

      ),
    );
  }

  GestureDetector buildSmallProductPreview(int index, BuildContext context) {
    int selectedImage = 0;
    double stackWidth = MediaQuery.of(context).size.width;
    double stackHeight = MediaQuery.of(context).size.height;
    return GestureDetector(
      onTap: () {
        setState(() {
          selectedImage = index;
        });
      },
      child: AnimatedContainer(
        duration: Duration(seconds: 1),

        margin: EdgeInsets.only(right: 10),
        height: stackHeight * 0.07,
        width: stackWidth * 0.15,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(10),
          border: Border.all(
              color: kPrimaryColor.withOpacity(selectedImage == index ? 1 : 0)),
        ),
        child: Image.asset(product.images[index]),
      ),
    );
  }
}

如果使用 statefull 小部件并且不使用 setState 它工作正常,我不知道为什么它会显示错误。但我必须需要 setState 所以我必须继续使用 stateFull 小部件。我需要解决错误xD

标签: flutter

解决方案


您需要将 final 变量和构造函数放在 ProductDetailPage 类中。像这样:

class ProductDetailPage extends StatefulWidget {

  final Product product;

  const ProductDetailPage({Key key, @required this.product}) : super(key: key);

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

class _ProductDetailPageState extends State<ProductDetailPage> {


  @override
  Widget build(BuildContext context) {...}
}

推荐阅读