Passing data to a State from his Statefulwidget - flutter

this is my code and i want to access to "initialValue" propierty from the StatefulWudget but for some reason marks a error in counter = widget.initialValue
the image with the error from vs code.
I'm following a course and i don't know if something change in the new versions, cause all the questions that i found use the same code.
class MyCounter extends StatefulWidget{
final int initialValue;
const MyCounter({Key? key, this.initialValue = 0}) : super(key: key);
#override
State createState(){ //puede ser lamda => MyCounterState();
return MycounterState();
}
}
class MycounterState extends State{
int counter = 0;
#override
void initState() {
// TODO: implement initState
super.initState();
counter = widget.initialValue;
}
...
Or do i have an error in a different part of the code?

for someone with the same problem the solution(found in the discord offical flutter server) was
"Your state must have a type argument containing the widget"
class MyCounter extends StatefulWidget{
final int initialValue;
const MyCounter({Key? key, this.initialValue = 0}) : super(key: key);
#override
State<MyCounter> createState(){ //puede ser lamda => MyCounterState();
return MycounterState();
}
}
class MycounterState extends State<MyCounter>{
int counter = 0;
#override
void initState() {
// TODO: implement initState
super.initState();
counter = widget.initialValue;
}
just need to change State to State<MyCounter> in the "createState()" from MyCounter class and the "extends State{" from MyCounterState class

Related

how to use a data transfer from the parent widget?

Here is the child class that receives from its parent the index data that identifies the box to modify
class InformationPatient extends StatefulWidget {
final Patients patients;
final int index;
const InformationPatient(this.patients, this.index, {Key? key})
: super(key: key);
#override
State<InformationPatient> createState() => _InformationPatientState();
}
class _InformationPatientState extends State<InformationPatient> {
final int indexitem = 0;
late Box<Patients> boxPatient;
#override
void initState() {
super.initState();
boxPatient = Hive.box('Patient');
}
void _addNote(String newtitle, String newnote, String newconclusion) {
final newNOTE = Patients(
listOfNotes: [
ListNote(title: newtitle, note: newnote, conclusion: newconclusion)
],
);
boxPatient.put(indexitem, newNOTE);
Navigator.of(context).pop();
}
This way works but I don't have the index of the parent, I give it to him
final int indexitem = 0; <--- Works perfectly with my function patientbox.put() it receives the index
boxPatient.put(indexitem, newNOTE);
I would like to give indexbox the value of index but I don't know how to do it or if there is another way
final int indexitem = ??? <---- add the value of index
boxPatient.put(indexitem, newNOTE);
obviously I can't use index directly in the function boxPatient.put()
Thank you very much for your help
To read variables from the widget inside the state, you can simply refer to widget.<variable>. So in your example
boxPatient.put(widget.index, newNOTE);

LateInitializationError: Field 'authProvider' has not been initialized

I got the error LateInitializationError: Field 'authProvider' has not been initialized. for the following:
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
#override
State createState() => HomePageState();
}
class HomePageState extends State<HomePage> {
final FirebaseMessaging firebaseMessaging = FirebaseMessaging.instance;
final ScrollController listScrollController = ScrollController();
late AuthProvider authProvider;
String? currentUserId;
late MainProvider mainProvider;
Debouncer searchDebouncer = Debouncer();
StreamController<bool> btnClearController = StreamController<bool>();
TextEditingController searchBarTec = TextEditingController();
#override
void initState() {
super.initState();
mainProvider = context.read<MainProvider>();
if (authProvider.getUserFirebaseId()!.isNotEmpty == true) {
currentUserId = authProvider.getUserFirebaseId()!;
} else {
return null;
}
registerNotification();
listScrollController.addListener(scrollListener);
}
//more code below
This code is from a Demo: Chat App with Flutter
How do I initialize the fields for authProvider, mainProvider etc?
Late initialization error means that a variable marked as late (in your case authProvider) was not initialized before it was accessed.
on a widget the first thing you execute is the constructor and then you execute the initstate. your constructor has nothing and initstate reads authProvider.getUserFirebaseId().
If you take a look at the video's github page, you will see that before calling authProvider, they initialize it by running the following line:
authProvider = context.read<AuthProvider>();
homeProvider = context.read<HomeProvider>();
If you are following a tutorial, the tutorial is either outdated or not complete if it has this sort of error.

Uri.parse('https://www.a2rstore.in/api/school/v1/noticeApi.php?id=${widget.s_id}'); got error on widget.s_id

class Notice extends StatefulWidget {
final String s_id;
const Notice({Key key, this.s_id}) : super(key: key);
#override
_NoticeState createState() => _NoticeState();
}
class _NoticeState extends State<Notice> {
TextEditingController _titleController = new TextEditingController();
var api =
Uri.parse('https://www.a2rstore.in/api/school/v1/noticeApi.php?id=${widget.s_id}');
You can't call the "widget" without the context.
The proper way to do it is by first defining your variable:
class _NoticeState extends State<Notice> {
TextEditingController _titleController = new TextEditingController();
var api;
...
}
And then assigning to it the value either in the build or initState method:
#override
initState(){
api = Uri.parse('https://www.a2rstore.in/api/school/v1/noticeApi.php?id=${widget.s_id}');
}

Stateful widget, class marked #immutable

I got a Visual Studio warning on my class (below) saying "This class (or a class which this class inherits from) is marked as '#immutable', but one or more of its instance fields are not final: UserSignIn._email", but I cannot mark this argument as final because I initialise it in the constructor
Without final :
class UserSignIn extends StatefulWidget {
TextEditingController _email;
UserSignIn({String emailInput}) {
this._email = TextEditingController(text: (emailInput ?? ""));
}
#override
_UserSignInState createState() => _UserSignInState();
}
class _UserSignInState extends State<UserSignIn> {
#override
Widget build(BuildContext context) {
...
}
}
How to do this ?
Thank you
You should put the TextEditingController in the state class and initialise it in the initState method, like this.
And keep in mind that the StatefulWidget can be different every time when the widget tree is changed, so don't put anything in there that is not immutable.
Keep everything dynamic in the State class
class UserSignIn extends StatefulWidget {
final String emailInput;
const UserSignIn({Key key, this.emailInput}) : super(key: key);
#override
_UserSignInState createState() => _UserSignInState();
}
class _UserSignInState extends State<UserSignIn> {
TextEditingController _controller;
#override
void initState() {
_controller = TextEditingController(text: widget.emailInput);
super.initState();
}
...
}

flutter - clear the widget cache

When I leave a page when I work with flutter and then re-enter it, the old values are saved.
I don't want this to happen.
For example, when I first enter:
int number = 1;
class TestPage extends StatefulWidget {
#override
_TestPageState createState() => _TestPageState();
}
bool donus = true;
class _TestPageState extends State<TestPage> {
List<Todo> sorular = new List<Todo>();
#override
void initState() {
print(donus);
super.initState();
getTodos();
}
bool pressAttention = true;
String ileri = "İleri", geri = "Geri";
#override
Widget build(BuildContext context) {number++;
print(number);
output:1
Second entry to the page:
output:2
I do not know how to fix this.
The scope of your number variable is outside the scope of your page and its state.
number is essentially static or global, and its lifetime is tied to your application's. Tighten up its scope so that it is declared within your state class and initialise it in your initState method (for private non-final variables).
class TestPage extends StatefulWidget {
#override
_TestPageState createState() => _TestPageState();
}
bool donus = true;
class _TestPageState extends State<TestPage> {
List<Todo> sorular = new List<Todo>();
int _number;
#override
void initState() {
_number = 1;
print(donus);
super.initState();
getTodos();
}
bool pressAttention = true;
String ileri = "İleri", geri = "Geri";
#override
Widget build(BuildContext context) {
_number++; // You probably don't want to increment every time you build,
// but I have no idea what you're using `number` for.
print(_number);
Your donus variable is also global, which is unlikely to be what you had intended. Dart is an object-oriented language; refer to the language tour for more details on classes, scope, etc.