Listview of item of StatefulWidget - flutter

Once the StatefulWidget dispose, (item out of screen) how to retrieve the state of the StatefulWidget?
I'm actually set a animatedlist but I think it's the same probleme. May be update the list might solved the probleme. But how?
I just want the same state.

You'll want the State that needs to be preserved to use AutomaticKeepAliveClientMixin.
Here's an example:
class Foo extends StatefulWidget {
#override
FooState createState() {
super.build(context);
return new FooState();
}
}
class FooState extends State<Foo> with AutomaticKeepAliveClientMixin {
#override
Widget build(BuildContext context) {
return Container(
);
}
#override
bool get wantKeepAlive => true;
}
Such Foo widget will preserve its state even if it leaves the screen inside a ListView

Related

Flutter what's StatefulHookWidget and how can we use it?

There quote is from Riverpod documentation:
A StatefulWidget that can use Hook
It's usage is very similar to StatefulWidget, but use hooks inside
State.build.
The difference is that it can use Hook, which allows HookWidget to
store mutable data without implementing a State.
besides this, I can't find any sample code or another tutorial or any description more than the quote.
in this simple HookWidget how can I implement that with StatefulHookWidget?
class MyHomePage extends HookWidget {
#override
Widget build(BuildContext context) {
final store = useMemoized(() => MyStore());
return Container();
}
}
A StatefulHookWidget is for when you need to use any of the overridable functions of a regular StatefulWidget - like didChangeDependencies, or initState, or dispose.
Generally, unless you have a really good or niche reason to use StatefulHookWidget, do prefer HookWidget.
Essentially, if we replicate your example, both Class1 and Class2 are equivalent in terms of the end product. The only difference is the verbiage needed to get there.
class Class1 extends HookWidget {
const Class1({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
final store = useMemoized(() => MyStore());
return Container();
}
}
class Class2 extends StatefulHookWidget {
const Class2({Key? key}) : super(key: key);
#override
_Class2State createState() => _Class2State();
}
class _Class2State extends State<Class2> {
#override
Widget build(BuildContext context) {
final store = useMemoized(() => MyStore());
return Container();
}
}
I am on the latest version of riverpod so I am using StatefulHookConsumerWidget
Following is one way to implement StatefulHookConsumerWidget. This might give you a hint for your answer
class MyHomePage extends StatefulHookConsumerWidget {
#override
_MyHomePage State createState() => _SocietyHomeState();
}
class MyHomePage extends ConsumerState<SocietyHome> {
Widget build(BuildContext context) {
return Container();
}
}

How to use ever() with Flutter getx variable in GetxController if I didn't add .obs

I am using Flutter getx package.
I know how to use "ever" with (.obs) variable like this
class CountController extends GetxController {
final count = 0.obs;
#override
void onInit() {
ever(count1, (_) => print("$_ has been changed"));
super.onInit();
}
}
But how to use "ever()" or triggering specific callbacks when variable change if the variable doesn't have (.obs) because I am using GetBuilder (not : Obx or GetX) in my view
class AnyScreen extends StatelessWidget {
final controller = Get.put(CounterController());
#override
Widget build(BuildContext context) {
ever(controller.counter, (value) => print("$value has been changed"));
}
#override
Widget build(BuildContext context) {
return Text("whatever!");
}
}
NOTE: Workers should always be used when starting a Controller or Class, so it should always be on onInit (recommended), Class constructor, or the initState of a StatefulWidget (this practice is not recommended in most cases, but it shouldn't have any side effects)
docs

How do I access an variable from a StatefulWidget inside an StatelessWidget?

How do I access the variable "selectedTag" from this statefulWidget:
class _AlertDialogOneState extends State<AlertDialogOne> {
Item selectedTag;
...
}
}
inside this statelessWidget :
class CardTile extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(...
Pass it as parameter,
class CardTile extends StatelessWidget {
final Item selectedTag;// Add this
CardTile(this.selectedTag); // Add this
#override
Widget build(BuildContext context) {
return Container(...
To pass this variable, you have multiple ways:
Pass it as a constructor when u navigate to this class using your navigator
Navigator.push(
context,
MaterialPageRoute(builder: (context) => CardTile(selectedTag)),
);
class CardTile extends StatelessWidget {
Item selectedTag;
CardTile(this.selectedTag);
#override
Widget build(BuildContext context) {
return Container(...
Use a state management like provider
class ProviderData with ChangeNotifier {
Item selected;
void changeSelection(newSelect) {
selected = newSelect;
changeNotifier();
}
}
and inside any class you need call this:
final providerData = Provider.of<ProviderData>(context);
so you can access the variable or change it using this instance like this:
final variable = providerData.selected;
providerData.changeSelection(newValue);
print(variable);
hope this help but i see that it is better to pass it through the constructor if you are not using a state managemnt, however i just gave you an example for illustration

Flutter: How can I avoid recreating the model for parts of the application?

My app uses a set of Card()s inside a PageView(), each card has multiple text lines.
The user gives input for each line (e.g. modifying the text etc.).
I want to keep this input for a while.
This is how my code looks at the moment, abstractly speaking:
class MyCard extends StatefulWidget {
final List<Widget> _myLines = [];
#override
State<StatefulWidget> createState() => MyCardState();
}
class MyCardState extends State<MyCard> {
...
#override
Widget build(BuildContext context) {
...
widget._myLines.add(ChangeNotifierProvider(
create: (context) => MyLineModel(context, lineText),
child: RecipeLine())
...
}
}
This doesn't work well:
As soon as I swipe left / right through the PageView onto other cards and then swipe back, the Card is being built again. This also leads to a rebuild of MyLineModel, which in turn erases all the user's input.
How can I avoid the rebuild of MyLineModel and keep the user's input?
You can solve this in 2 ways:
Create the model outside the widget and pass the model for the widget, as a variable to a constructor for example, or using Provider or any other technique of Dependency Injection.
Using any of the KeepAlive APIs, such as the AutomaticKeepAliveClientMixin as:
class MyCardState extends State<MyCard> with AutomaticKeepAliveClientMixin {
...
#override
bool get wantKeepAlive => true;
}
As the official documentation states, we can simply use the ChangeNotifierProvider.value() constructor...
In the original code:
class MyCardState extends State<MyCard> {
...
#override
Widget build(BuildContext context) {
...
widget._myLines.add(ChangeNotifierProvider.value(
value: MyLineModel(context, lineText),
child: RecipeLine())
...
}
}

Mount a new state in Flutter

I'm new to Flutter. I have made a stateful widget that has multiple options for states, and I have no clue how to switch between them, or if it's even possible. Basically I have:
class SWidget extends StatefulWidget {
State<StatefulWidget> createState(){
return _State1();
}
}
class _State1 extends State<SWidget> {
...
}
class _State2 extends State<SWidget> {
...
}
I want SWidget to switch from _State1 to _State2
Sorry if I don't understand your question but state is often tied to UI. If you need new state then chances are you're wanting to display something different. In that case, you'd want to distinguish the two states (and their UI components) by placing them in their own stateful widgets. You can then switch between the two widgets in a stateful or stateless widget:
class SWidget extends StatelessWidget {
SWidget(this.condition);
final bool condition;
#override
Widget build(BuildContext context) {
return condition ? Foo() : Bar();
}
}
class Foo extends StatefulWidget {
#override
_FooState createState() => _FooState();
}
class _FooState extends State<Foo> {
var _foo = 'foo';
#override
Widget build(BuildContext context) {
return Text(_foo);
}
}
class Bar extends StatefulWidget {
#override
_BarState createState() => _BarState();
}
class _BarState extends State<Bar> {
var _bar = 'bar';
#override
Widget build(BuildContext context) {
return Text(_bar);
}
}
I don't think I've ever seen anyone actually switch the state object out from underneath a widget. You can though easily change a widget's state by calling setState and toggling between values that way too:
class SWidget extends StatefulWidget {
#override
_SWidgetState createState() => _SWidgetState();
}
class _SWidgetState extends State<SWidget> {
var _value = true;
#override
Widget build(BuildContext context) {
return Switch(
value: _value,
onChanged: (value) => setState(() => _value = value),
);
}
}