Mock a Widget in Flutter tests - flutter

I am trying to create tests for my Flutter application. Simple example:
class MyWidget extends StatelessWidget {
#override
build(BuildContext context) {
return MySecondWidget();
}
}
I would like to verify that MyWidget is actually calling MySecondWidget without building MySecondWidget.
void main() {
testWidgets('It should call MySecondWidget', (WidgetTester tester) async {
await tester.pumpWidget(MyWidget());
expect(find.byType(MySecondWidget), findsOneWidget);
}
}
In my case this will not work because MySecondWidget needs some specific and complex setup (like an API key, a value in a Provider...). What I would like is to "mock" MySecondWidget to be an empty Container (for example) so it doesn't raise any error during the test.
How can I do something like that ?

There is nothing done out of the box to mock a widget. I'm going to write some examples/ideas on how to "mock"/replace a widget during a test (for example with a SizedBox.shrink().
But first, let me explain why I think this is not a good idea.
In Flutter you are building a widget tree. A specific widget has a parent and usually has one or several children.
Flutter chose a single pass layout algorithm for performance reasons (see this):
Flutter performs one layout per frame, and the layout algorithm works in a single pass. Constraints are passed down the tree by parent objects calling the layout method on each of their children. The children recursively perform their own layout and then return geometry up the tree by returning from their layout method. Importantly, once a render object has returned from its layout method, that render object will not be visited again until the layout for the next frame. This approach combines what might otherwise be separate measure and layout passes into a single pass and, as a result, each render object is visited at most twice during layout: once on the way down the tree, and once on the way up the tree.
From this, we need to understand that a parent needs its children to build to get their sizes and then render itself properly. If you remove its children, it might behave completely differently.
It is better to mock the services if possible. For example, if your child makes an HTTP request, you can mock the HTTP client:
HttpOverrides.runZoned(() {
// Operations will use MyHttpClient instead of the real HttpClient
// implementation whenever HttpClient is used.
}, createHttpClient: (SecurityContext? c) => MyHttpClient(c));
If the child needs a specific provider you can provide a dummy one:
testWidgets('My test', (tester) async {
tester.pumpWidget(
Provider<MyProvider>(
create: (_) => MyDummyProvider(),
child: MyWidget(),
),
);
});
If you still want to change a widget with another one during your tests, here are some ideas:
1. Use Platform.environment.containsKey('FLUTTER_TEST')
You can either import Platform from dart:io (not supported on web) or universal_io (supported on web).
and your build method could be:
#override
Widget build(BuildContext context) {
final isTest = Platform.environment.containsKey('FLUTTER_TEST');
if (isTest) return const SizedBox.shrink();
return // Your real implementation.
}
2. Use the annotation #visibleForTesting
You can annotate a parameter (ex: mockChild) that is only visible/usable in a test file:
class MyWidget extends StatelessWidget {
const MyWidget({
#visibleForTesting this.mockChild,
});
final Widget? child;
#override
Widget build(BuildContext context) {
return mockChild ?? // Your real widget implementation here.
}
}
And in your test:
tester.pumpWidget(
MyWidget(
mockChild: MyMockChild(),
),
);

You can mock MySecondWidget (eg using Mockito) but you do need to change your real code to create a MockMySecondWidget when in test mode, so it's not pretty. Flutter does not support object instantiation based on a Type (except through dart:mirrors but that is not compatible with Flutter), so you cannot 'inject' the type as a dependency. To determine if you are in test mode use Platform.environment.containsKey('FLUTTER_TEST') - best to determine this once upon startup and set the result as a global final variable, which will make any conditional statements quick.

One way to do it, is to wrap the child widget into a function, and pass the function to parent widget's constructor:
class MyWidget extends StatelessWidget {
final Widget Function() buildMySecondWidgetFn;
const MyWidget({
Key? key,
this.buildMySecondWidgetFn = _buildMySecondWidget
}): super(key: key);
#override
build(BuildContext context) {
return buildMySecondWidgetFn();
}
}
Widget _buildMySecondWidget() => MySecondWidget();
Then you can make up your mock widget, pass it thru buildMySecondWidgetFn in test.

Related

why use initState() in flutter, when we can just initailize a variable in the very first line of code

is there a difference in these 3 codes:
First: when i call my function inside onInit().
#override
void onInit() {
super.onInit();
fetchProductsFromAPI();
}
Second: when i call my function inside of build method, in stateless widget.
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
fetchProductsFromAPI();
return GetMaterialApp(
home: ShoppingPage(),
);
}
}
Third: when i call my function outside of build method, in stateless widget.
class MyApp extends StatelessWidget {
fetchProductsFromAPI();
#override
Widget build(BuildContext context) {
return GetMaterialApp(
home: ShoppingPage(),
);
}
}
Yes, there is a difference. You can read about flutter widget life cycle to have more details:
Life cycle in flutter
https://medium.flutterdevs.com/app-lifecycle-in-flutter-c248d894b830
In summary
When you call your method outside of build method (your 3rd example).
This is what is usually recommended when you can do it.
See is there any difference between assigning value to the variable inside of initState or not in Flutter StatefulWidget?
This will be run only once, when the class is created.
Inside the initState (your 1st example)
At this moment, your widget is being created. Some getters are already available, like the context. This method is called only once.
Inside the build method (your 2nd example)
This is usually the worst approach. Your method will be called for each and every build (you can consider 1 build = 1 frame) which can lead to poor performances. It is recommended to move those calls out of the build method when possible (and if it makes sense)
See How to deal with unwanted widget build?
First:
Put it on initState then the function fetchProductsFromAPI will only call first time your widget create
Second:
I highly recommend you do not use this approach, because build method will be trigger many time when widget need to rebuild, if you put it there, your app will be fetchProductsFromAPI at a lot of unexpected times.
Example when you need to call setState() for some changes, you don't want to call fetch API
Third:
This way will cause compile error, I don't think you can put it there like your code above

How to get the State<> instance inside of its StatefulWidget?

I have an unusual use case where I'd like to add a getter to a StatefulWidget class that accesses its State instance. Something like this:
class Foo extends StatefulWidget {
Foo({super.key});
int get bar => SomethingThatGetsFooState.bar;
#override
State<Foo> createState() => _FooState();
}
class _FooState extends State<Foo> {
int bar = 42;
#override
Widget build(BuildContext context) {
return Container();
}
}
Does SomethingThatGetsFooState exist?
I wonder, if your approach is the right way.
Flutter's way isn't 'Ask something about its state'
Flutter is much more like this: 'The consumer of a Widget passes something to another Widget, which the other Widget e.g. calls in case of certain situations (e.g. value change).'
Approach 1
You map pass a Callback Function to Foo and pass that along to _FooState.
If something special happens inside _FooState, you may call the callback and thus pass some value back to the provider of the Callback.
Approach 2
Probably use a state management solution like Flutter Redux. Using Flutter Redux, you establish a state store somewhere at the top of the widget tree, e.g. in MaterialApp.
Then you subscribe to the store at certain other locations, where dependent widgets exist, which need to update accordingly.
In one project I created certain Action classes, which I send to certain so called reducers of those states, to perform a change on the state:
StoreProvider.of<EModel>(context).dispatch( SaveToFileAction())
This call finds the relevant EModel state and asks it to perform the SaveToFileAction().
This way, a calling Widget not even needs to know, who is responsible for the Action.
The responsible Widget can even be moved around the widget tree - and the application still works. The initiator of SaveToFileAction() and the receiver are decoupled. The receiver you told a coordination 'Tell me, if someone tried to ask me for something.'
Could your provide some further details? Describe the usage pattern?
#SteAp is correct for suggesting there's a code smell in my OP. Typically there's no need to access State thru its StatefulWidget. But as I responded to his post, I'm fleshing out the first pass at a state management package, so it's an unusual case. Once I get it working, I'll revisit.
Below worked without Flutter complaining.
class _IntHolder {
int value;
}
class Foo extends StatefulWidget {
Foo({super.key});
final _intHolder = _IntHolder();
int get bar => _intHolder.value;
#override
State<Foo> createState() => _FooState();
}
class _FooState extends State<Foo> {
int value = 42;
#override
Widget build(BuildContext context) {
widget._intHolder.value = value;
return Container();
}
}

Why BuildContext only avaliable in StatelessWidget.build and what is the good way to use it?

I already known that build context can be used in StatefulWidget any where but only in build function when using Stateless Widget. There is so many content in widget need to reference the build context like Theme, showDialog,Navigator,Provider...
For Example, I have some code below in StatelessWidget:
#override
Widget build(BuildContext context){
...
_getFirstWidget();
...
}
...
Widget _getFirstWidget(){
return _getSecondWidget();
}
Widget _getSecondWidget(){
return _getThirdWidget();
}
Widget _getThirdWidget(){
// use build context here
}
...
If I want to use the build context at the end Widget, I think of 3 ways:
Pass the build context layer by layer
Convert to StatefulWidget
Convert the last widget to a Stateless Widget itself (and use the build context in build)
Why flutter make this restriction in StatelessWidget?
I'm not really sure but I think you want the use the BuildContext from the build method in the function '_getThirdWidget()'. You could just pass it as a parameter like below:
Widget _getThirdWidget(BuildContext context) {
// Use the context here
}
// Call the function like this in the parent widget
#override
Widget build(BuildContext context) {
return _getThirdWidget(context);
}
Let me know if this answers your question!
If you use the method of adding an argument to use context,
Almost every function needs a context argument
this is stupid behavior
StatelessWidget is inconvenient
I try to use StatelessWidget, but end up using Statefulwidget

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

Extracting Class Members like Widget Builders to a Different File?

In developing some of the screens for my flutter app, I regularly need to dynamically render widgets based on the state of the screen. For circumstances where it makes sense to create a separate widget and include it, I do that.
However, there are many use cases where what I need to render is not fit for a widget, and leverages existing state from the page. Therefore I use builder methods to render the appropriate widgets to the page. As anyone who uses Flutter knows, that can lead to lengthy code where you need to scroll up/down a lot to get to what you need to work on.
For better maintainability, I would love to move those builder methods into separate files, and then just include them. This would make it much easier to work on specific code widgets rendered and make the screen widget much cleaner.
But I haven't found a proper way to extract that dynamic widget code, which makes use of state, calls to update state, etc. I'm looking for a type of "include" file that would insert code into the main screen and render as if it's part of the core code.
Is this possible? How to achieve?
With the introduction of extension members, I came across this really neat way of achieving exactly what your described!
Say you have a State class defined like this:
class MyWidgetState extends State<MyWidget> {
int cakes;
#override
void initState() {
super.initState();
cakes = 0;
}
#override
Widget build(BuildContext context) {
return Builder(
builder: (context) => Text('$cakes'),
);
}
}
As you can see, there is a local variable cakes and a builder function. The very neat way to extract this builder now is the following:
extension CakesBuilderExtension on MyWidgetState {
Widget cakesBuilder(BuildContext context) {
return Text('$cakes');
}
}
Now, the cakes member can be accessed from the extension even if the extension is placed in another file.
Now, you would update your State class like this (the builder changed):
class MyWidgetState extends State<MyWidget> {
int cakes;
#override
void initState() {
super.initState();
cakes = 0;
}
#override
Widget build(BuildContext context) {
return Builder(
builder: cakesBuilder,
);
}
}
The cakesBuilder can be referenced from MyWidgetState, even though it is only declared in the CakesBuilderExtension!
Note
The extension feature requires Dart 2.6. This is not yet available in the stable channel, but should be around the end of 2019 I guess. Thus, you need to use the dev or master channels: flutter channel dev or flutter channel master and update the environment constraint in your pubspec.yaml file:
environment:
sdk: '>=2.6.0-dev.8.2 <3.0.0'