When I try to use setState()
inside of a custom function that I have defined it says that "setState() isn’t defined" even though I have ‘flutter/material.dart’ package imported:
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:smooth_like_flutter/components/service_field.dart';
void showCustomDialog(
BuildContext context,
) {
var number = 10;
showDialog(
context: context,
builder: (BuildContext context) {
return Column(
children: [
Text(
number,
style: TextStyle(color: Colors.grey[700]),
),
MyServiceField(
hint: 'hello',
onChange: (fieldData) {
var fieldNum = int.parse(fieldData);
setState( // The function 'setState' isn't defined.
number = fieldNum
);
},
),
],
);
});
}
This code is to only give a general idea of what I’m trying to achieve, if need be, I can upload the entire code
i’ve tried importing material.dart
2
Answers
It is possible to call setState method when you’re inside a StatefulWidget but not outside it, unless you pass a callback.
At this point you could extract the widget inside the dialog into a statefulwidget:
and use it in the dialog as follows:
setState’s role is to update the UI of a screen/widget. You can use setState inside a function but it has to be inside a stateful class. Stateful class allows you to rebuild your user interface. In your code, you have declared the function outside a statefulwidget class. What you can do is:-