Ad

Widget.Variable Does Not Work To Access String Variable Form Stful Constructor

- 1 answer

I build a constructor in stateful class that take one string parameter, then when I call this parameter using widget.label, it gives me this error

"Invalid constant value."

here is my code:

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),
      ),
    );
  }
}

enter image description here

Ad

Answer

The error occurs because you defined your TextField as constant but you variable cannot be constant. To fix your issue, just remove const in front of 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),
      ),
    );
  }
}
Ad
source: stackoverflow.com
Ad