Flutter: preserve state when changing body in Drawer - flutter

I am creating a Flutter application with a navigation drawer by using the Drawer class of the Material library. The Widget containing the Drawer is a StatefulWidget and the Scaffold's content is displayed according to the selected item on the navigation drawer. The content is either WidgetOne or WidgetTwo, both maintaining their own state as StatefulWidgets. See the code example below.
At the moment, when I change from one widget to another and back, the whole state of the earlier displayed widget is reloaded. This is not ideal, since both widgets have network calls from an API, and need to be redrawn accordingly.
What I've tried so far
Implementing AutomaticKeepAliveClientMixin on both sub widgets, as suggested here: https://stackoverflow.com/a/50074067/4009506. However, this does not seem to work.
Using an IndexedStack as suggested here: https://stackoverflow.com/a/54999503/4009506. This loads all widgets directly, even if they are not yet displayed.
Code
class DrawerWidget extends StatefulWidget {
#override
State<StatefulWidget> createState() => _DrawerState();
}
class _DrawerState extends State<DrawerWidget> {
Widget _activeWidget;
#override
void initState() {
_activeWidget = FirstWidget();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Drawer demo")),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
ListTile(
title: Text("First Widget"),
onTap: () {
setState(() {
_activeWidget = FirstWidget();
});
},
),
ListTile(
title: Text("Second Widget"),
onTap: () {
setState(() {
_activeWidget = SecondWidget();
});
},
),
],
),
),
body: _activeWidget);
}
}
class FirstWidget extends StatefulWidget {
// [..]
}
class SecondWidget extends StatefulWidget {
// [..]
}
Desired result
WidgetOne and WidgetTwo are only loaded on initial load (after selecting them in the Drawer). Switching to another widget and back should not reload the widget if it was already loaded earlier. The sub widgets should not load all directly, only when they are initially pressed.
Actual result
Both FirstWidget and SecondWidget are reloaded and redrawn each time they are selected in the Drawer.

I resolved this issue by using a PageView and implementing AutomaticKeepAliveClientMixin on all sub widgets:
class DrawerWidget extends StatefulWidget {
#override
State<StatefulWidget> createState() => _DrawerState();
}
class _DrawerState extends State<DrawerWidget> {
final _pageController = PageController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Drawer demo")),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
ListTile(
title: Text("First Widget"),
onTap: () {
_pageController.jumpToPage(0);
},
),
ListTile(
title: Text("Second Widget"),
onTap: () {
_pageController.jumpToPage(1);
},
),
],
),
),
body: PageView(
controller: _pageController,
children: <Widget>[
FirstWidget(),
SecondWidget()
],
physics: NeverScrollableScrollPhysics()
));
}
}
class FirstWidget extends StatefulWidget {
#override
State<StatefulWidget> createState() => _FirstWidgetState();
}
class _FirstWidgetState extends State<FirstWidget> with AutomaticKeepAliveClientMixin<FirstWidget> {
// [..]
#override
bool get wantKeepAlive => true;
}
class SecondWidget extends StatefulWidget {
#override
State<StatefulWidget> createState() => _SecondWidgetState();
}
class _SecondWidgetState extends State<SecondWidget> with AutomaticKeepAliveClientMixin<SecondWidget> {
// [..]
#override
bool get wantKeepAlive => true;
}
Now, all widgets are only loaded upon initial switch in the navigation drawer and do not get reloaded when switching back.

Related

How to change variable of a stateful widget from another widget?

How to change a variable of a Widget from another widget?
This is the main stateful widget called HomePage:
class _HomePageState extends State<HomePage> {
#override
num counter = 0;
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Title")),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [Text(counter.toString()), CardWidget()],
),
));
}
}
This is CardWidget which is added to HomePage:
class CardWidget extends StatefulWidget {
const CardWidget({Key? key}) : super(key: key);
#override
_CardWidgetState createState() => _CardWidgetState();
}
class _CardWidgetState extends State<CardWidget> {
#override
Widget build(BuildContext context) {
return Card(
child: Column(
children: [
Text("Press the button to increment the counter"),
ElevatedButton(
onPressed: () {
//Something here to increment the counter in HomePage
},
child: const Text('Increment'),
),
],
));
}
}
This is what is shown on the screen:
Is it possible to create a connection between the two widgets: if I tap the button something happens in the HomePage Widget? (similar to delegate in UIKit)
You can pass Function parameter.
In your CardWidget add Function parameter.
class CardWidget extends StatefulWidget {
//Add clicked function
final Function onClicked;
const CardWidget({Key? key, required this.onClicked}) : super(key: key);
#override
_CardWidgetState createState() => _CardWidgetState();
}
class _CardWidgetState extends State<CardWidget> {
int _count = 0;
#override
Widget build(BuildContext context) {
return Card(
child: Column(
children: [
Text("Press the button to increment the counter"),
ElevatedButton(
onPressed: () {
//Something here to increment the counter in HomePage
//Execute `onClicked` and pass parameter you want
_count++;
widget.onClicked(_count);
},
child: const Text('Increment'),
),
],
));
}
}
then on HomePage add onClicked parameter
class _HomePageState extends State<HomePage> {
#override
num counter = 0;
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Fontanelle")),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(counter.toString()),
CardWidget(
//Add onClicked
onClicked:(count){
print("Clicked "+count.toString());
}
)
],
),
));
}
}
You have some solution for this case:
1, Create GlobalKey for StatefullWidget, and you can access to State from HomePage
2, Create a Stream from Homepage and pass to StatefullWidget
3, Pass param to StatefullWidget and use didUpdateWidget on state to listen.
I remember that was my first question when did my first step in flutter, how say #dangngocduc is true but my advice is that read about BLOC
https://pub.dev/packages/flutter_bloc
This is very helpful to do this.

how to stop navigator to reload view?

I'm new to flutter and have a question about navigator.
I have 2 views one called Home and List. I created a drawer that is persistent in these two views. In each view I'm creating a reference to Firebase using FutureBuilder. The problem I'm running into is that every time I go to either Home or List initState is being called again. I believe the problem comes from selecting the page from the drawer. My question How can I still move to different pages without having to called InitState everytime I change screens.
title: Text('Go to page 1'),
onTap: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => Listdb()));
This is where I think the screen rebuilds itself. Is there a way to avoid rebuilding?
Thank you for your help!
You can use the AutomaticKeepAliveClientMixin to prevent reloading everytime you change page, combining with PageView for better navigation. I'll included an example here:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final PageController _pageController = PageController();
Widget build(BuildContext context) {
return Scaffold(
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
DrawerHeader(
child: Text('Drawer Header'),
decoration: BoxDecoration(
color: Colors.blue,
),
),
ListTile(
title: Text('Item 1'),
onTap: () {
_pageController.jumpToPage(0);
Navigator.pop(context);
},
),
ListTile(
title: Text('Item 2'),
onTap: () {
_pageController.jumpToPage(1);
Navigator.pop(context);
},
),
],
),
),
body: PageView(
controller: _pageController,
children: <Widget>[
PageOne(),
PageTwo(),
],
),
);
}
}
class PageOne extends StatefulWidget {
#override
_PageOneState createState() => _PageOneState();
}
class _PageOneState extends State<PageOne> with AutomaticKeepAliveClientMixin {
#override
void initState() {
print("From PageOne - This will only print once");
super.initState();
}
#override
bool get wantKeepAlive => true;
#override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
backgroundColor: Colors.red,
);
}
}
class PageTwo extends StatefulWidget {
#override
_PageTwoState createState() => _PageTwoState();
}
class _PageTwoState extends State<PageTwo> with AutomaticKeepAliveClientMixin {
#override
void initState() {
print("From PageTwo - This will only print once");
super.initState();
}
#override
bool get wantKeepAlive => true;
#override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
backgroundColor: Colors.blue,
);
}
}

How to change the page using Navigator.push so that the body and header animation is different, while the footer remains unchanged

I am trying to go to the next page using Navigator.push and at the same time change only the body on the page. I only got this when, for example, I wrap the index of page 2 in materialApp. But when I decided to make the animation (it smoothly pushes the old page to the left and pushes the new page to the right), it turned out that she pushed the old page, but behind it was exactly the same motionless page, which was later blocked by the new one.
I understood this in such a way that the first deleted page was an index 2 page, which is wrapped in MaterialApp, and behind it is exactly the same fixed MaterialApp for the entire application. At the moment, I have no idea how to remove a fixed page. I gave a picture of how I am currently navigating in the application, it may not be perfect, but I do not know better, any help would be appreciated.
In many applications, I see such an animation that the header fades out smoothly and at the same time a new one appears. And the body at this moment is replaced with the old page with a smooth movement, I really like it and I want to do the same.
You can try to use nested Navigator inside your scaffold.
Page index 1,2 and 3 will be inside the root Navigator under material app. Page 2 will contain another Navigator to fit your purpose.
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
final GlobalKey<NavigatorState> outgoingKey = GlobalKey<NavigatorState>();
return MaterialApp(
title: 'Sample',
home: Scaffold(
body: PageView(
children: <Widget>[
Page1(),
Page2(navigatorKey: outgoingKey,),
Page3(),
],
pageSnapping: false,
scrollDirection: Axis.horizontal,
physics: BouncingScrollPhysics(),
),
bottomNavigationBar: /*SomeBottomNavigationBar()*/,
),
);
}
}
class Page2 extends StatelessWidget {
Page2({Key key, this.navigatorKey}) : super(key: key);
final GlobalKey<NavigatorState> navigatorKey;
#override
Widget build(BuildContext context) {
return Container(
child: Column(children: [
Expanded(
child: Navigator(
key: navigatorKey, // you need to use this to pop i.e. navigatorKey.currentState.pop()
initialRoute: 'initialPageIndex2',
onGenerateRoute: (RouteSettings settings) {
WidgetBuilder _builder;
switch (settings.name) {
case 'nextPageForPageIndex2':
_builder = (context) => /*NextPageForPageIndex2()*/;
break;
case 'initialPageIndex2':
default:
_builder = (context) => /*InitialPageIndex2()*/;
}
return MaterialPageRoute(builder: _builder);
},
transitionDelegate: DefaultTransitionDelegate(),
);
)
],)
);
}
}
class Page1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
child: Text('Page1'),
);
}
}
class Page3 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
child: Text('Page3'),
);
}
}
You have to use the PageView please check the code below, hope it will help you :
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
void initState() {
// TODO: implement initState
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Basic AppBar'),
),
body: PageView(
children: <Widget>[
Page1(),
Page2()
],
pageSnapping: false,
scrollDirection: Axis.horizontal,
physics: BouncingScrollPhysics(),
),
);
}
}
class Page1 extends StatefulWidget {
#override
_Page1State createState() => _Page1State();
}
class _Page1State extends State<Page1> {
#override
Widget build(BuildContext context) {
return Container(
child: Center(child:Text("Page 1")),
color: Colors.red,
);
}
}
class Page2 extends StatefulWidget {
#override
_Page2State createState() => _Page2State();
}
class _Page2State extends State<Page2> {
#override
Widget build(BuildContext context) {
return Container(
child: Center(child:Text("Page 2")),
color: Colors.blueAccent,
);
}
}

Flutter - Update parant widget class UI on child button click

I have such kind of scenario
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Hello"),
),
body: Container(
child: ChildWidget(
listControl: this.sentToScreenBuildJson,
notifyParent: refresh,
),
),
);
}
this is my parent build method where I have added ChildWidget a another statfulscreen and passing is a json and a refresh funtion
as per json child will able to draw UI
and on button click I am able to get callback to refresh method.
refresh() {
print("I get refreshed from child");
setState(() {
print("I get refreshed from child in setState");
this.sentToScreenBuildJson = this.newJson;
});
}
on button click both print get execute but UI is not updating as per newJson.
Like I am expecting that as setState run parent has to call build with passing updated json.
which is not working.
thanks for any help.
When you want to pass data from Child to Parent you should use NotificationListener at parent and dispatch Notification from child.
Instance of Notification class will be having data that you can consume in Parent using NotificationListener.
Mostly all the Flutter Widgets are using this technique, for example tab controller receive OverscrollNotification when user reaches to the last tab and still try to swipe.
Following is the demo that you can use to understand how you can use NotificationListener in your code.
import 'package:flutter/material.dart';
void main() => runApp(ParentWidget());
class ParentWidget extends StatefulWidget {
ParentWidget({Key key}) : super(key: key);
#override
_ParentWidgetState createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
String _text = 'You have not pressed the button yet';
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: NotificationListener<IntegerNotification>(
onNotification: (IntegerNotification notification) {
setState(() {
print(notification);
_text = 'You have pressed button ${notification.value} times';
});
return true;
},
child: Column(
children: <Widget>[
Text(_text),
ChildWidget(),
],
)
),
),
);
}
}
class ChildWidget extends StatefulWidget {
const ChildWidget({Key key}) : super(key: key);
#override
_ChildWidgetState createState() => _ChildWidgetState();
}
class _ChildWidgetState extends State<ChildWidget> {
int _counter = 0;
#override
Widget build(BuildContext context) {
return RaisedButton(onPressed: (){
IntegerNotification(++_counter).dispatch(context);
},child: Text('Increment counter'),);
}
}
#immutable
class IntegerNotification extends Notification{
final int value;
const IntegerNotification(this.value);
String toString(){
return value.toString();
}
}
Update parant widget class UI on child button click
This is a common use case in flutter and flutter has built in InheritedWidget class for these kind of purpose. You may either directly use it for your purpose or use some ready made package solution which uses InheritedWidget behind the scenes like Provider.
An alternative to #Darish's answer, you can declare a static variable in your class 1, access that static variable in class 2 and then update the state of the variable in the class 2.
For example:
import 'package:flutter/material.dart';
class Demo extends StatefulWidget {
static UserObject userObject;
#override
_Demo createState() => _Demo();
}
class _Demo extends State<Demo> {
#override
void initState() {
Demo.userObject = new UserObject(name: "EXAMPLE NAME");
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xfff3f3f3),
appBar: AppBar(title: Text("DEMO")),
body: InkWell(
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => HeroClass()));
},
child: Center(
child: Hero(
tag: "tag-demo-id",
child: Container(
color: Colors.black,
padding: EdgeInsets.all(20),
child: Text("${Demo.userObject.name} -> CLICK HERE",
style: TextStyle(color: Colors.white)))))));
}
}
class HeroClass extends StatefulWidget {
#override
_HeroClassState createState() => _HeroClassState();
}
class _HeroClassState extends State<HeroClass> {
final myController = TextEditingController();
#override
void initState() {
myController.text = Demo.userObject.name;
super.initState();
}
#override
void dispose() {
// Clean up the controller when the widget is removed from the widget tree.
// This also removes the _printLatestValue listener.
myController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("DEMO HERO")),
body: Hero(
tag: "tag-demo-id",
child: Container(
child: TextField(
controller: myController,
),
)),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
Demo.userObject.name = myController.text;
});
},
child: Icon(Icons.save),
));
}
}
// object class
class UserObject {
String name;
UserObject({this.name});
UserObject.fromJson(Map<String, dynamic> json) {
name = json['name'];
}
}

How to use `GlobalKey` to maintain widgets' states when changing parents?

In Emily Fortuna's article (and video) she mentions:
GlobalKeys have two uses: they allow widgets to change parents
anywhere in your app without losing state, or they can be used to
access information about another widget in a completely different part
of the widget tree. An example of the first scenario might if you
wanted to show the same widget on two different screens, but holding
all the same state, you’d want to use a GlobalKey.
Her article includes a gif demo of an app called "Using GlobalKey to ReuseWidget" but does not provide source code (probably because it's too trivial). You can also see a quick video demo here, starting at 8:30 mark: https://youtu.be/kn0EOS-ZiIc?t=510
How do I implement her demo? Where do I define the GlobalKey variable and how/where do I use it? Basically for example, I want to display a counter that counts up every second, and have it on many different screens. Is that something GlobalKey can help me with?
The most common use-case of using GlobalKey to move a widget around the tree is when conditionally wrapping a "child" into another widget like so:
Widget build(context) {
if (foo) {
return Foo(child: child);
}
return child;
}
With such code, you'll quickly notice that if child is stateful, toggling foo will make child lose its state, which is usually unexpected.
To solve this, we'd make our widget stateful, create a GlobalKey, and wrap child into a KeyedSubtree.
Here's an example:
class Example extends StatefulWidget {
const Example({Key key, this.foo, this.child}) : super(key: key);
final Widget child;
final bool foo;
#override
_ExampleState createState() => _ExampleState();
}
class _ExampleState extends State<Example> {
final key = GlobalKey();
#override
Widget build(BuildContext context) {
final child = KeyedSubtree(key: key, child: widget.child);
if (widget.foo) {
return Foo(child: child);
}
return child;
}
}
I would not recommend using GlobalKey for this task.
You should pass the data around, not the widget, not the widget state. For example, if you want a Switch and a Slider like in the demo, you are better off just pass the actual boolean and double behind those two widgets. For more complex data, you should look into Provider, InheritedWidget or alike.
Things have changed since that video was released. Saed's answer (which I rewarded 50 bounty points) might be how it was done in the video, but it no longer works in recent Flutter versions. Basically right now there is no good way to easily implement the demo using GlobalKey.
But...
If you can guarantee that, the two widgets will never be on the screen at the same time, or more precisely, they will never be simultaneously inserted into the widget tree on the same frame, then you could try to use GlobalKey to have the same widget on different parts of the layout.
Note this is a very strict limitation. For example, when swiping to another screen, there is usually a transition animation where both screens are rendered at the same time. That is not okay. So for this demo, I inserted a "blank page" to prevent that when swiping.
How to:
So, if you want the same widget, appearing on very different screens (that hopefully are far from each other), you can use a GlobalKey to do that, with basically 3 lines of code.
First, declare a variable that you can access from both screens:
final _key = GlobalKey();
Then, in your widget, have a constructor that takes in a key and pass it to the parent class:
Foo(key) : super(key: key);
Lastly, whenever you use the widget, pass the same key variable to it:
return Container(
color: Colors.green[100],
child: Foo(_key),
);
Full Source:
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(home: MyApp()));
}
class MyApp extends StatelessWidget {
final _key = GlobalKey();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Global Key Demo")),
body: PageView.builder(
itemCount: 3,
itemBuilder: (context, index) {
switch (index) {
case 0:
return Container(
color: Colors.green[100],
child: Foo(_key),
);
break;
case 1:
return Container(
color: Colors.blue[100],
child: Text("Blank Page"),
);
break;
case 2:
return Container(
color: Colors.red[100],
child: Foo(_key),
);
break;
default:
throw "404";
}
},
),
);
}
}
class Foo extends StatefulWidget {
#override
_FooState createState() => _FooState();
Foo(key) : super(key: key);
}
class _FooState extends State<Foo> {
bool _switchValue = false;
double _sliderValue = 0.5;
#override
Widget build(BuildContext context) {
return Column(
children: [
Switch(
value: _switchValue,
onChanged: (v) {
setState(() => _switchValue = v);
},
),
Slider(
value: _sliderValue,
onChanged: (v) {
setState(() => _sliderValue = v);
},
)
],
);
}
}
Update: this was an old approach to tackle the state management and not recommended anymore,please see my comments on this answer and also check user1032613's answer below
Global keys can be used to access the state of a statefull widget from anywhere in the widget tree
import 'package:flutter/material.dart';
main() {
runApp(MaterialApp(
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: App(),
));
}
class App extends StatefulWidget {
#override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
GlobalKey<_CounterState> _counterState;
#override
void initState() {
super.initState();
_counterState = GlobalKey();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
children: <Widget>[
Counter(
key: _counterState,
),
],
)),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.navigate_next),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) {
return Page1(_counterState);
}),
);
},
),
);
}
}
class Counter extends StatefulWidget {
const Counter({
Key key,
}) : super(key: key);
#override
_CounterState createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int count;
#override
void initState() {
super.initState();
count = 0;
}
#override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () {
setState(() {
count++;
});
},
),
Text(count.toString()),
],
);
}
}
class Page1 extends StatefulWidget {
final GlobalKey<_CounterState> counterKey;
Page1( this.counterKey);
#override
_Page1State createState() => _Page1State();
}
class _Page1State extends State<Page1> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Row(
children: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: () {
setState(() {
widget.counterKey.currentState.count++;
print(widget.counterKey.currentState.count);
});
},
),
Text(
widget.counterKey.currentState.count.toString(),
style: TextStyle(fontSize: 50),
),
],
),
),
);
}
}