-1

Total newbie here but I can't get around this. I want a reusable widget that takes a String title in its constructor and then uses it in the build's widget:

import 'package:flutter/material.dart';

class TemperatureInputDecoration extends StatelessWidget {
  const TemperatureInputDecoration({Key? key, required this.title})
    : super(key: key);
  final String title;

  @override
  Widget build(BuildContext context) {
    return const InputDecorator(
      decoration: InputDecoration(
        labelText: title,
        focusColor: Colors.orangeAccent,
      ),
    );
  }
}

I get an error on the line 'labelText: title' saying 'Invalid constant value'. I've tried widget.title, creating a getter for super.widget and using a Stateful widget but no go.

I've seen this page but none of it worked for me. Maybe it has something to do with InputDecoration not being a widget? Any help appreciated.

CraigFoote
  • 371
  • 1
  • 7
  • 23

3 Answers3

0

InputDecoration is not a widget, as defined by the class,

import 'package:flutter/material.dart';

class TemperatureInputDecoration extends StatelessWidget {
  const TemperatureInputDecoration({Key? key, required this.title})
    : super(key: key);
  final String title;

  @override
  Widget build(BuildContext context) {
    return const Text(
      title,
      style: TextStyle(color: Colors.red)
    );
  }
}

this will work just fine

M.M.Hasibuzzaman
  • 1,015
  • 5
  • 10
  • InputDecorator is a widget it extends StatefulWidget – mario francois Nov 27 '21 at 22:57
  • @M.M.Hasibuzzaman thanks for replying but won't that set the text value in the Text widget rather than its decorator? InputDecoration does not have an unnamed(?) String parameter. To set its text value I think you use labelText property. – CraigFoote Nov 27 '21 at 22:58
0

Turns out it was simple, just extend InputDecoration rather than StatefulWidget:

import 'package:flutter/material.dart';

class TemperatureInputDecoration extends InputDecoration {
  const TemperatureInputDecoration({required this.text, required this.color});

  final String text;
  final Color color;

  @override
  String get labelText => text;

  @override
  Color get focusColor => color;
}

Now I can just instantiate the Decoration where I need it, passing text and color in from above rather than inline.

CraigFoote
  • 371
  • 1
  • 7
  • 23
-1

Try this:

class TemperatureInputDecoration extends StatefulWidget {
  TemperatureInputDecoration (this.uid);
  final uid;
  @override
  TemperatureInputDecorationstate  createState() => TemperatureInputDecorationstate  (this.uid);
}

class TemperatureInputDecorationstate    extends State<TemperatureInputDecoration > {
      TemperatureInputDecorationstate (this.uid);
  var uid;
//you can use uid inside widget.....
}

and to reuse variable:

TemperatureInputDecoration('set here uid value');
Mohamed Amin
  • 997
  • 2
  • 12
  • 29