BuildContext: the meaning of nearest enclosing? - flutter

I'm reading the docs: https://docs.flutter.io/flutter/widgets/BuildContext-class.html
This can lead to some tricky cases. For example, Theme.of(context) looks for the nearest enclosing Theme of the given build context. ...
Does enclosing includes the Theme of current context? I don't understand what the tricky cases the author indicated.

The tricky situation they mentioned becomes more clear if you understand the previous statement:
In particular, this means that within a build method, the build context of the widget of the build method is not the same as the build context of the widgets returned by that build method.
Ok, not a very helpful language. Imagine:
FooWidgetA:
attributes: context, height, width
methods: build
FooWidgetB:
attributes: context, theme
methods: build
FooWidgetB gets built inside FooWidgetA build method. If you try to find theme using the context of FooWidgetA it won't find because FooWidgetA is one level above in the widget tree.
So, exemplifying their tricky situation, it looks like this:
class Foo extends StatelessWidget {
#override
Widget build(BuildContext buildMethodContext) {
return MaterialApp(
// Here we create the [ThemeData] that our method below will try to find
theme: ThemeData(primaryColor: Colors.orange),
builder: (BuildContext materialAppContext, _) {
return RaisedButton(
child: const Text('Get ThemeData'),
onPressed: () {
getThemeData(buildMethodContext); // unsucessful
getThemeData(materialAppContext); // sucessful
},
);
},
);
}
ThemeData getThemeData(BuildContext context) => Theme.of(context);
}
It's tricky because, since the two contexts are way to close, it's easy to forget that buildMethodContext is actually from the parent (Foo), so it cannot see materialAppContext.

Related

Triggering Widget Rebuilds with Provider's context.read<T>() Method

According to Flutter's documentation and this example, as I'm understanding it, a key difference between the Provider package's context.read<T> and context.watch<T> methods relate to triggering widget rebuilds. You can call context.watch<T>() in a build method of any widget to access current state, and to ask Flutter to rebuild your widget anytime the state changes. You can't use context.watch<T>() outside build methods, because that often leads to subtle bugs. Instead, they say, use context.read<T>(), which gets the current state but doesn't ask Flutter for future rebuilds.
I tried making this simple app:
class MyDataNotifier extends ChangeNotifier {
String _testString = 'test';
// getter
String get testString => _testString;
// update
void updateString(String aString) {
_testString = aString;
notifyListeners();
}
}
void main() {
runApp(
ChangeNotifierProvider(
create: (_) => MyDataNotifier(),
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text(context.read<MyDataNotifier>().testString),
),
body: Container(
child: Level1(),
),
),
);
}
}
class Level1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Column(
children: [
TextField(
onChanged: (val) {
context.read<MyDataNotifier>().updateString(val);
},
),
Text(context.read<MyDataNotifier>().testString),
],
);
}
}
All the calls are to counter.read<T>(). The app's state changes, but the UI is not rebuilt with the new value. I have to change one of the calls to counter.watch<T>() to get the state to rebuild.
On the other hand, in DZone's simple example, the UI rebuilds, and all the calls are to context.read().
What's different between their code and mine? Why can't I rebuild with counter.read() calls?
TLDR: after a quick glance, the DZone article looks like it has a bug.
Longer answer
context.watch<Foo>() does 2 things:
return the instance of the state from the tree
mark context as dependent on Foo
context.read<Foo>() only does 1).
Whenever your UI depends on Foo, you should use context.watch, since this appropriately informs Flutter about that dependency, and it will be rebuilt properly.
In general, it boils down to this rule of thumb:
Use context.watch in build() methods, or any other method that returns a Widget
Use context.read in onPressed handlers (and other related functions)
The main reason people seem to use context.read inappropriately is for performance reasons. In general, preferring context.read over context.watch for performance is an anti-pattern. Instead, you should use context.select if you want to limit how often a widget rebuilds. This is most useful whenever you have a value that changes often.
Imagine you have the following state:
class FooState extends ChangeNotifier {
// imagine this us updated very often
int millisecondsSinceLastTap;
// updated less often
bool someOtherProperty = false;
}
If you had a widget that displays someOtherProperty, context.watch could cause many unnecessary rebuilds. Instead, you can use context.select only depend on a processed part of the state:
// read the property, rebuild only when someOtherProperty changes
final property = context.select((FooState foo) => foo.someOtherProperty);
return Text('someOtherProperty: $property');
Even with a frequently updating value, if the output of the function provided to select doesn't change, the widget won't rebuild:
// even though millisecondsSinceLastTap may be updating often,
// this will only rebuild when millisecondsSinceLastTap > 1000 changes
final value = context.select((FooState state) => state.millisecondsSinceLastTap > 1000);
return Text('${value ? "more" : "less"} than 1 second...');

Locally overriding CupertinoTheme with Flutter

I'm working with Cupertino widgets, and need to locally override my global CupertinoTheme, and use CupertinoTheme widget for this purpose. My use case is to force some 'dark' theme when displaying text on top of images, but the issue is general.
In the following sample, I try to change the font size for one text style (from 42px to 21px), but it is not applied: the two texts have the same size (second should be 21px high).
It seems that CupertinoTheme.of(context) does not read the overriden style, contrary to the documentation
Descendant widgets can retrieve the current CupertinoThemeData by calling CupertinoTheme.of
Here is a sample (that can be tested on DartPad):
import 'package:flutter/cupertino.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return CupertinoApp(
debugShowCheckedModeBanner: true,
theme: CupertinoThemeData(
brightness: Brightness.dark,
textTheme: CupertinoTextThemeData(
navLargeTitleTextStyle: TextStyle(fontSize: 42)
)
),
home: Home()
);
}
}
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
child: Column(
children: [
Text(
'Hello, World #1!',
style: CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle
),
CupertinoTheme(
data: CupertinoThemeData(
textTheme: CupertinoTextThemeData(
navLargeTitleTextStyle: TextStyle(fontSize: 21)
)
),
child: Text(
'Hello, World #2!',
style:
CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle
),
),
]
)
);
}
}
You’re getting the theme from the wrong context. The context must be a descendant of the CupertinoTheme widget (or rather the element that will be created from it). Try:
CupertinoTheme(
data: ...,
child: Builder(
builder: (context) => ... CupertinoTheme.of(contex)...
)
)
With the content parameter of the build method you can access anything done by ancestors of the build-method’s widget. Whatever you do in the build method has no effect on it.
Widgets are recipes for creating a tree of Elements. The context parameter that you get in build(er) method is (a reduced interface of) the element created for that widget. The Foo.of(context) methods typically search through the ancestor elements of context to find a Foo. (In some cases there is caching, so it isn’t a slow search.) When you create a tree of widgets in a build method, you’re just creating widgets; the elements will be created after that build method competes. Using a Builder widget, like I did above, delays creation of the widgets in Builder’s builder parameter until after an elements have been created for the Builder (and the widgets above it). So that is a way to get around your problem. Another way would be to create a new StatelessWidget with the widgets that are children of CupertinoTheme in your code, because it will similarly delay the creation of those widgets until after the element for that stateless widget (and its parents) is created.

Dart : Object vs Function what's the best implementation choice [duplicate]

I have realized that it is possible to create widgets using plain functions instead of subclassing StatelessWidget. An example would be this:
Widget function({ String title, VoidCallback callback }) {
return GestureDetector(
onTap: callback,
child: // some widget
);
}
This is interesting because it requires far less code than a full-blown class. Example:
class SomeWidget extends StatelessWidget {
final VoidCallback callback;
final String title;
const SomeWidget({Key key, this.callback, this.title}) : super(key: key);
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: callback,
child: // some widget
);
}
}
So I've been wondering: Is there any difference besides syntax between functions and classes to create widgets? And is it a good practice to use functions?
Edit: The Flutter team has now taken an official stance on the matter and stated that classes are preferable. See https://www.youtube.com/watch?v=IOyq-eTRhvo
TL;DR: Prefer using classes over functions to make reusable widget-tree.
EDIT: To make up for some misunderstanding:
This is not about functions causing problems, but classes solving some.
Flutter wouldn't have StatelessWidget if a function could do the same thing.
Similarly, it is mainly directed at public widgets, made to be reused. It doesn't matter as much for private functions made to be used only once – although being aware of this behavior is still good.
There is an important difference between using functions instead of classes, that is: The framework is unaware of functions, but can see classes.
Consider the following "widget" function:
Widget functionWidget({ Widget child}) {
return Container(child: child);
}
used this way:
functionWidget(
child: functionWidget(),
);
And it's class equivalent:
class ClassWidget extends StatelessWidget {
final Widget child;
const ClassWidget({Key key, this.child}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
child: child,
);
}
}
used like that:
new ClassWidget(
child: new ClassWidget(),
);
On paper, both seem to do exactly the same thing: Create 2 Container, with one nested into the other. But the reality is slightly different.
In the case of functions, the generated widget tree looks like this:
Container
Container
While with classes, the widget tree is:
ClassWidget
Container
ClassWidget
Container
This is important because it changes how the framework behaves when updating a widget.
Why that matters
By using functions to split your widget tree into multiple widgets, you expose yourself to bugs and miss on some performance optimizations.
There is no guarantee that you will have bugs by using functions, but by using classes, you are guaranteed to not face these issues.
Here are a few interactive examples on Dartpad that you can run yourself to better understand the issues:
https://dartpad.dev/?id=bcae5878ccced764b35dd9a659a593db
This example showcases how by splitting your app into functions,
you may accidentally break things like AnimatedSwitcher
https://dartpad.dev/?id=481a2c301c2e4bed6c30ba651d01bacb
This example showcases how classes allow more granular rebuilds of the
widget tree, improving performances
https://dartpad.dev/?id=8bcb85ba535102bed652e5bf1540ac3b
This example showcases how, by using functions, you expose yourself
to misusing BuildContext and facing bugs when using InheritedWidgets (such as Theme or providers)
Conclusion
Here's a curated list of the differences between using functions and classes:
Classes:
allow performance optimization (const constructor, more granular rebuild)
ensure that switching between two different layouts correctly disposes of the resources (functions may reuse some previous state)
ensures that hot-reload works properly (using functions could break hot-reload for showDialogs & similar)
are integrated into the widget inspector.
We see ClassWidget in the widget-tree showed by the devtool, which
helps understanding what is on screen
We can override debugFillProperties to print what the parameters passed to a widget are
better error messages
If an exception happens (like ProviderNotFound), the framework will give you the name of the currently building widget.
If you've split your widget tree only in functions + Builder, your errors won't have a helpful name
can define keys
can use the context API
Functions:
have less code (which can be solved using code-generation functional_widget)
Overall, it is considered a bad practice to use functions over classes for reusing widgets because of these reasons.
You can, but it may bite you in the future.
I've been researching on this issue for the past 2 days. I came to the following conclusion: it is OKAY to break down pieces of the app into functions. It's just ideal that those functions return a StatelessWidget, so optimisations can be made, such as making the StatelessWidget const, so it doesn't rebuild if it doesn't have to.
For example, this piece of code is perfectly valid:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
++_counter;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
const MyWidgetClass(key: const Key('const')),
MyWidgetClass(key: Key('non-const')),
_buildSomeWidgets(_counter),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
Widget _buildSomeWidgets(int val) {
print('${DateTime.now()} Rebuild _buildSomeWidgets');
return const MyWidgetClass(key: Key('function'));
// This is bad, because it would rebuild this every time
// return Container(
// child: Text("hi"),
// );
}
}
class MyWidgetClass extends StatelessWidget {
const MyWidgetClass({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
print('${DateTime.now()} Rebuild MyWidgetClass $key');
return Container(
child: Text("hi"),
);
}
}
The use of function there is perfectly fine, as it returns a const StatelessWidget. Please correct me if I'm wrong.
1 - Most of the time build method (child widget) calls number of synchronous and asynchronous functions.
Ex:
To download network image
get input from users etc.
so build method need to keep in the separate class widget (because all other methods call by build() method can keep in one class)
2 - Using the widget class you can create a number of other classes without writing the same code again and again (** Use Of Inheritance** (extends)).
And also using inheritance(extend) and polymorphism (override) you can create your own custom class.
(Down below example, In there I will customize (Override) the animation by extending MaterialPageRoute (because its default transition I want to customize).👇
class MyCustomRoute<T> extends MaterialPageRoute<T> {
MyCustomRoute({ WidgetBuilder builder, RouteSettings settings })
: super(builder: builder, settings: settings);
#override //Customize transition
Widget buildTransitions(BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child) {
if (settings.isInitialRoute)
return child;
// Fades between routes. (If you don't want any animation,
// just return child.)
return new FadeTransition(opacity: animation, child: child);
}
}
3 - Functions cannot add conditions for their parameters, But using the class widget's constructor You can do this.
Down below Code example👇 (this feature is heavily used by framework widgets)
const Scaffold({
Key key,
this.bottomNavigationBar,
this.bottomSheet,
this.backgroundColor,
this.resizeToAvoidBottomPadding,
this.resizeToAvoidBottomInset,
this.primary = true,
this.drawerDragStartBehavior = DragStartBehavior.start,
this.extendBody = false,
this.extendBodyBehindAppBar = false,
this.drawerScrimColor,
this.drawerEdgeDragWidth,
}) : assert(primary != null),
assert(extendBody != null),
assert(extendBodyBehindAppBar != null),
assert(drawerDragStartBehavior != null),
super(key: key);
4 - Functions cannot use const and the Class widget can use the const for their constructors.
(that affect the performance of the main thread)
5 - You can create any number of independent widgets using the same class (instances of a class/objects)
But function cannot create independant widgets(instance), but reusing can.
[each instance has its own instance variable and that is completely independant from other widgets(object), But function's local variable is dependant on each function call* (which means, when you change a value of a local variable it affect for all other parts of the application which use this function)]
There were many Advantages in class over functions..(above are few use cases only)
My Final Thought
So don't use Functions as building blocks of your application, use them only for doing Operations.
Otherwise, it causes many unchangeable problems when your application gets scalable.
Use functions for doing a small portion of the task
Use class as a building block of an application(Managing application)
As Remi has eloquently put repeatedly, it's not the functions by themselves that cause a problem, the problem is us thinking that using a function has a similar benefit to using a new widget.
Unfortunately this advice is evolving into "the act of merely using a function is inefficient", with often incorrect speculations into why this might be.
Using a function is almost the same as using what the function returns in place of that function. So, if you are calling a widget constructor and giving it as a child to another widget, you are not making your code inefficient by moving that constructor call into a function.
//...
child: SomeWidget(),
//...
is not significantly better in terms of efficiency than
//...
child: buildSomeWidget();
//...
Widget buildSomeWidget() => SomeWidget();
It is fine to argue the following about the second one:
It's ugly
It's unnecessary
I don't like it
Function does not appear in Flutter Inspector
Two functions may not work with AnimatedSwitcher et al.
It does not create a new context, so you can't reach the Scaffold above it through context
If you use ChangeNotifier in it, its rebuild is not contained within the function
But it's not correct to argue this:
Using a function is inefficient in terms of performance
Creating a new widget brings these performance benefits:
ChangeNotifier within it does not make its parent rebuild upon changes
Sibling widgets are protected from each other's rebuilds
Creating it with const (if possible) protects it from parent's rebuilds
You are more likely to keep your const constructor if you can isolate the changing children to other widgets
However, if you do not have any of these cases, and your build function is looking more and more like pyramid of doom, it is better to refactor a part of it to a function rather than keeping the pyramid. Especially if you are enforcing 80 character limit, you may find yourself writing code in about 20 character-wide space. I see a lot of newbies falling into this trap. The message to those newbies should be "You should really be creating new widgets here. But if you can't, at least create a function.", not "You have to create a widget or else!". Which is why I think we have to be more specific when we promote widgets over functions and avoid being factually incorrect about efficiency.
For your convenience, I have refactored Remi's code to show that the problem is not simply using functions, but the problem is avoiding creating new widgets. So, if you were to place the widget-creating code in those functions into where the functions are called (refactor-inline) you have the exact same behavior as using functions, but without using functions! So, it's not using functions that's the problem, it's the avoidance of creating new widget classes.
(remember to turn off null safety as the original code is from 2018)
Here are a few interactive examples on Dartpad that you can run
yourself to better understand the issues:
https://dartpad.dev/1870e726d7e04699bc8f9d78ba71da35 This example
showcases how by splitting your app into functions, you may
accidentally break things like AnimatedSwitcher
Non-function version: https://dartpad.dev/?id=ae5686f3f760e7a37b682039f546a784
https://dartpad.dev/a869b21a2ebd2466b876a5997c9cf3f1 This example
showcases how classes allow more granular rebuilds of the widget tree,
improving performances
Non-function version: https://dartpad.dev/?id=795f286791110e3abc1900e4dcd9150b
https://dartpad.dev/06842ae9e4b82fad917acb88da108eee This example
showcases how, by using functions, you expose yourself to misusing
BuildContext and facing bugs when using InheritedWidgets (such as
Theme or providers)
Non-function version: https://dartpad.dev/?id=65f753b633f68503262d5adc22ea27c0
You will find that not having them in a function creates the exact same behavior. So it's adding widgets that gives you the win. It's not adding functions that creates a problem.
So the suggestions should be:
Avoid the pyramid of doom at any cost! You need horizontal space to code. Don't get stuck at the right margin.
Create functions if you need, but do not give parameters to them as it's impossible to find the line that calls the function through Flutter Inspector.
Consider creating new widget classes, it's the better way! Try Refactor->Extract Flutter Widget. You won't be able to if your code is too coupled with the current class. Next time you should plan better.
Try to comment out things that prevent you from extracting a new widget. Most likely they are function calls in the current class (setState, etc.). Extract your widget then, and find ways of adding that stuff in. Passing functions to the constructor may be ok (think onPressed). Using a state management system may be even better.
I hope this can help remind why we prefer widgets over functions and that simply using a function is not a huge problem.
Edit: one point that was missed in this whole discussion: when you widgetize, siblings don't rebuild each other anymore. This Dartpad demonstrates this: https://dartpad.dartlang.org/?id=8d9b6d5bd53a23b441c117cd95524892
When you are calling the Flutter widget make sure you use the const keyword. For example const MyListWidget();
In case this helps anyone passing this way, some things I have in my conceptual model of Flutter developed from this question and working with Flutter in general (caveat: I could still be deeply confused and wrong about this stuff).
A Widget is what you want and the Elements are what you have. It is the job of the rendering engine to reconcile the two as efficiently as possible.
Use Keys, they can help a lot.
A BuildContext is an Element.
Any Thing.of(context) is likely to introduce a build dependency. If Thing changes it will trigger a rebuild from the context element.
In your build() if you access a BuildContext from a nested widget you are acting on the Element at the top of your subtree.
Widget build(BuildContext rootElement) {
return Container(
child:Container(
child:Container(
child:Text(
"Depends on rootElement",
// This introduces a build trigger
// If ThemeData changes a rebuild is triggered
// on rootElement not this Text()-induced element
style:Theme.of(rootElement).textTheme.caption,
),
),
),
);
}
AnimatedSwitcher is a slippery beast - it has to be able to distinguish its children. You can use functions if they return different types or return the same type but with different Keys
If you are authoring a Widget use a class not a Function but feel free to refactor your 1000 line build() method with functions/methods, the outcome is identical*.
* but could be even better to refactor into classes

What is the difference between functions and classes to create reusable widgets?

I have realized that it is possible to create widgets using plain functions instead of subclassing StatelessWidget. An example would be this:
Widget function({ String title, VoidCallback callback }) {
return GestureDetector(
onTap: callback,
child: // some widget
);
}
This is interesting because it requires far less code than a full-blown class. Example:
class SomeWidget extends StatelessWidget {
final VoidCallback callback;
final String title;
const SomeWidget({Key key, this.callback, this.title}) : super(key: key);
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: callback,
child: // some widget
);
}
}
So I've been wondering: Is there any difference besides syntax between functions and classes to create widgets? And is it a good practice to use functions?
Edit: The Flutter team has now taken an official stance on the matter and stated that classes are preferable. See https://www.youtube.com/watch?v=IOyq-eTRhvo
TL;DR: Prefer using classes over functions to make reusable widget-tree.
EDIT: To make up for some misunderstanding:
This is not about functions causing problems, but classes solving some.
Flutter wouldn't have StatelessWidget if a function could do the same thing.
Similarly, it is mainly directed at public widgets, made to be reused. It doesn't matter as much for private functions made to be used only once – although being aware of this behavior is still good.
There is an important difference between using functions instead of classes, that is: The framework is unaware of functions, but can see classes.
Consider the following "widget" function:
Widget functionWidget({ Widget child}) {
return Container(child: child);
}
used this way:
functionWidget(
child: functionWidget(),
);
And it's class equivalent:
class ClassWidget extends StatelessWidget {
final Widget child;
const ClassWidget({Key key, this.child}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
child: child,
);
}
}
used like that:
new ClassWidget(
child: new ClassWidget(),
);
On paper, both seem to do exactly the same thing: Create 2 Container, with one nested into the other. But the reality is slightly different.
In the case of functions, the generated widget tree looks like this:
Container
Container
While with classes, the widget tree is:
ClassWidget
Container
ClassWidget
Container
This is important because it changes how the framework behaves when updating a widget.
Why that matters
By using functions to split your widget tree into multiple widgets, you expose yourself to bugs and miss on some performance optimizations.
There is no guarantee that you will have bugs by using functions, but by using classes, you are guaranteed to not face these issues.
Here are a few interactive examples on Dartpad that you can run yourself to better understand the issues:
https://dartpad.dev/?id=bcae5878ccced764b35dd9a659a593db
This example showcases how by splitting your app into functions,
you may accidentally break things like AnimatedSwitcher
https://dartpad.dev/?id=481a2c301c2e4bed6c30ba651d01bacb
This example showcases how classes allow more granular rebuilds of the
widget tree, improving performances
https://dartpad.dev/?id=8bcb85ba535102bed652e5bf1540ac3b
This example showcases how, by using functions, you expose yourself
to misusing BuildContext and facing bugs when using InheritedWidgets (such as Theme or providers)
Conclusion
Here's a curated list of the differences between using functions and classes:
Classes:
allow performance optimization (const constructor, more granular rebuild)
ensure that switching between two different layouts correctly disposes of the resources (functions may reuse some previous state)
ensures that hot-reload works properly (using functions could break hot-reload for showDialogs & similar)
are integrated into the widget inspector.
We see ClassWidget in the widget-tree showed by the devtool, which
helps understanding what is on screen
We can override debugFillProperties to print what the parameters passed to a widget are
better error messages
If an exception happens (like ProviderNotFound), the framework will give you the name of the currently building widget.
If you've split your widget tree only in functions + Builder, your errors won't have a helpful name
can define keys
can use the context API
Functions:
have less code (which can be solved using code-generation functional_widget)
Overall, it is considered a bad practice to use functions over classes for reusing widgets because of these reasons.
You can, but it may bite you in the future.
I've been researching on this issue for the past 2 days. I came to the following conclusion: it is OKAY to break down pieces of the app into functions. It's just ideal that those functions return a StatelessWidget, so optimisations can be made, such as making the StatelessWidget const, so it doesn't rebuild if it doesn't have to.
For example, this piece of code is perfectly valid:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
++_counter;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
const MyWidgetClass(key: const Key('const')),
MyWidgetClass(key: Key('non-const')),
_buildSomeWidgets(_counter),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
Widget _buildSomeWidgets(int val) {
print('${DateTime.now()} Rebuild _buildSomeWidgets');
return const MyWidgetClass(key: Key('function'));
// This is bad, because it would rebuild this every time
// return Container(
// child: Text("hi"),
// );
}
}
class MyWidgetClass extends StatelessWidget {
const MyWidgetClass({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
print('${DateTime.now()} Rebuild MyWidgetClass $key');
return Container(
child: Text("hi"),
);
}
}
The use of function there is perfectly fine, as it returns a const StatelessWidget. Please correct me if I'm wrong.
1 - Most of the time build method (child widget) calls number of synchronous and asynchronous functions.
Ex:
To download network image
get input from users etc.
so build method need to keep in the separate class widget (because all other methods call by build() method can keep in one class)
2 - Using the widget class you can create a number of other classes without writing the same code again and again (** Use Of Inheritance** (extends)).
And also using inheritance(extend) and polymorphism (override) you can create your own custom class.
(Down below example, In there I will customize (Override) the animation by extending MaterialPageRoute (because its default transition I want to customize).👇
class MyCustomRoute<T> extends MaterialPageRoute<T> {
MyCustomRoute({ WidgetBuilder builder, RouteSettings settings })
: super(builder: builder, settings: settings);
#override //Customize transition
Widget buildTransitions(BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child) {
if (settings.isInitialRoute)
return child;
// Fades between routes. (If you don't want any animation,
// just return child.)
return new FadeTransition(opacity: animation, child: child);
}
}
3 - Functions cannot add conditions for their parameters, But using the class widget's constructor You can do this.
Down below Code example👇 (this feature is heavily used by framework widgets)
const Scaffold({
Key key,
this.bottomNavigationBar,
this.bottomSheet,
this.backgroundColor,
this.resizeToAvoidBottomPadding,
this.resizeToAvoidBottomInset,
this.primary = true,
this.drawerDragStartBehavior = DragStartBehavior.start,
this.extendBody = false,
this.extendBodyBehindAppBar = false,
this.drawerScrimColor,
this.drawerEdgeDragWidth,
}) : assert(primary != null),
assert(extendBody != null),
assert(extendBodyBehindAppBar != null),
assert(drawerDragStartBehavior != null),
super(key: key);
4 - Functions cannot use const and the Class widget can use the const for their constructors.
(that affect the performance of the main thread)
5 - You can create any number of independent widgets using the same class (instances of a class/objects)
But function cannot create independant widgets(instance), but reusing can.
[each instance has its own instance variable and that is completely independant from other widgets(object), But function's local variable is dependant on each function call* (which means, when you change a value of a local variable it affect for all other parts of the application which use this function)]
There were many Advantages in class over functions..(above are few use cases only)
My Final Thought
So don't use Functions as building blocks of your application, use them only for doing Operations.
Otherwise, it causes many unchangeable problems when your application gets scalable.
Use functions for doing a small portion of the task
Use class as a building block of an application(Managing application)
As Remi has eloquently put repeatedly, it's not the functions by themselves that cause a problem, the problem is us thinking that using a function has a similar benefit to using a new widget.
Unfortunately this advice is evolving into "the act of merely using a function is inefficient", with often incorrect speculations into why this might be.
Using a function is almost the same as using what the function returns in place of that function. So, if you are calling a widget constructor and giving it as a child to another widget, you are not making your code inefficient by moving that constructor call into a function.
//...
child: SomeWidget(),
//...
is not significantly better in terms of efficiency than
//...
child: buildSomeWidget();
//...
Widget buildSomeWidget() => SomeWidget();
It is fine to argue the following about the second one:
It's ugly
It's unnecessary
I don't like it
Function does not appear in Flutter Inspector
Two functions may not work with AnimatedSwitcher et al.
It does not create a new context, so you can't reach the Scaffold above it through context
If you use ChangeNotifier in it, its rebuild is not contained within the function
But it's not correct to argue this:
Using a function is inefficient in terms of performance
Creating a new widget brings these performance benefits:
ChangeNotifier within it does not make its parent rebuild upon changes
Sibling widgets are protected from each other's rebuilds
Creating it with const (if possible) protects it from parent's rebuilds
You are more likely to keep your const constructor if you can isolate the changing children to other widgets
However, if you do not have any of these cases, and your build function is looking more and more like pyramid of doom, it is better to refactor a part of it to a function rather than keeping the pyramid. Especially if you are enforcing 80 character limit, you may find yourself writing code in about 20 character-wide space. I see a lot of newbies falling into this trap. The message to those newbies should be "You should really be creating new widgets here. But if you can't, at least create a function.", not "You have to create a widget or else!". Which is why I think we have to be more specific when we promote widgets over functions and avoid being factually incorrect about efficiency.
For your convenience, I have refactored Remi's code to show that the problem is not simply using functions, but the problem is avoiding creating new widgets. So, if you were to place the widget-creating code in those functions into where the functions are called (refactor-inline) you have the exact same behavior as using functions, but without using functions! So, it's not using functions that's the problem, it's the avoidance of creating new widget classes.
(remember to turn off null safety as the original code is from 2018)
Here are a few interactive examples on Dartpad that you can run
yourself to better understand the issues:
https://dartpad.dev/1870e726d7e04699bc8f9d78ba71da35 This example
showcases how by splitting your app into functions, you may
accidentally break things like AnimatedSwitcher
Non-function version: https://dartpad.dev/?id=ae5686f3f760e7a37b682039f546a784
https://dartpad.dev/a869b21a2ebd2466b876a5997c9cf3f1 This example
showcases how classes allow more granular rebuilds of the widget tree,
improving performances
Non-function version: https://dartpad.dev/?id=795f286791110e3abc1900e4dcd9150b
https://dartpad.dev/06842ae9e4b82fad917acb88da108eee This example
showcases how, by using functions, you expose yourself to misusing
BuildContext and facing bugs when using InheritedWidgets (such as
Theme or providers)
Non-function version: https://dartpad.dev/?id=65f753b633f68503262d5adc22ea27c0
You will find that not having them in a function creates the exact same behavior. So it's adding widgets that gives you the win. It's not adding functions that creates a problem.
So the suggestions should be:
Avoid the pyramid of doom at any cost! You need horizontal space to code. Don't get stuck at the right margin.
Create functions if you need, but do not give parameters to them as it's impossible to find the line that calls the function through Flutter Inspector.
Consider creating new widget classes, it's the better way! Try Refactor->Extract Flutter Widget. You won't be able to if your code is too coupled with the current class. Next time you should plan better.
Try to comment out things that prevent you from extracting a new widget. Most likely they are function calls in the current class (setState, etc.). Extract your widget then, and find ways of adding that stuff in. Passing functions to the constructor may be ok (think onPressed). Using a state management system may be even better.
I hope this can help remind why we prefer widgets over functions and that simply using a function is not a huge problem.
Edit: one point that was missed in this whole discussion: when you widgetize, siblings don't rebuild each other anymore. This Dartpad demonstrates this: https://dartpad.dartlang.org/?id=8d9b6d5bd53a23b441c117cd95524892
When you are calling the Flutter widget make sure you use the const keyword. For example const MyListWidget();
In case this helps anyone passing this way, some things I have in my conceptual model of Flutter developed from this question and working with Flutter in general (caveat: I could still be deeply confused and wrong about this stuff).
A Widget is what you want and the Elements are what you have. It is the job of the rendering engine to reconcile the two as efficiently as possible.
Use Keys, they can help a lot.
A BuildContext is an Element.
Any Thing.of(context) is likely to introduce a build dependency. If Thing changes it will trigger a rebuild from the context element.
In your build() if you access a BuildContext from a nested widget you are acting on the Element at the top of your subtree.
Widget build(BuildContext rootElement) {
return Container(
child:Container(
child:Container(
child:Text(
"Depends on rootElement",
// This introduces a build trigger
// If ThemeData changes a rebuild is triggered
// on rootElement not this Text()-induced element
style:Theme.of(rootElement).textTheme.caption,
),
),
),
);
}
AnimatedSwitcher is a slippery beast - it has to be able to distinguish its children. You can use functions if they return different types or return the same type but with different Keys
If you are authoring a Widget use a class not a Function but feel free to refactor your 1000 line build() method with functions/methods, the outcome is identical*.
* but could be even better to refactor into classes

InheritedWidget with Scaffold as child doesn't seem to be working

I was hoping to use InheritedWidget at the root level of my Flutter application to ensure that an authenticated user's details are available to all child widgets. Essentially making the Scaffold the child of the IW like this:
#override
Widget build(BuildContext context) {
return new AuthenticatedWidget(
user: _user,
child: new Scaffold(
appBar: new AppBar(
title: 'My App',
),
body: new MyHome(),
drawer: new MyDrawer(),
));
}
This works as expected on app start so on the surface it seems that I have implemented the InheritedWidget pattern correctly in my AuthenticatedWidget, but when I return back to the home page (MyHome) from elsewhere like this:
Navigator.popAndPushNamed(context, '/home');
This call-in the build method of MyHome (which worked previously) then results in authWidget being null:
final authWidget = AuthenticatedWidget.of(context);
Entirely possible I'm missing some nuances of how to properly implement an IW but again, it does work initially and I also see others raising the same question (i.e. here under the 'Inherited Widgets' heading).
Is it therefore not possible to use a Scaffold or a MaterialApp as the child of an InheritedWidget? Or is this maybe a bug to be raised? Thanks in advance!
MyInherited.of(context) will basically look into the parent of the current context to see if there's a MyInherited instantiated.
The problem is : Your inherited widget is instantiated within the current context.
=> No MyInherited as parent
=> crash
The trick is to use a different context.
There are many solutions there. You could instantiate MyInherited in another widget, so that the context of your build method will have a MyInherited as parent.
Or you could potentially use a Builder to introduce a fake widget that will pass you it's context.
Example of builder :
return new MyInheritedWidget(
child: new Builder(
builder: (context) => new Scaffold(),
),
);
Another problem, for the same reasons, is that if you insert an inheritedWidget inside a route, it will not be available outside of this route.
The solution is simple here !
Put your MyInheritedWidget above MaterialApp.
above material :
new MyInherited(
child: new MaterialApp(
// ...
),
)
Is it therefore not possible to use a Scaffold or a MaterialApp as the
child of an InheritedWidget?
It is very possible to do this. I was struggling with this earlier and posted some details and sample code here.
You might want to make your App-level InheritedWidget the parent of the MaterialApp rather than the Scaffold widget.
I think this has more to do with how you are setting up your MaterialWidget, but I can't quite tell from the code snippets you have provided.
If you can add some more context, I will see if I can provide more.