【问题标题】:Why I'm getting the error, Invalid constant value in flutter statfulwidget flutter为什么我收到错误,flutter statfulwidget flutter 中的常量值无效
【发布时间】:2021-07-20 10:25:56
【问题描述】:

在下面的代码中,widget.hintText 给出了错误,我试图将 datepicker 作为单独的组件,并在从另一个文件调用它时动态传递提示文本值。

import 'package:date_field/date_field.dart';
import 'package:flutter/material.dart';


class DatePicker extends StatefulWidget {
  final String hintText;
  DatePicker({
    this.hintText,
    Key key,
  }): super(key: key);

  @override
  _DatePickerState createState() => _DatePickerState();
}
class _DatePickerState extends State<DatePicker> {
  @override
  Widget build(BuildContext context) {
    return DateTimeFormField(
  decoration: const InputDecoration(
    hintText: widget.hintText,
    hintStyle: TextStyle(color: Colors.black54,fontSize: 16),
    errorStyle: TextStyle(color: Colors.redAccent),
    suffixIcon: Icon(Icons.event_note),
  ),
  mode: DateTimeFieldPickerMode.date,
  autovalidateMode: AutovalidateMode.always,
  // validator: (e) => (e?.day ?? 0) == 1 ? 'Please not the first day' : null,
  onDateSelected: (DateTime value) {
  },
);
  }
}


【问题讨论】:

    标签: flutter dart statefulwidget


    【解决方案1】:

    错误来自于在 const 对象 InputDecoration 内部使用变量 widget.hint

    我在date_field 代码中找不到强制您使用常量decoration 的任何地方

    因此,您可能只需删除 InputDecoration 前面的 const 关键字

    constfinal 的区别详见this answer

    【讨论】:

      【解决方案2】:

      您可以尝试从字符串中删除final 关键字

      【讨论】:

      • 是的,我尝试删除 final 关键字,但它给出了错误“此类(或此类继承自的类)被标记为 '@immutable',但它的一个或多个实例字段不是”最终"
      猜你喜欢
      • 2017-11-30
      • 2022-08-21
      • 2022-01-01
      • 2021-05-22
      • 2019-07-29
      • 1970-01-01
      • 2020-06-05
      • 2019-07-29
      • 1970-01-01
      相关资源
      最近更新 更多