我在有狀態類中構建了一個帶有一個字串引數的建構式,然后當我使用 widget.label 呼叫這個引數時,它給了我這個錯誤
“無效的常數值。”
這是我的代碼:
import 'package:flutter/material.dart';
class TextFieldDecoration extends StatefulWidget {
final String? label;
const TextFieldDecoration({Key? key, this.label}) : super(key: key);
@override
_TextFieldDecorationState createState() => _TextFieldDecorationState();
}
class _TextFieldDecorationState extends State<TextFieldDecoration> {
@override
Widget build(BuildContext context) {
return const TextField(
decoration: InputDecoration(
labelStyle: TextStyle(color: Colors.black45),
labelText: widget.label,
),
style: TextStyle(
color: Color(0xff1f8ac0),
),
);
}
}

uj5u.com熱心網友回復:
發生錯誤是因為您將您定義TextField為常量,但您的變數不能是常量。要解決您的問題,只需洗掉const前面的TextField.
class _TextFieldDecorationState extends State<TextFieldDecoration> {
@override
Widget build(BuildContext context) {
return TextField(
decoration: InputDecoration(
labelStyle: TextStyle(color: Colors.black45),
labelText: widget.label,
),
style: TextStyle(
color: Color(0xff1f8ac0),
),
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/430009.html
