Accessing members of a stateful widget in a pageview - flutter

I have a screen in my Flutter app that contains a pageview. In that pageview are four stateful widgets. I need to be able to access the members of the first three widgets so I can get the data from them, bring it into the main screen class, and send it to the fourth widget. Below is a model of what I'm trying to accomplish.
I'm thinking that I can do this with methods in each widget's state class but when I create a method there, I can't access it anywhere else even if it's public.
An example of one of the widgets:
import 'package:flutter/material.dart';
class WidgetSample extends StatefulWidget {
#override
_WidgetSampleState createState() => _WidgetSampleState();
}
class _WidgetSampleState extends State<WidgetSample> {
TextEditingController _sampleController = new TextEditingController();
//I want to access this method through an instance of the WidgetSample class
String getTextFromField(){
return _sampleController.text;
}
#override
Widget build(BuildContext context) {
return Container(
child: TextField(
controller: _sampleController,
),
);
}
}
I have tried creating a copy of the method in the widget sample class that calls the method in the state class but that hasn't worked.
Any help would be appreciated. Thanks in advance!

Edit: I have found an answer to my problem provided by BambinoUA on this post:
Controlling State from outside of a StatefulWidget

Related

what does it mean when we see people calling widget in dart?

I have seen many times people calling widget. sth inside the code.
May I know what it is actually doing?
For example code below, (highlighted part is my confusion)
class _MyOwnClassState extends State<MyOwnClass> {
#override
Widget build(BuildContext context) {
return ListTile(
title: Container(
child: Column(children: makeWidgetChildren(**widget.jsonObject)**),
),
);
}
}
In flutter's StatefulWidget, we have the following architecture.
You have a StatefulWidget like this,
class MyOwnClass extends StatefulWidget {
State createState () => _MyOwnClassState();
}
And you have a State class for your StatefulWidget like this,
class _MyOwnClassState extends State<MyOwnClass> {
}
Now, State class is meant to house variables that tend to change in order for your UI to be rebuilt.
So you can have variables in your State that you can update using setState.
But what if you had some data that doesn't change and you want to avoid putting them inside the State class.
That's where your StatefulWidget comes to play.
You can store variables in your MyOwnClass and the widget variable inside the State class gives you a way to access them.
For example,
class MyOwnClass extends StatefulWidget {
int numberThatDoesntChange = 1;
State createState () => _MyOwnClassState();
}
You can access them in your State class like this,
class _MyOwnClassState extends State<MyOwnClass> {
Widget build(BuildContext context) {
return Text('$widget.numberThatDoesntChange');
}
}
Apart from this, your StatefulWidget has many more internal instance members that you can access inside of your State class using the widget variable.
The widget refers to the actual view that renders on the screen. It extends the StatefulWidget class of the flutter framework and overrides the createState() method. The createState() method is used to create the instance of state class. We will look into createState().
The state class is used to maintain the state of the widget so that it can be rebuilt again. It extends the State class of the flutter framework and overrides the build method.
The framework calls build() method again and again whenever setState() method is called. The setState() method notifies the framework that the internal state of this object has changed and it should be rebuilt. Suppose we change the value of text in StatefulWidget then we need to call setState().
Edit As Nisanth pointed outh in his comment - I missed your question completely; please ignore the below....
Let me try my answer, I don't think others are getting your point.
In your exapmle, Column(children: x) expect a list of Widgets.
You have two options - either provide this list directly:
class _MyOwnClassState extends State<MyOwnClass> {
#override
Widget build(BuildContext context) {
return ListTile(
title: Container(
child: Column(children: <Widget>[SomeWidget()]),
),
);
}
}
Or if you have more complex code that generates widget - based on input parameters, or you have the same widget generated multiple times and you want to avoid the code duplication - you would create the separate function to do the job.
Something like:
class _MyOwnClassState extends State<MyOwnClass> {
List<Widget> makeWidgetChildren(int param) {
/*
some very complex logic here
/*
if (param>3 && param<4) {
return List<Widget>.generate(4, (index)=>SomeWidget1(index));
} else {
return <Widget>[Center()];
}
}
#override
Widget build(BuildContext context) {
return ListTile(
title: Container(
child: Column(children: makeWidgetChildren(**widget.jsonObject)**),
),
);
}
}
So basically, it is just to make the code nicer; and to avoid having code repeated over and over again in the build function.

How to use Provider/Consumer when extending a class

To start, I'm new to Flutter, so I am completely open to the possibility that my problem stems from a fundamental misunderstanding, but here is my question:
I am trying to get a good understanding of how to use Provider in conjunction with with the get_it package.
I think I understand how to use the Provider pattern in the standard case, by which I mean creating a unique class with a view and a view_model. Where I seem to have become lost is when I design a custom widget as a base template class and then extend that widget so that it can be tailored for use in a specific class view, I'm not seeing how to connect it to the Provider pattern because the base class doesn't know in advance which view_model it needs to listen to.
Below I will provide short example of what I am doing in the standard case, where things seem to work fine, and then I will show a short example of how I am trying to build the custom widget and extend it...
Here is the sample standard way in which I am using the Provider pattern with get_it, in which everything seems to work just fine:
class MyScreenView extends StatefulWidget{
#override
_ProfileEditScreenViewState createState() => _ProfileEditScreenViewState();
}
class _MyScreenViewState extends State<MyScreenView>{
final MyScreenViewModel model = serviceLocator<MyScreenViewModel>();
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider<MyScreenViewModel>(
create: (context) => model,
child: Material(
color: Colors.white,
child: Consumer<MyScreenViewModel>(
builder: (context,model,child) => Text(model.someText),
),
),
);
}
}
class MyScreenViewModel extends ChangeNotifier{
String? _someText;
MyScreenViewModel() {
this._someText= 'Sample Text';
}
String get someText=> _someText;
set someText(String value) {
_someText= value;
notifyListeners();
}
}
Here is an example of how I am trying to build a base class, but am uncertain as to how I go about connecting it to Provider: (The idea here is that the below widget would be part of a more complex widget that would have a view_model where the state for the overall widget would be maintained)
class BaseCheckBoxTile extends StatefulWidget{
bool isChecked;
Function(bool) checkBoxOnChanged;
BaseCheckBoxTile({this.isChecked = false, required this.checkBoxOnChanged});
#override
_BaseCheckBoxTileState createState() => _BaseCheckBoxTileState();
}
class _BaseCheckBoxTileState extends State<BaseCheckBoxTile>{
#override
Widget build(BuildContext context) {
return SizedBox(
child: Checkbox(value: widget.isChecked,onChanged: widget.checkBoxOnChanged,),
);
}
}
class CustomCheckBoxTile extends BaseCheckBoxTile{
bool isChecked;
Function(bool) checkBoxOnChanged;
CustomCheckBoxTile({this.isChecked =false, required this.checkBoxOnChanged})
:super(isChecked: isChecked, checkBoxOnChanged: checkBoxOnChanged);
}
My instinct is to want to put something in my _BaseCheckBoxTileState that gives me access to the larger widget's view_model, like what I do in the first example with:
"MyScreenViewModel model = serviceLocator<MyScreenViewModel>(); "
If I had that, then I could assign the values in my _BaseCheckBoxTileState by referring to the model instead of widget (e.g., model.isChecked instead of widget.isChecked). The model would obviously extend ChangeNotifier, and the view that is making use of the custom widget would wrap the widget in a Consumer. However, the _BaseCheckBoxTileState doesn't know what view_model to listen to.
Would I accomplish this by putting some generic Type or Object in for my View_Model which could be assigned when the class is built? Or am I approaching this in a completely wrong way?

Assign value of TextEditingController inside buildMethod

i have some questions about which is the correct way of creating TexEditingController;
Assuming that i want to create a controller with a fixed text, so i can do like this :
TextEditingController bioEditorController = new TextEditingController(text:"dummy");
Now my questions is this:
if i'm usign a stateful widget i can create this controller ad assign an initial text by doing this :
TextEditingController bioEditorController;
#override
void initState() {
bioEditorController = new TextEditingController(text: "dummy");
super.initState();
}
but if i'm not using a stateful widget is it correct to make something like this :
#override
Widget build(BuildContext context) {
TextEditingController bioEditorController =
new TextEditingController(text: controller.profile.value.bio);
What i mean is it correct to create this controller inside the build method, if i do like this it works , but i think that probably is not the best way of doing this things, also becauze i know that controller should also disposed....
I really need some help about clarifying this. Thanks
You are correct in assuming that doing that in the build method is not ideal. You have way less control over how many times the build method runs vs initState.
And while it's generally true that you would need a stateful widget when dealing with TextEditingControllers (or hooks), if you use GetX state management it's absolutely fine, and preferred to not bother with a stateful widget just because you need a TextEditingController.
Another benefit of this way is very easy access to the value of the TextEditingController from anywhere else in the app.
Here's a quick example. This is a class where you can keep all your TextEditingControllers.
class TextController extends GetxController {
RxString textfieldString = ''.obs; // observable String
TextEditingController textController;
// this onInit replaces initState of a stateful widget
#override
onInit() {
super.onInit();
textController = TextEditingController(text: 'dummy');
// adding a listener that automatically updates the textfieldString with the textfield value
textController.addListener(() {
textfieldString.value = textController.text;
debugPrint(textfieldString.value);
});
}
}
Initialize the controller in your main or anytime before you actually use it. This is when the onInit from that class is called.
Get.put(TextController()).textController;
Here's Page1 a stateless widget with an already initialized TextEditingController
class Page1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
final controller = Get.find<TextController>(); // finding same initialized controller
return Scaffold(
body: Center(
child: TextFormField(
controller: controller.textController, // using TextEditingConroller from GetX class
),
),
);
}
}
And here's a quick example of a text widget on a different page automatically updating anytime the user types into the TextFormField
class Page2 extends StatelessWidget {
#override
Widget build(BuildContext context) {
final controller =
Get.find<TextController>(); // finding same instance of controller
return Scaffold(
body: Center(
// this Obx widget rebuilds based on any updates
child: Obx(
() => Text(controller.textfieldString.value),
),
),
);
}
}
So no matter where you are in your app, you can access the value of that TextFormField and you don't have to use a stateful widget. The GetxController will be removed from memory when not in use.
At this point the only time I ever need to use a stateful widget is when I need the AutomaticKeepAliveClientMixin.
Even animations can be done with stateless widgets in GetX by adding SingleGetTickerProviderMixin to a Getx class and doing everything there that would normally clutter up your stateful widget.

Flutter and GetxController - How to manage state unreliability?

I currently have many problems in my app with the get package for Flutter (https://pub.dev/packages/get) and the following state scenario:
For example I have a GetxController UserController. I need this controller in different Widgets, so I initialize it with Get.put() in the first widget and for the other child widgets I'll call it with Get.find(). That works.
But: I have some widgets that sometimes load before the controller got initialized and sometimes after. So I get many "UsersController" not found errors. Maybe there exists some workaround for this problem?
You could initialize your UsersController class using a Bindings class, prior to the start of your app.
Example
class UsersController extends GetxController {
static UsersController get i => Get.find();
int userId = 5;
}
class UsersBinding extends Bindings {
#override
void dependencies() {
Get.put<UsersController>(UsersController());
}
}
void main() async {
UsersBinding().dependencies();
runApp(MyApp());
}
Done this way your UsersController is guaranteed to be available everywhere in your app, prior to any Widgets loading.
class MyHomePage extends StatelessWidget {
final UsersController uc = Get.find();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('GetX Bindings'),
),
body: Center(
child: Obx(() => Text('userId: ${uc.userId}')),
),
);
}
}
try to add
GetMaterialApp(
smartManagement: SmartManagement.keepFactory,
)
so that it can store factory of those instanse
or make sure add permanent
Get.put<Repo>(Repo(), permanent: true);
so that it never get deleted from memory
if u need to check class is initialized, u most keep the class in memory with permanent:trueand set tag:'anything you want for check this object' property in Get.put function, and now u can check
bool Get.isRegistered<className>(tag: 'TagInPut')
If there's no specific reason, you can just call Get.put(UserController()) at main function and wrap material app with GetMaterialApp.
if you are using get to provide an instance of something across your app
meaby https://pub.dev/packages/get_it could help you more. just be sure that you use allowReassignment==true so you can update your instance if you want save a full new controller, but if you want to use the same always get_it is perfect for you

Flutter - Calling methods from one child class to another child class

I just got calling methods from a child class working with help from someone in this thread.
What I am trying to do now, and I am not sure if it is different, is call a method in one child from another child of the same parent.
So visually:
Parent class
- Method()
^
|
Child class
In the above, I can easily access the Parent class method from the child class using the callback function in the link provided above.
This does not appear to work in the below structure, and I can't figure this out from any of the threads I have read on calling methods from other classes:
Parent class
| |
Child class 1 Child class 2
- Method() <-- callback
Is the procedure for this structure handled differently? Is it possible or can you only ever callback to a parent method?
Although I think, in flutter, it would be better to use state changes to update/trigger calls on UI widgets, but for your speciffic case, the delegate pattern can work. Here's an example of I would do it.
abstract class TheTrigger { // you can use VoidCallback or whatever, this is just for the demo
void triggerMe();
}
class ChildOneWidget extends StatelessWidget with TheTrigger {
#override
Widget build(BuildContext context) {
return Container(); // add the content of the child one
}
#override
void triggerMe() {
// TODO: implement triggerMe
}
}
class ChildTwoWidget extends StatelessWidget {
final TheTrigger trigger;
const ChildTwoWidget({Key key, this.trigger}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
//something here that will trigger "the trigger"
child: RaisedButton(onPressed: () {
trigger?.triggerMe(); // you should use the "?" this will allow a bit more customisation on your widgets, you might want to use it without listener.
}),
);
}
}
class ParrentWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
ChildOneWidget childOneWidget = ChildOneWidget();
ChildTwoWidget childTwoWidget = ChildTwoWidget(trigger: childOneWidget); // here you set the "delegate"
return ListView(
children: <Widget>[childOneWidget, childTwoWidget],
);
}
}
One more time, this is just a dumb example on how you can do it, but I would strongly recommend to use state to trigger changes on children, you'll have a more flexible widget tree.
The way flutter widgets work is that the children widgets in your case are in the parents widget tree. On the callback of Child class 2 you can use setState to rebuild your parent and thus rebuild any of its children, for example by changing the value of a parameter in Child class 1