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.
CodePudding user response:
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
CodePudding user response:
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.
CodePudding user response:
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');