This question already has an answer here:
Why am I getting TypeError at runtime with my generic StatefulWidget class?
(1 answer)
Closed 10 months ago.
I'm trying to create a class that use a generic type as a parameter in a callback that returns some subtype of Flutter's Widget. Here's what I started with:
class Subscriber<P extends PublishingController> extends StatefulWidget {
const Subscriber({required this.builder, Key? key}) : super(key: key);
final Widget Function(P) builder;
#override
_SubscriberState<P> createState() => _SubscriberState<P>();
}
class _SubscriberState<P extends PublishingController> extends State<Subscriber> {
final P publisher = GetIt.instance.get<P>();
#override
void initState() {
publisher.subscribe(rebuild);
super.initState();
}
#override
Widget build(BuildContext context) {
return widget.builder(publisher);
}
#override
void dispose() {
publisher.unsubscribe(rebuild);
super.dispose();
}
void rebuild() {
setState(() {});
}
}
... with the Publisher:
mixin Publisher {
List<Function> subscribers = <void Function()>[];
void subscribe(Function f) {
subscribers.add(f);
}
void unsubscribe(Function f) {
subscribers.remove(f);
}
void publish() {
for (var f in subscribers) {
f();
}
}
}
class PublishingController with Publisher {}
... and how I called it:
child: Subscriber<MapController>(
builder: (controller) => Column(...
... with:
class MapController extends PublishingController {...
... but that gives me the error:
======== Exception caught by widgets library =======================================================
The following _TypeError was thrown building Subscriber<MapController>(dirty, state: _SubscriberState<MapController>#d7e05):
type '(MapController) => Column' is not a subtype of type '(PublishingController) => Widget'
I think I'm specifying the parameter type through the generics, and a function can return a subtype of its return type— what am I getting wrong here?
EDIT:
I got it working, but I'm not putting this in as an answer— I don't understand what the problem was, or why this version works; I changed my Subscriber class to:
abstract class Builder<P extends PublishingController> extends StatefulWidget {
const Builder({required this.builder, Key? key}) : super(key: key);
final Widget Function(P) builder;
}
class Subscriber<P extends PublishingController> extends Builder<P> {
const Subscriber({required builder, Key? key}) : super(builder: builder, key: key);
#override
_SubscriberState<P> createState() => _SubscriberState<P>();
}
Can someone explain why this change would make the difference?
Your _SubscriberState<P> class extends State<Subscriber>, which in your case is shorthand for State<Subscriber<PublishingController>>, not for State<Subscriber<P>>.
The static type of the _SubscriberState<P>'s inherited widget member therefore will be Subscriber<PublishingController>, and the static type of widget.builder will be Widget Function(PublishingController). At runtime, the associated Subscriber object has a reference to a Column Function(MapController) object. However, that cannot be treated as a Widget Function(PublishingController) since it does not accept all PublishingController arguments, so you end up with a runtime error.
See: Why am I getting TypeError at runtime with my generic StatefulWidget class?
Related
I am trying to access the 'updateNotesModel' variable declared in the code in the _UpdateNotesState. I found out that you can do it using the 'widget' keyword as shown in the Scaffold below. But the problem here is that I am trying to access the variable outside the build method in order to give the TextEditingController a default value. How can I achieve this?
class UpdateNotes extends StatefulWidget {
final NotesModel updateNotesModel;
UpdateNotes({Key key, this.updateNotesModel}): super(key: key);
#override
_UpdateNotesState createState() => _UpdateNotesState();
}
class _UpdateNotesState extends State<UpdateNotes> {
TextEditingController _titleController =
new TextEditingController(text: widget.updateNotesModel.someValue); //getting an error
}
#override
Widget build(BuildContext context) {
return Scaffold(
var a = widget.updateNotesModel.someValue
.
.
.
)
}
}
You can do it in initState:
class _UpdateNotesState extends State<UpdateNotes> {
TextEditingController _titleController = new TextEditingController();
#override
void initState() {
_titleController.text= widget.updateNotesModel.someValue;
super.initState();
}
}
Now you can use the late keyword. From the docs:
Dart 2.12 added the late modifier, which has two use cases:
Declaring a non-nullable variable that’s initialized after its declaration.
Lazily initializing a variable.
class _UpdateNotesState extends State<UpdateNotes> {
late TextEditingController _titleController = new TextEditingController(text: widget.updateNotesModel.someValue);
#override
Widget build(BuildContext context) {
.
.
.
}
}
that unfortunately cannot be done as, widget keyword cannot be accessed while initializing
In a Flutter projet, I saw this snippet: _State createState() => _State();
What does ClassName method() => ClassName() mean in Dart and where is the method createState() defined what does all of this mean for Flutter?
Here is the full code:
class Nearby extends StatefulWidget {
#override
_State createState() => _State();
}
class _State extends State<Nearby> {
GoogleMapController mapController;
LatLng _center;
#override
void initState() {
super.initState();
_getCurrentLocation();
}
#override
Widget build(BuildContext context) {
return Container()
}}
From the Dart language tour:
The => expr syntax is a shorthand for { return expr; }. The => notation is sometimes referred to as arrow syntax.
Therefore:
_State createState() => _State();
means that createState() is a function that invokes a _State constructor (with no arguments) and returns the newly constructed _State object.
As for what it means for Flutter, see the StatefulWidget.createState documentation:
Creates the mutable state for this widget at a given location in the tree.
Subclasses should override this method to return a newly created instance of their associated State subclass
(You also might want to look at the StatefulWidget documentation.)
Is there a way to pass one widget as a parameter to another?
My code has something similar to this with two TextWidget of type BoldWidget and ItalicWidget:
abstract class TextWidget extends StatelessWidget {
final String text;
TextWidget({
#required this.text,
});
}
class BoldWidget extends TextWidget {
#override
Widget build(BuildContext context) {
return Text(this.text, style: TextStyle(fontWeight: FontWeight.bold),);
}
}
class ItalicWidget extends TextWidget {
#override
Widget build(BuildContext context) {
return Text(this.text, style: TextStyle(fontStyle: FontStyle.italic),);
}
}
At runtime, I want to pass in either TextWidget as an argument to another widget (TextDisplay) like this:
class TextDisplay extends StatelessWidget {
final TextWidget widget;
final String string;
const TextDisplay({Key key, this.widget, this.string}) : super(key: key);
#override
Widget build(BuildContext context) {
return widget(string);
}
}
What doesn't work in the code above is widget(string), with error message "'widget' isn't a function".
How can I pass one widget as another argument so it can constructed by another class?
My actual code can't build the TextWidget before passing it to TextDisplay as TextDisplay needs to apply some of the arguments to the TextWidget.
You can use the CallBack pattern using typedef :
typedef CustomCallBack = TextWidget Function(String value);
class TextDisplay extends StatelessWidget {
final CustomCallBack widget;
final String string;
const TextDisplay({Key key, this.widget, this.string}) : super(key: key);
#override
Widget build(BuildContext context) {
return widget(string);
}
}
The demo example has the following code, which is apparently typical of Flutter apps:
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {...}
}
I'm OK, I guess, with MyHomePage overriding the StatefulWidget createState method. It's a little awkward but what the heck? And even depending on a State subclass. Fine.
But then having the State subclass turn around and depend on MyHomePage?! I'm having trouble wrapping my fairly abundant wits around that one.
So perhaps I'm unclear on what State<MyHomePage> is/does. With, say, Map<String, Object> the meaning is clear: Associate a string with an object. Can someone please elucidate? And if you could include something about the need for a state object to extend a widget, I would enjoy reading that.
This is to make widget properties access far easier.
When you do
new MyStatefulWidget(foo: 42, bar: "string")
Then you most likely want to access foo/bar from your State.
Without such syntax you'd have to type custom State constructor and pass all StatefulWidget subclass properties to State subclass inside createState. Basically you'd have that:
class MyStatefulWidget extends StatefulWidget {
final int foo;
MyStatefulWidget({this.foo});
#override
MyStatefulWidgetState createState() => MyStatefulWidgetState(foo: foo);
}
class MyStatefulWidgetState extends State<MyStatefulWidget> {
final int foo;
MyStatefulWidgetState({this.foo});
#override
Widget build(BuildContext context) {
return Container(
);
}
}
Boring. You have to write all fields of StatefulWidget subclass twice.
With the current syntax; you don't have to do this. You can directly access all properties of the currently instantiated widget within State by using widget field.
class MyStatefulWidgetState extends State<MyStatefulWidget> {
#override
Widget build(BuildContext context) {
print(widget.foo);
return Container();
}
}
In Flutter, everything is a widget and there are 2 types of widgets: Stateless and Statefull.
Stateless: A widget that does not require mutable state.
Statefull: A widget that has mutable state.
That is why all Statefull widget is dependent of a State<T>, because it manages changes (state) in the widget.
I am writing a base loadmore listview in flutter following the tutorial building-a-social-network-with-flutter:
Define a typedef function as a listview adapter, it return a widget for each item:
typedef Widget WidgetAdapter<T>(T t);
My base listview widget:
class LoadingListView<T> extends StatefulWidget{
...
final WidgetAdapter<T> widgetAdapter;
...
#override createState() => new _LoadingListViewState();
}
My base listview state:
class _LoadingListViewState<T> extends State<LoadingListView<T>> {
...
List<T> objects = [];
...
Widget itemBuilder(BuildContext context, int index) {
return widget.widgetAdapter != null ? widget.widgetAdapter(objects[index]);
: new Container();
}
}
In my UserList widget:
#override
Widget build(BuildContext context) {
Widget w;
w = new LoadingListView<User>(
request, widgetAdapter: adapt, pageSize: widget.pageSize, pageThreshold: widget.pageThreshold);
return w;
}
Widget adapt(User user){
return new UserItem(user); //return widget UserItem
}
And i am getting the error:
type '(User) => Widget' is not a subtype of type '(dynamic) => Widget'
How to fix it. Please help me. Thanks you very much.
There is a problem with createState() method in your StatefullWidget class.
Update your createState() method like this.
#override
State createState() => new _LoadingListViewState<T>()