rrousselgit / functional_widget Goto Github PK
View Code? Open in Web Editor NEWA code generator to write widgets as function without loosing the benefits of classes.
A code generator to write widgets as function without loosing the benefits of classes.
I tried both:
flutter pub run build_runner watch
webdev serve
without success.
There was a builders:
option which you described will generate the widgets during the flutter build itself and it was so satisfying to prevent separate building concerns.
I know you had a good reason to remove it. I just wanted to ask you to give me some information about it. @rrousselGit
...
import 'package:provider/provider.dart';
import 'package:functional_widget_annotation/functional_widget_annotation.dart';
part 'activity_show_ticket_replies.g.dart';
class ActivityShowTicketReplies extends StatefulWidget {
final int ticketNumber;
ActivityShowTicketReplies({@required this.ticketNumber});
@override
State<StatefulWidget> createState() => ActivityShowTicketRepliesState();
}
class ActivityShowTicketRepliesState extends State<ActivityShowTicketReplies> {
/* GETTING THIS ERROR ON THIS LINE OF CODE */
int get _ticketNumber => widget.ticketNumber;
@override
Widget build(BuildContext context) {
return ScopedModel(
...
);
}
}
@widget
Widget _loader(BuildContext context, String message) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
ColorLoader3(
radius: 25.0,
dotRadius: 5.0,
),
Padding(
padding: const EdgeInsets.all(3.0),
child: Text(
Strings.pleaseWait,
style: AppTheme(context).caption().copyWith(color: Colors.red[900]),
),
),
],
));
}
The mobx.dart
requires analyzer: '>=0.38.5 <0.40.0'
, while this package forces to be lower. Thus, the two cannot be installed without conflict. So I update the version. In addition, there is a bug when updating it, so I also fix two little lines.
How about adding the name attribute?
@swidget(name: 'MyCoolWidget')
Also maybe add a configurable naming rule into build.yaml
?
I thought about it, because builder methods are most often named like: _buildHeader()
, _buildDataList()
But I want to have resulting widgets like Header()
instead of _BuildHeader()
My idea is to make functional_widget support for functions inside class as well as class inheritance and function overriding.
class A extends StatelessWidget
{
@override
Widget build(BuildContext context) => test();
@widget
Widget test() => Container()
}
class B extends A
{
@widget
@override
Widget test() => Text("hello");
}
Widgets can benefit from overriding operator==
for a performance gain.
We can potentially generate an operator== override on the widget class.
We should benchmark it first, to see the difference between:
Tests should be running both with and without const constructors
identical
check internallySame as #1 but for annotations:
class Foo {
Foo({ @required String parameter });
}
@required
being a pretty common use case
When using a parameter both @required
and with a type not included in the Dart SDK (Color
for example), the generation fails.
Example :
@widget
Widget example(BuildContext context, {@required Color splashColor})
Produces :
line 17, column 7: Expected an identifier.
╷
17 │ final @ splashColor;
│ ^
╵
line 17, column 7: Expected to find ';'.
╷
17 │ final @ splashColor;
│ ^
╵
line 17, column 20: Expected a class member.
╷
17 │ final @ splashColor;
│ ^
This is due of the access of the first token of the computedNode
.
You can also replace BuildContext by HookContext from https://github.com/rrousselGit/flutter_hooks
This should be changed to speak about @hwidget
decorator instead
flutter create example
dependencies:
flutter:
sdk: flutter
functional_widget_annotation: ^0.5.1
builders:
functional_widget: ^0.7.1
Error generating build_script snapshot: Could not find a file named "pubspec.yaml" in "/Users/gregorysech/.pub-cache/hosted/pub.dartlang.org/functional_widget-0.7.1".
[ +288 ms] generating build script... (completed in 11.9s)
[ +3 ms] "flutter run" took 16,008ms.
Error generating build_script snapshot: Could not find a file named "pubspec.yaml" in "/Users/gregorysech/.pub-cache/hosted/pub.dartlang.org/functional_widget-0.7.1".
#0 throwToolExit (package:flutter_tools/src/base/common.dart:28:3)
#1 BuildRunner.generateBuildScript (package:flutter_tools/src/build_runner/build_runner.dart:119:9)
<asynchronous suspension>
#2 BuildRunner.daemon (package:flutter_tools/src/build_runner/build_runner.dart:146:11)
<asynchronous suspension>
#3 CodeGeneratingResidentCompiler.create (package:flutter_tools/src/codegen.dart:188:61)
<asynchronous suspension>
#4 FlutterDevice.create (package:flutter_tools/src/resident_runner.dart:68:56)
<asynchronous suspension>
#5 RunCommand.runCommand (package:flutter_tools/src/commands/run.dart:405:29)
<asynchronous suspension>
#6 FlutterCommand.verifyThenRunCommand (package:flutter_tools/src/runner/flutter_command.dart:553:18)
#7 _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:71:64)
#8 _rootRunUnary (dart:async/zone.dart:1132:38)
#9 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#10 _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
#11 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
#12 Future._propagateToListeners (dart:async/future_impl.dart:707:32)
#13 Future._completeWithValue (dart:async/future_impl.dart:522:5)
#14 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:30:15)
#15 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:288:13)
#16 RunCommand.usageValues (package:flutter_tools/src/commands/run.dart)
#17 _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:71:64)
#18 _rootRunUnary (dart:async/zone.dart:1132:38)
#19 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#20 _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
#21 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
#22 Future._propagateToListeners (dart:async/future_impl.dart:707:32)
#23 Future._completeWithValue (dart:async/future_impl.dart:522:5)
#24 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:30:15)
#25 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:288:13)
#26 IosProject.isSwift (package:flutter_tools/src/project.dart)
#27 _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:71:64)
#28 _rootRunUnary (dart:async/zone.dart:1132:38)
#29 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#30 _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
#31 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
#32 Future._propagateToListeners (dart:async/future_impl.dart:707:32)
#33 Future._completeWithValue (dart:async/future_impl.dart:522:5)
#34 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:30:15)
#35 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:288:13)
#36 IosProject.buildSettings (package:flutter_tools/src/project.dart)
#37 _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:71:64)
#38 _rootRunUnary (dart:async/zone.dart:1132:38)
#39 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#40 _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
#41 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
#42 Future._propagateToListeners (dart:async/future_impl.dart:707:32)
#43 Future._completeWithValue (dart:async/future_impl.dart:522:5)
#44 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:30:15)
#45 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:288:13)
#46 XcodeProjectInterpreter.getBuildSettings (package:flutter_tools/src/ios/xcodeproj.dart)
#47 _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:71:64)
#48 _rootRunUnary (dart:async/zone.dart:1132:38)
#49 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#50 _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
#51 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
#52 Future._propagateToListeners (dart:async/future_impl.dart:707:32)
#53 Future._completeWithValue (dart:async/future_impl.dart:522:5)
#54 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:30:15)
#55 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:288:13)
#56 _DefaultProcessUtils.run (package:flutter_tools/src/base/process.dart)
#57 _asyncThenWrapperHelper.<anonymous closure> (dart:async-patch/async_patch.dart:71:64)
#58 _rootRunUnary (dart:async/zone.dart:1132:38)
#59 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#60 _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
#61 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
#62 Future._propagateToListeners (dart:async/future_impl.dart:707:32)
#63 Future._completeWithValue (dart:async/future_impl.dart:522:5)
#64 Future.wait.<anonymous closure> (dart:async/future.dart:400:22)
#65 _rootRunUnary (dart:async/zone.dart:1132:38)
#66 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#67 _FutureListener.handleValue (dart:async/future_impl.dart:137:18)
#68 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:678:45)
#69 Future._propagateToListeners (dart:async/future_impl.dart:707:32)
#70 Future._complete (dart:async/future_impl.dart:512:7)
#71 _BufferingStreamSubscription.asFuture.<anonymous closure> (dart:async/stream_impl.dart:204:14)
#72 _rootRun (dart:async/zone.dart:1120:38)
#73 _CustomZone.run (dart:async/zone.dart:1021:19)
#74 _CustomZone.runGuarded (dart:async/zone.dart:923:7)
#75 _BufferingStreamSubscription._sendDone.sendDone (dart:async/stream_impl.dart:389:13)
#76 _BufferingStreamSubscription._sendDone (dart:async/stream_impl.dart:399:15)
#77 _BufferingStreamSubscription._close (dart:async/stream_impl.dart:283:7)
#78 _SinkTransformerStreamSubscription._close (dart:async/stream_transformers.dart:96:11)
#79 _EventSinkWrapper.close (dart:async/stream_transformers.dart:23:11)
#80 _StringAdapterSink.close (dart:convert/string_conversion.dart:249:11)
#81 _Utf8ConversionSink.close (dart:convert/string_conversion.dart:300:20)
#82 _ConverterStreamEventSink.close (dart:convert/chunked_conversion.dart:80:18)
#83 _SinkTransformerStreamSubscription._handleDone (dart:async/stream_transformers.dart:141:24)
#84 _rootRun (dart:async/zone.dart:1120:38)
#85 _CustomZone.run (dart:async/zone.dart:1021:19)
#86 _CustomZone.runGuarded (dart:async/zone.dart:923:7)
#87 _BufferingStreamSubscription._sendDone.sendDone (dart:async/stream_impl.dart:389:13)
#88 _BufferingStreamSubscription._sendDone (dart:async/stream_impl.dart:399:15)
#89 _BufferingStreamSubscription._close (dart:async/stream_impl.dart:283:7)
#90 _SyncStreamControllerDispatch._sendDone (dart:async/stream_controller.dart:772:19)
#91 _StreamController._closeUnchecked (dart:async/stream_controller.dart:629:7)
#92 _StreamController.close (dart:async/stream_controller.dart:622:5)
#93 _Socket._onData (dart:io-patch/socket_patch.dart:1836:21)
#94 _rootRunUnary (dart:async/zone.dart:1136:13)
#95 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#96 _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
#97 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:336:11)
#98 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:263:7)
#99 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:764:19)
#100 _StreamController._add (dart:async/stream_controller.dart:640:7)
#101 _StreamController.add (dart:async/stream_controller.dart:586:5)
#102 new _RawSocket.<anonymous closure> (dart:io-patch/socket_patch.dart:1384:35)
#103 _NativeSocket.issueReadEvent.issue (dart:io-patch/socket_patch.dart:890:18)
#104 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
#105 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
#106 _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:116:13)
#107 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:173:5)
Analyzing example...
No issues found! (ran in 3.4s)
In stable flutter run
works as intended but in dev it does not.
[✓] Flutter (Channel dev, v1.10.7, on Mac OS X 10.14.6 18G87, locale en-GB)
• Flutter version 1.10.7 at /Users/gregorysech/flutter
• Framework revision e70236e36c (27 hours ago), 2019-10-02 09:32:30 -0700
• Engine revision 9e6314d348
• Dart version 2.6.0 (build 2.6.0-dev.0.0 1103600280)
[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
• Android SDK at /Users/gregorysech/Library/Android/sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-29, build-tools 28.0.3
• Java binary at: /Volumes/SD/IDEs/apps/AndroidStudio/ch-0/191.5791312/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
• All Android licenses accepted.
[✓] Xcode - develop for iOS and macOS (Xcode 10.2.1)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 10.2.1, Build version 10E1001
• CocoaPods version 1.7.5
[✓] Chrome - develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
[✓] Android Studio (version 3.5)
• Android Studio at /Volumes/SD/IDEs/apps/AndroidStudio/ch-0/191.5791312/Android Studio.app/Contents
• Flutter plugin version 39.0.3
• Dart plugin version 191.8423
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
[✓] VS Code (version 1.38.1)
• VS Code at /Users/gregorysech/Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.4.1
[✓] Connected device (3 available)
• iPhone Xʀ • AE87AF8A-D548-4345-BE9A-81D64DDF453A • ios • com.apple.CoreSimulator.SimRuntime.iOS-12-2 (simulator)
• Chrome • chrome • web-javascript • Google Chrome 77.0.3865.90
• Headless Server • headless-server • web-javascript • Flutter Tools
• No issues found!
It works on Stable
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, v1.9.1+hotfix.4, on Mac OS X 10.14.6 18G87, locale en-GB)
[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✓] Xcode - develop for iOS and macOS (Xcode 10.2.1)
[✓] Android Studio (version 3.5)
[✓] VS Code (version 1.38.1)
[✓] Connected device (1 available)
• No issues found!
Gregorys-MBP:example gregorysech$ flutter doctor -v
[✓] Flutter (Channel stable, v1.9.1+hotfix.4, on Mac OS X 10.14.6 18G87, locale en-GB)
• Flutter version 1.9.1+hotfix.4 at /Users/gregorysech/flutter
• Framework revision cc949a8e8b (6 days ago), 2019-09-27 15:04:59 -0700
• Engine revision b863200c37
• Dart version 2.5.0
[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
• Android SDK at /Users/gregorysech/Library/Android/sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-29, build-tools 28.0.3
• Java binary at: /Volumes/SD/IDEs/apps/AndroidStudio/ch-0/191.5791312/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
• All Android licenses accepted.
[✓] Xcode - develop for iOS and macOS (Xcode 10.2.1)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 10.2.1, Build version 10E1001
• CocoaPods version 1.7.5
[✓] Android Studio (version 3.5)
• Android Studio at /Volumes/SD/IDEs/apps/AndroidStudio/ch-0/191.5791312/Android Studio.app/Contents
• Flutter plugin version 39.0.3
• Dart plugin version 191.8423
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
[✓] VS Code (version 1.38.1)
• VS Code at /Users/gregorysech/Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.4.1
[✓] Connected device (1 available)
• iPhone Xʀ • AE87AF8A-D548-4345-BE9A-81D64DDF453A • ios • com.apple.CoreSimulator.SimRuntime.iOS-12-2 (simulator)
• No issues found!
I'm adding this issue here as I am not sure if it's a package problem or a build system problem.
If needed I can add this issue on the Flutter repository.
Consider:
typedef Foo<T> = void Function(T value);
@widget
Widget foo(Foo<int> cb) {}
the expected result is:
class Foo extends StatelessWidget {
final void Function(int) cb;
}
actual behavior:
class Foo extends StatelessWidget {
final void Function(T) cb;
}
According to Install (builder) in readme, I added dependencies in pubspec.yaml
dependencies:
flutter:
sdk: flutter
functional_widget_annotation: ^0.5.1
builders:
functional_widget: ^0.7.1
and made a simple widget
@widget
Widget foo(BuildContext context, int value) {
return Text('$value');
}
However when I add Foo(42)
in my code and try to run it, it doesn't work
Compiler message:
org-dartlang-app:/main.dart:23:16: Error: Method not found: 'Foo'.
child: Foo(42),
^^^
org-dartlang-app:/main.dart:23:16: Error: The method 'Foo' isn't defined for the class 'MyHomePage'.
- 'MyHomePage' is from 'package:test_functional_widget/main.dart' ('org-dartlang-app:/main.dart').
Try correcting the name to the name of an existing method, or defining a method named 'Foo'.
child: Foo(42),
^^^
flutter build apk
log
flutter run
log
flutter doctor
Repository with my example app
environment:
sdk: ">=2.6.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
functional_widget_annotation: ^0.5.1
builders:
functional_widget: ^0.7.1
BuildContext
(no actual extension methods are required):extension on BuildContext {
}
BuildContext
such as:@widget
Widget example(BuildContext context) => const Placeholder();
class Example extends StatelessWidget {
const Example({Key key}) : super(key: key);
@override
Widget build(BuildContext _context) => example(_context);
}
class Example extends StatelessWidget {
const Example(this.context, {Key key}) : super(key: key);
final dynamic context;
@override
Widget build(BuildContext _context) => example(context);
}
Because mobx_codegen >=0.0.7 depends on analyzer ^0.35.0 and functional_widget 0.5.0 depends on analyzer >=0.32.2 <0.34.0, mobx_codegen >=0.0.7 is incompatible with functional_widget 0.5.0.
And because no versions of functional_widget match >0.5.0 <0.6.0, mobx_codegen >=0.0.7 is incompatible with functional_widget ^0.5.0.
Is it possible to use interfaces with fucntional widgets ?
Classes allow documenting and annotating fields:
/// documentation
class Foo {
/// documentation
final field;
}
It would be interesting to import documentation from the function to the class, for a better integration in the IDE
Example:
@widget
Widget foo(VoidCallback bar) => Container();
generates
class Foo extends StatelessWidget {
const Foo(this.bar, {Key key}) : super(key: key);
final dynamic bar;
@override
Widget build(BuildContext _context) => foo(bar);
}
resulting in error:
The argument type 'dynamic' can't be assigned to the parameter type 'VoidCallbackvoid Function()'.dart(argument_type_not_assignable)
I'm trying few of your packages :) and from what I understand for now it's not possible to use this one with flutter_hook right ?
The idea will be to use flutter_hook to also allow "stateful" widgets define as a function.
So basically instead of:
class Example extends HookWidget {
@override
Widget build(HookContext context) {
finalmyState = context.useState(initialData: 0);
return Container();
}
}
We'll have :
Widget foo(HookContext context, { int value, int value2 }) {
final myState = context.useState(initialData: 0);
return Text('${myState.value} $value $value2');
}
We don't gain that much in terms of code, but at least we have the same way to define widget across the project.
I am using some non-null default parameters. The default values disappear when using the functional widget.
Sent with GitHawk
There's a lint called always_put_required_named_parameters_first.
Could you possibly add an // ignore_for_file: always_put_required_named_parameters_first
to the generated files?
I am returning to flutter and I am looking to uses the "builders" option in pubspec.yaml instead of build_runner. In the readme, it says that method should work unless you're using an older version of flutter. Have tried lastest stable, dev, and master (1.8.2) but as far as I can tell nothing uses this option and I can't find any documentation on this option after an hour of searching. Going to back to build_runner, but would like to use it for future use. Am I just missing something?
Maybe something like this:
@FunctionalWidget(className: 'FooBar')
Widget foo() => Text('foo');
Hello, I am trying to start using this library, but keep getting the following error:
generating build script...
Because build_runner >=1.6.5 <1.7.4 depends on build_config >=0.4.1 <0.4.2 and functional_widget >=0.7.3 depends on build_config ^0.4.2, build_runner >=1.6.5 <1.7.4 is incompatible with functional_widget >=0.7.3.
So, because flutter_tool depends on both functional_widget ^0.7.3 and build_runner 1.7.1, version solving failed.
generating build script... 2.0s
Exception: pub get failed (1; So, because flutter_tool depends on both functional_widget ^0.7.3 and build_runner 1.7.1, version solving failed.)
Exited (1)
It seems that some dependency of flutter_tool
pulls a fixed version of build_runner
, which depends on an old build_config
version.
Here is my pubspec.yaml
:
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
google_maps_flutter: ^0.5.28+1
functional_widget_annotation: ^0.5.1
geolocator: ^5.3.2+2
rxdart: ^0.24.1
flutter:
sdk: flutter
openapi:
path: gen
builders:
functional_widget: ^0.7.3
I am using latest stable version of Flutter:
Flutter 1.17.5 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 8af6b2f038 (5 days ago) • 2020-06-30 12:53:55 -0700
Engine • revision ee76268252
Tools • Dart 2.8.4
What I have already tried:
dependency_override
for build_runner
or build_config
- doesn't seem work.master
branch of Flutter SDK - same behavior.build_runner: 1.9.0
to flutter_tool
- breaks the package.Any ideas how to make it work?
We know that we can use kernel-to-kernel transformation to change the dill
(dart intermediate language). There is already some libraries, such as https://github.com/alibaba-flutter/aspectd, which uses this to modify the code during compilation. Therefore, I think we can do the same thing to transform the functional_widget
s. :)
P.S. This article explains this technique, but it is only in Chinese...
It is theoretically possible to make analyzer plugins using https://pub.dartlang.org/packages/analyzer_plugin
It could be interesting to make one so that renaming a function correctly renames the class too.
It may be interesting to allow enabling/disabled the new operator==
and debugFillProperties
features.
We could allow changing the default behavior through build.yaml
. And then have widget specific override using a custom decorator:
@FunctionalWidget.hook(overrideEquals: true, overrideDebugFillProperties: true)
Widget foo() {
}
I tried to install the last version, however I get the following error:
The current Dart SDK version is 2.1.0-dev.9.4.flutter-f9ebf21297.
Because project requires SDK version >=2.1.0 <3.0.0, version solving failed.
pub get failed (1)
exit code 1
I guess this issue is same with #55 (comment),
but my sdk is stable channel v1.12.13+hotfix.8
try with:
functional_widget_annotation: ^0.5.1
functional_widget: ^0.7.2
when i run the app, error occurs.
the output is:
`generating build script... 31.9s
Exception: Error generating build_script snapshot: ../../../base/flutterSDK/flutter/.pub-cache/hosted/pub.flutter-io.cn/functional_widget-0.7.2/lib/function_to_widget_class.dart:216:43: Error: The getter 'isUndefined' isn't defined for the class 'DartType'.
I am not exactly sure if it's related to #70 but as soon as I added import 'package:functional_widget_annotation/functional_widget_annotation.dart';
in a stateful widget, my calls from the private class to wiget.whatEverHere threw errors throughout the entirety of the class, so I could not do anything at that point and had to remove it before I had the opportunity to test it out.
Is there a restriction of wigets having to originate in a stateless class and I just missed the note on it? I read through the readme and don't recall seeing it.
Thanks,
-MH
It would be nice to decorate _example and generate Example so that users don't refer to _example by accident.
Does declaring a widget as a function support parameters's assert?
Most of the times I writ my code as:
class MyWidget extends StatelessWidget {
final int valueA;
final int valueB;
MyWidget({this.valueA, this.valueB})
: assert(valueA != null),
assert(valueB != 1);
@override
Widget build(BuildContext context) {
return Container();
}
}
How do I write the assert so that this package can apply in the generated widget?
If I write it in the fuction it will be moved in the generated widget as well?
Documentation for parameters is actually possible using the following syntax:
/// Function doc
///
/// * [pameter] documentation for parameter
void function(String parameter) {
}
It would be interesting to extract these
@widget
Widget foo({int a = 42}) {
}
this is my simple class which i want to use @fn.widget
in that, but after 3 hours that i try to make class for building widget as class i can't.
i don't get any error
...
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:functional_widget_annotation/functional_widget_annotation.dart' as fn;
...
part 'activity_show_post_content.g.dart';
class ActivityShowPostContent extends StatefulWidget {
final int postId;
ActivityShowPostContent({@required this.postId});
@override
_ActivityShowPostContentState createState() => _ActivityShowPostContentState();
}
class _ActivityShowPostContentState extends State<ActivityShowPostContent> {
int get _postId => widget.postId;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: FutureBuilder(
future: Provider.of<DiabetistApiService>(context).getSinglePost(_postId),
builder: (context,snapshot){
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
return Text(snapshot.data);
} else {
return _loader(context,"List is empty");
}
}
return _loader(context,Strings.pleaseWait);
},
),
));
}
@fn.widget
Widget _loader(BuildContext context, String message){
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
ColorLoader3(
radius: 25.0,
dotRadius: 5.0,
),
Padding(
padding: const EdgeInsets.all(3.0),
child: Text(
message,
style: AppTheme(context).caption(),
),
),
],
));
}
}
and this is build output in console:
E:\Projects\Flutter\project>flutter packages pub run build_runner build
[INFO] Generating build script...
[INFO] Generating build script completed, took 1.3s
[INFO] Initializing inputs
[INFO] Reading cached asset graph...
[INFO] Reading cached asset graph completed, took 1.0s
[INFO] Checking for updates since last build...
[INFO] Checking for updates since last build completed, took 3.7s
[INFO] Running build...
[INFO] 1.1s elapsed, 0/12 actions completed.
[INFO] 2.3s elapsed, 0/12 actions completed.
[INFO] 3.5s elapsed, 0/12 actions completed.
[INFO] 4.6s elapsed, 0/12 actions completed.
[INFO] 5.9s elapsed, 0/12 actions completed.
[INFO] 7.2s elapsed, 0/12 actions completed.
[INFO] 8.5s elapsed, 0/12 actions completed.
[INFO] 9.6s elapsed, 0/12 actions completed.
[INFO] 10.8s elapsed, 0/12 actions completed.
[INFO] 25.7s elapsed, 1/12 actions completed.
[INFO] 27.1s elapsed, 1/12 actions completed.
[INFO] 30.1s elapsed, 2/12 actions completed.
[INFO] 31.2s elapsed, 11/12 actions completed.
[INFO] 32.7s elapsed, 12/12 actions completed.
[INFO] 33.7s elapsed, 24/24 actions completed.
[INFO] 34.8s elapsed, 36/36 actions completed.
[INFO] 36.0s elapsed, 48/48 actions completed.
[INFO] 37.1s elapsed, 60/60 actions completed.
[INFO] 38.2s elapsed, 69/75 actions completed.
[INFO] Running build completed, took 38.4s
[INFO] Caching finalized dependency graph...
[INFO] Caching finalized dependency graph completed, took 638ms
[INFO] Succeeded after 39.0s with 0 outputs (75 actions)
--------------------------------------------------------------------------
E:\Projects\Flutter\project>flutter packages pub run build_runner build
[INFO] Generating build script...
[INFO] Generating build script completed, took 1.2s
[INFO] Initializing inputs
[INFO] Reading cached asset graph...
[INFO] Reading cached asset graph completed, took 1.1s
[INFO] Checking for updates since last build...
[INFO] Checking for updates since last build completed, took 2.9s
[INFO] Running build...
[INFO] Running build completed, took 303ms
[INFO] Caching finalized dependency graph...
[INFO] Caching finalized dependency graph completed, took 565ms
[INFO] Succeeded after 915ms with 0 outputs (0 actions)
Example:
@widget
Widget foo(String foo) => Text(foo);
functional_widget generates a widget class for this, but it doesn't compile because the field name in the generated class shadows the function.
I don't think it's possible to fix this issue, so perhaps the best path is to print an error in this case.
Types coming from dart:ui
are generated as dynamic
instead of their real type.
I like both functional_widget and nested packages:
@nwidget
Widget w1() => child;
@nwidget
Widget w2() => child;
@swidget
Widget wBoth() => Nested(
children: [
W1(),
W2(),
],
child: Text('Great!'),
)
I am trying to get a hook for a ScrollController
.
The naive approach doesn't work:
final controller = useListenable(ScrollController());
So, the question is how one can build a simple hook from a disposable that is only instantiated in the first build.
I am using functional_widget for a long time (on both dev and master flutter dev channels).
After upgrading flutter dev channel last week, functional_widget-0.7.2
stops working (0.7.1 works well):
flutter pub pub run build_runner watch
[INFO] Generating build script...
[INFO] Generating build script completed, took 604ms
[INFO] Creating build script snapshot......
[INFO] Creating build script snapshot... completed, took 7.5s
[SEVERE] Failed to snapshot build script .dart_tool/build/entrypoint/build.dart.
This is likely caused by a misconfigured builder definition.
[SEVERE] /C:/Users/pzika/AppData/Roaming/Pub/Cache/hosted/pub.dartlang.org/functional_widget-0.7.2/lib/function_to_widget_class.dart:216:43: Error: The getter 'isUndefined' isn't defined for the class 'DartType'. - 'DartType' is from 'package:analyzer/dart/element/type.dart' ('/C:/Users/pzika/AppData/Roaming/Pub/Cache/hosted/pub.dartlang.org/analyzer-0.39.4/lib/dart/element/type.dart').Try correcting the name to the name of an existing getter, or defining a getter or field named 'isUndefined'. 'DiagnosticsProperty<${element.type.isUndefined ? findBeginToken(element) : element.type.displayName}>'; ^^^^^^^^^^^/C:/Users/pzika/AppData/Roaming/Pub/Cache/hosted/pub.dartlang.org/functional_widget-0.7.2/lib/src/parameters.dart:57:20: Error: The gettePS
C:\wikibulary\dart\know_how> flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel dev, v1.15.3, on Microsoft Windows [Version 10.0.18362.657], locale cs-CZ)
[!] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
X No Java Development Kit (JDK) found; You must have the environment variable JAVA_HOME set and the java
binary in your PATH. You can download the JDK from
https://www.oracle.com/technetwork/java/javase/downloads/.
[√] Chrome - develop for the web
[!] Android Studio (version 3.5)
X Flutter plugin not installed; this adds Flutter specific functionality.
X Dart plugin not installed; this adds Dart specific functionality.
X Unable to determine bundled Java version.
[√] VS Code (version 1.42.1)
[√] Connected device (2 available)
! Doctor found issues in 2 categories.
PS C:\wikibulary\dart\know_how>
It simply does not working (nothing generates).
That's my steps:
part 'checkup_results_screen.g.dart';
(not mentioned in docs but I guess it is needed)build
word.My pubspec:
I also tried to put functional_widget
into dev_dependencies
For a cool integration with the widget inspector, we can generate debugFillProperties
.
i think this code:
@widget
Widget _loader(BuildContext context, String message) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
ColorLoader3(
radius: 25.0,
dotRadius: 5.0,
),
Padding(
padding: const EdgeInsets.all(3.0),
child: Text(
Strings.pleaseWait,
style: AppTheme(context).caption().copyWith(color: Colors.red[900]),
),
),
],
));
}
should be build this class:
class _Loader extends StatelessWidget {
const _Loader(this.message, {Key key}) : super(key: key);
final String message;
@override
Widget build(BuildContext _context) => Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
ColorLoader3(
radius: 25.0,
dotRadius: 5.0,
),
Padding(
padding: const EdgeInsets.all(3.0),
child: Text(
Strings.pleaseWait,
style: AppTheme(_context).caption().copyWith(color: Colors.red[900]),
),
),
],
));
}
but i have:
class _Loader extends StatelessWidget {
const _Loader(this.message, {Key key}) : super(key: key);
final String message;
@override
Widget build(BuildContext _context) => _loader(_context, message);
}
lets say in some class i need to init something in the constructor:
class _MyPageViewState extends State<MyPageView> {
PageController _pageController;
@override
void initState() {
super.initState();
_pageController = PageController();
}
}
what is the correct way to achive it using functional widget - is this correct:
@hwidget
Widget app(int value) {
final index = useState(0);
PageController _pageController = PageController(initialPage: 0);
void _onItemTapped(int i) {
index.value = i;
_pageController.animateToPage(i,
duration: Duration(milliseconds: 500), curve: Curves.easeOut);
}
return Scaffold(); // some widet uses this pageController
}
I know there is usePageController
but for the sake of it - what if i need to initialize something ? or write a callback inside the functional widget - is this cause performance issues when build trigger ?
Cause in class functions and properties are separate from the build funciton - what is the best practice to do it in functional widget ?
In Dart, List
s don't do deep hashCode or operator==, i.e. ['a'].hashCode != ['a'].hashCode
and ['a'] != ['a']
.
Should functional_widget
detect Lists and provide deep hashCode/==?
Generic functions should be supported
@widget
Widget foo<T extends Something>(T value) {
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.