Flutte Floor: There are no type converts defined even though the #TypeConverters annotation is used - flutter

everything was working fine until last build, where it displays the following error:
[INFO] Running build...
[SEVERE] floor_generator:floor_generator on lib/db/app_database.dart:
There are no type converts defined even though the #TypeConverters annotation is used.
package:apoce/db/app_database.dart:24:16
╷
24 │ abstract class AppDatabase extends FloorDatabase {
│ ^^^^^^^^^^^
╵
[INFO] Running build completed, took 1.3s
[INFO] Caching finalized dependency graph...
[INFO] Caching finalized dependency graph completed, took 53ms
I'm not sure why it's showing this error, I googled for a while but it appears no one has got same at first glance.
My database class is:
import 'dart:async';
import 'package:apoce/db/FormFieldsDao.dart';
import 'package:apoce/db/FormsDao.dart';
import 'package:apoce/db/HashDao.dart';
import 'package:apoce/db_converters/list_choices.converter.dart';
import 'package:apoce/db_converters/list_fieldsets.converter.dart';
import 'package:apoce/db_converters/list_questions.converter.dart';
import 'package:apoce/db_converters/list_string.converter.dart';
import 'package:apoce/models/FormFields.dart';
import 'package:apoce/models/Forms.dart';
import 'package:apoce/models/Question.dart';
import 'package:apoce/models/choice.dart';
import 'package:apoce/models/hash.dart';
import 'package:floor/floor.dart';
import 'package:sqflite/sqflite.dart' as sqflite;
part 'app_database.g.dart'; // the generated code will be there
#TypeConverters([
StringListConverter,
FiledSetsListConverter,
QuestionsListConverter,
ChoicesListConverter,
])
#Database(version: 5, entities: [Forms, FormFields, Hashes, Question, Choice])
abstract class AppDatabase extends FloorDatabase {
//static Future<AppDatabase> openDatabase() async => _$open();
FormsDao get formsDao;
FormFieldsDao get formFieldsDao;
HashDao get hashDao;
}
My pubspec.yaml
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
floor: ^0.17.0
dio: ^3.0.10
freezed: ^0.12.2
flutter_bloc: ^6.1.1
dependency_overrides:
analyzer: '0.40.4'
Thank you.

Related

Why is my flutter code generation using `build_runner` and `source_gen` not creating output files?

I am trying to create a code generation package within Flutter using the build_runner and source_gen packages. I've looked over numerous examples but cannot seem to find what is preventing my output files from being created. I know it's probably something stupid, but I've been trying for days and cannot seem to find the problem.
So far, I've got the following directory structure:
─┬ fletch
├── fletch_annotations
├── fletch_example
└── fletch_generator
fletch_annotations has annotation classes like the following:
package:fletch_annotations/src/model/annotation/column.dart
import 'package:fletch_annotations/src/model/enum/enum.dart';
class Column {
final FletchDataType dataType;
final bool isNullable;
final OnConflictAction onConflictAction;
final OnDeleteAction onDeleteAction;
final OnUpdateAction onUpdateAction;
final bool isUnique;
final String? columnName;
final dynamic defaultValue;
final String? check;
const Column({
required this.dataType,
required this.isNullable,
this.onConflictAction = OnConflictAction.abort,
this.onDeleteAction = OnDeleteAction.setDefault,
this.onUpdateAction = OnUpdateAction.setDefault,
this.isUnique = false,
this.columnName,
this.defaultValue,
this.check,
});
}
In fletch_generator, I have the following pubspec.yaml file:
fletch_generator/pubspec.yaml
name: fletch_generator
description: A new Flutter package project.
version: 0.0.1
homepage: https://example.com #! TODO: Replace this
environment:
sdk: ">=2.18.4 <3.0.0"
dependencies:
analyzer: ^5.3.1
build: ^2.3.1
collection: ^1.17.0
fletch_annotations:
path: ../fletch_annotations
source_gen: ^1.2.6
dev_dependencies:
build_config: ^1.1.1
build_runner: ^2.3.2
build_test: ^2.1.5
flutter_lints: ^2.0.1
test: ^1.22.1
fletch_generator has corresponding model classes:
package:fletch_generator/src/model/column.dart
import 'package:fletch_annotations/fletch_annotations.dart';
class Column {
final FletchDataType dataType;
final bool isNullable;
final OnConflictAction onConflictAction;
final OnDeleteAction onDeleteAction;
final OnUpdateAction onUpdateAction;
final bool isUnique;
final String? columnName;
final dynamic defaultValue;
final String? check;
Column({
required this.dataType,
required this.isNullable,
this.onConflictAction = OnConflictAction.abort,
this.onDeleteAction = OnDeleteAction.setDefault,
this.onUpdateAction = OnUpdateAction.setDefault,
this.isUnique = false,
this.columnName,
this.defaultValue,
this.check,
});
#override
bool operator ==(Object other) =>
identical(this, other) ||
other is Column &&
runtimeType == other.runtimeType &&
dataType == other.dataType &&
isNullable == other.isNullable &&
onConflictAction == other.onConflictAction &&
onDeleteAction == other.onDeleteAction &&
onUpdateAction == other.onUpdateAction &&
isUnique == other.isUnique &&
columnName == other.columnName &&
defaultValue == other.defaultValue &&
check == other.check;
#override
int get hashCode {
return Object.hash(dataType, columnName, defaultValue, check);
}
#override
String toString() {
return 'Column('
'dataType: $dataType, '
'isNullable: $isNullable ,'
'onConflictAction: $onConflictAction ,'
'onDeleteAction: $onDeleteAction ,'
'onUpdateAction: $onUpdateAction ,'
'isUnique: $isUnique ,'
'columnName: $columnName, '
'defaultValue: $defaultValue, '
'check: $check'
')';
}
}
My build.yaml file in fletch_generator:
fletch_generator/build.yaml
targets:
$default:
builders:
fletch_generator:
enabled: true
source_gen|combining_builder:
enabled: true
options:
ignore_for_file:
- lines_longer_than_80_chars
- lint_alpha
- lint_beta
build_extensions: '"{{dir}}/entity/{{file}}.dart": "{{dir}}/dao/{{file}}.g.dart"'
builders:
fletch_generator:
import: "package:fletch_generator/builder.dart"
builder_factories: ["fletchBuilder"]
build_extensions: { ".dart": [".fletch.g.part"] }
auto_apply: dependents
build_to: cache
applies_builders: ["source_gen|combining_builder"]
build.dart, also in fletch_generator (in the lib directory):
package:fletch_generator/build.dart
import 'package:build/build.dart';
import 'package:fletch_generator/src/generator/column.dart';
import 'package:source_gen/source_gen.dart';
Builder fletchBuilder(final BuilderOptions _) =>
SharedPartBuilder([ColumnGenerator()], 'fletch');
And finally, the fletch_generator definition for ColumnGenerator:
package:fletch_generator/src/generator/column.dart
import 'dart:async';
import 'package:analyzer/dart/element/element.dart';
import 'package:build/build.dart';
import 'package:fletch_annotations/fletch_annotations.dart' as annotations;
import 'package:source_gen/source_gen.dart';
class ColumnGenerator extends GeneratorForAnnotation<annotations.Column> {
#override
FutureOr<String> generateForAnnotatedElement(
Element element,
ConstantReader annotation,
BuildStep buildStep,
) {
return '// ColumnProcessor works!';
}
}
In fletch_example, I have a sample_class that utilizes the Column annotation:
`package:fletch_example/src/model/entity/sample_class.dart
import 'package:fletch_annotations/fletch_annotations.dart';
part '../dao/sample_class.g.dart';
class SampleClass {
#Column(
dataType: FletchDataType.bigInt,
isNullable: false,
)
final int? sampleClassIndex;
SampleClass({
this.sampleClassIndex,
});
}
As well as the appropriate dependencies in the pubspec.yaml file for fletch_example:
name: fletch_example
description: A starting point for Dart libraries or applications.
version: 1.0.0
# homepage: https://www.example.com
environment:
sdk: ">=2.18.4 <3.0.0"
dependencies:
fletch_annotations:
path: ../fletch_annotations
dev_dependencies:
build_runner: ^2.3.2
fletch_generator:
path: ../fletch_generator
flutter_lints: ^2.0.1
lints: ^2.0.0
test: ^1.16.0
In my fletch_example directory, I run the following commands:
flutter clean
flutter pub get
flutter packages pub run build_runner build --delete-conflicting-outputs
This generates the following console output:
[INFO] Generating build script...
[INFO] Generating build script completed, took 525ms
[INFO] Precompiling build script......
[INFO] Precompiling build script... completed, took 9.5s
[INFO] Initializing inputs
[INFO] Building new asset graph...
[INFO] Building new asset graph completed, took 1.3s
[INFO] Checking for unexpected pre-existing outputs....
[INFO] Checking for unexpected pre-existing outputs. completed, took 1ms
[INFO] Running build...
[INFO] Generating SDK summary...
[INFO] 2.8s elapsed, 0/1 actions completed.
[INFO] 5.3s elapsed, 0/1 actions completed.
[INFO] Generating SDK summary completed, took 6.2s
[INFO] Running build completed, took 6.3s
[INFO] Caching finalized dependency graph...
[INFO] Caching finalized dependency graph completed, took 40ms
[INFO] Succeeded after 6.4s with 0 outputs (2 actions)
It also creates the following fletch_example/.dart_tool/build/entrypoint/build.dart file:
// ignore_for_file: directives_ordering
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'package:build_runner_core/build_runner_core.dart' as _i1;
import 'package:fletch_generator/builder.dart' as _i2;
import 'package:source_gen/builder.dart' as _i3;
import 'dart:isolate' as _i4;
import 'package:build_runner/build_runner.dart' as _i5;
import 'dart:io' as _i6;
final _builders = <_i1.BuilderApplication>[
_i1.apply(
r'fletch_generator:fletch_generator',
[_i2.fletchBuilder],
_i1.toDependentsOf(r'fletch_generator'),
hideOutput: true,
appliesBuilders: const [r'source_gen:combining_builder'],
),
_i1.apply(
r'source_gen:combining_builder',
[_i3.combiningBuilder],
_i1.toNoneByDefault(),
hideOutput: false,
appliesBuilders: const [r'source_gen:part_cleanup'],
),
_i1.applyPostProcess(
r'source_gen:part_cleanup',
_i3.partCleanup,
),
];
void main(
List<String> args, [
_i4.SendPort? sendPort,
]) async {
var result = await _i5.run(
args,
_builders,
);
sendPort?.send(result);
_i6.exitCode = result;
}
My expectation is that a fletch_example/lib/src/model/dao/sample_class.g.dart file would be created containing the following:
// ColumnProcessor works!
If anyone could point me in the right direction, it would be so, incredibly appreciated!
A GeneratorForAnnotation only runs for top-level elements (like classes or top-level fields or methods) in a library. In your example, the #Column annotation is added to an instance member which does not trigger the generator.
If you can, the easiest way to fix this would be to exceptionally change your generator so that classes with #Column annotations on their fields also need an annotation on the class declaration.
Alternatively, you could use something like this to respect column annotations in class members as well:
class ColumnGenerator extends Generator {
static const _checker = TypeChecker.fromRuntime(annotations.Column);
#override
Future<String> generate(LibraryReader library, BuildStep buildStep) async {
final values = <String>{};
for (final classMember in library.classes) {
for (final child in classMember.children) {
final annotation = _checker.firstAnnotationOf(child);
if (annotation != null) {
values.add(await generateForAnnotatedElement(
child, ConstantReader(annotation), buildStep));
}
}
}
return values.join('\n\n');
}
FutureOr<String> generateForAnnotatedElement(
Element element,
ConstantReader annotation,
BuildStep buildStep,
) {
return '// ColumnProcessor works!';
}
}

Flutter: I get an error when running the official document unit test sample

https://flutter.dev/docs/cookbook/testing/unit/introduction
I am trying to run the unit test sample on the above page as is,
When I run it, I get an error.
flu_basic/
lib/
main.dart
test/
counter_test.dart
//main.dart
class Counter {
int value = 0;
void increment() => value++;
void decrement() => value--;
}
//counter_test.dart
import 'package:test/test.dart';
import 'package:flu_basic/main.dart';
void main() {
group('Counter🐭', () {
test('value should start at 0', () {
expect(Counter().value, 0);
});
test('value should be incremented♉️', () {
final counter = Counter();
counter.increment();
expect(counter.value, 1);
});
test('value should be decremented🐯', () {
final counter = Counter();
counter.decrement();
expect(counter.value, -1);
});
});
}
//part of dev_dependencies of pubspec.yaml file
dev_dependencies:
test: ^1.15.3
When I run the following in terminal
flutter test test/counter_test.dart
Running "flutter pub get" in flu_basic... 0.6s
00:00 +0: loading /Users/userno1/dev2/flu_basic/test/counter_test.dart
Error: cannot run without a dependency on "package:flutter_test". Ensure the following lines are present in your
pubspec.yaml:
dev_dependencies:
flutter_test:
sdk: flutter
00:00 +0 -1: loading /Users/userno1/dev2/flu_basic/test/counter_test.dart [E]
Failed to load "/Users/userno1/dev2/flu_basic/test/counter_test.dart":
Compilation failed
Test: /Users/userno1/dev2/flu_basic/test/counter_test.dart
Shell: /Users/userno1/dev2/flutter/bin/cache/artifacts/engine/darwin-x64/flutter_tester
00:00 +0 -1: Some tests failed.
I get the above error.
part of dev_dependencies of pubspec.yaml file like below↓
dev_dependencies:
#test: ^1.15.3 ←comment out
flutter_test:
sdk: flutter
00:00 +0: loading /Users/userno1/dev2/flu_basic/test/counter_test.dart Error: Could not resolve the package 'test' in 'package:test/test.dart'.
test/counter_test.dart:4:8: Error: Not found: 'package:test/test.dart'
import 'package:test/test.dart';
^
00:02 +0: loading /Users/userno1/dev2/flu_basic/test/counter_test.dart test/counter_test.dart:10:7: Error: Method not found: 'expect'.
expect(Counter().value, 0);
^^^^^^
test/counter_test.dart:9:5: Error: Method not found: 'test'.
test('value should start at 0', () {
^^^^
test/counter_test.dart:18:7: Error: Method not found: 'expect'.
expect(counter.value, 1);
^^^^^^
test/counter_test.dart:13:5: Error: Method not found: 'test'.
test('value should be incremented♉️', () {
^^^^
test/counter_test.dart:26:7: Error: Method not found: 'expect'.
expect(counter.value, -1);
^^^^^^
test/counter_test.dart:21:5: Error: Method not found: 'test'.
test('value should be decremented🐯', () {
^^^^
test/counter_test.dart:8:3: Error: Method not found: 'group'.
group('Counter🐭', () {
^^^^^
00:06 +0 -1: loading /Users/userno1/dev2/flu_basic/test/counter_test.dart [E]
Failed to load "/Users/userno1/dev2/flu_basic/test/counter_test.dart":
Compilation failed
Test: /Users/userno1/dev2/flu_basic/test/counter_test.dart
Shell: /Users/userno1/dev2/flutter/bin/cache/artifacts/engine/darwin-x64/flutter_tester
00:06 +0 -1: Some tests failed.
I get the above error.
Maybe on the page above
1.Add the test dependency
I think it's a problem with the part, but I don't know what to do.
What's wrong?
You should only use the test package If you’re working on a Dart package that does not depend on Flutter. From the look of it, your project requires flutter so rather than the dev dependencies you're using at the moment, you should use the following
dev_dependencies:
flutter_test:
sdk: flutter
and import the flutter_test package
import 'package:flutter_test/flutter_test.dart';

Generating dart json_seriaziable file wont work

I have a Dart class that I want to automatically serialize to and from json. However, I can't generate the part file for it.
root#430f48d3ead0:/workspaces/zstore/src# pub run build_runner build
[INFO] Generating build script completed, took 464ms
[INFO] Reading cached asset graph completed, took 123ms
[INFO] Checking for updates since last build completed, took 666ms
[INFO] Running build completed, took 19ms
[INFO] Caching finalized dependency graph completed, took 174ms
[INFO] Succeeded after 241ms with 0 outputs (0 actions)
Here's my file order.dart
import 'package:json_annotation/json_annotation.dart';
import 'product.dart';
part 'order.g.dart';
#JsonSerializable()
class Order {
String _id;
bool deleted;
String clientName;
String clientPhone;
DateTime date;
int orderNumber;
String observations;
List<Product> products;
double total;
factory Order.fromJson(Map<String, dynamic> json) => _$OrderFromJson(json);
Map<String, dynamic> toJson() => _$OrderToJson(this);
}
I got no errors in the output of the command as you can see, but I also get no order.g.dart file
pubspec.yaml:
name: zstore
description: Simple store api
environment:
sdk: '>=2.1.0 <3.0.0'
dependencies:
json_annotation: ^3.0.1
dev_dependencies:
build_runner: ^1.7.4
json_serializable: ^3.2.5
test: ^1.0.0

app database generated file having errors in moor flutter

I am using moor package in flutter for my application. im following the instructions online
https://moor.simonbinder.eu/docs/getting-started/starting_with_sql/#what-moor-generates
but when i run the build command: flutter pub run build_runner build
the appdatabase.g.dart file that gets generated has errors. here is a snapshot of errors:
here is my dependencies
cupertino_icons: ^0.1.2
month_picker_dialog: ^0.3.1
flutter_cupertino_localizations: ^1.0.1
moor: ^2.3.0
provider: ^4.0.3
moor_ffi: ^0.4.0
path_provider: ^1.6.0
dev_dependencies:
flutter_test:
sdk: flutter
intl_translation: ^0.17.1
moor_generator: ^2.3.1
build_runner:
the problem seems to be with 'Table' class. there is a conflict between dart and moor. the message indicate there are two versions. how can i solve this problem so that my error goes away
the answer is to use import 'package:flutter/widgets.dart' hide Table;
dependencies:
flutter:
sdk: flutter
#moor database
moor_flutter: ^3.1.0
# For the UI
provider: ^4.3.1
# For OS-specific directory paths
path_provider: ^1.6.11
cupertino_icons: ^0.1.3
dev_dependencies:
flutter_test:
sdk: flutter
#new Dependencies add
moor_generator: ^3.2.0
build_runner:
Step 1 : delete file appdatabase.g.dart
step 2: flutter clean
Step 3: flutter pub get
Step 4: flutter pub run build_runner build watch
This error occurs when you don't have the 'import' of your table or dao in your AppDb class, in my case I have more than 90 tables and dao's, I separated then in a class with a static list, but I need do the imports of my files in the app_database.dart too, because of the error.
I have this class for tables:
import '../tables/table_one.dart';
import '../tables/table_two.dart';
class TableList {
static const List<Type> tables = [
TableOne,
TableTwo,
]
}
And another for Dao files:
import '../dao/table_one_dao.dart';
import '../dao/table_two_dao.dart';
class DaoList{
static const List<Type> daos= [
TableOne,
TableTwo,
]
}
And this is my AppDb class:
import '../tables/table_one.dart';
import '../tables/table_two.dart';
import '../dao/table_one_dao.dart';
import '../dao/table_two_dao.dart';
part 'app_db.g.dart';
#DriftDatabase(
tables: TableList.tables,
daos: DaoList.daos,
)
class AppDb extends _$AppDb {
AppDb() : super(_openConnection());
#override
int get schemaVersion => 1;
}
LazyDatabase _openConnection() {
return LazyDatabase(() async {
final dbFolder = await getApplicationDocumentsDirectory();
final file = File(p.join(dbFolder.path, 'app_database.db'));
return NativeDatabase(file);
});
}
As you see, i have to declare the imports again in my AppDb file to resolve. If you declare your tables directly in the AppDb escope, i think you don't have problem.

Migrating to angulardart 4.0.0 fails with message Unsupported operation: Using the 'angular2' transformer is required

I just migrated my project from angulardart 3.1.0 to 4.0.0 my pubspec.yaml was:
dependencies:
angular2: ^3.1.0
http: ^0.11.0
#...other deps
dev_dependencies:
browser: ^0.10.0
dart_to_js_script_rewriter: ^1.0.1
transformers:
- angular2:
platform_directives:
- 'package:angular2/common.dart#COMMON_DIRECTIVES'
platform_pipes:
- 'package:angular2/common.dart#COMMON_PIPES'
entry_points: web/main.dart
resolved_identifiers:
BrowserClient: 'package:http/browser_client.dart'
Client: 'package:http/http.dart'
- dart_to_js_script_rewriter
- $dart2js:
sourceMaps: true
and became :
dependencies:
angular: ^4.0.0
angular_router: ^1.0.2
angular_components: ^0.8.0
http: ^0.11.0
#... other deps
dev_dependencies:
browser: ^0.10.0
dart_to_js_script_rewriter: ^1.0.1
transformers:
- angular:
entry_points: web/main.dart
- $dart2js:
sourceMaps: true
- dart_to_js_script_rewriter
My issue is that in dartium (Version 50.0.2661.108 (64-bit) "on mac") I have this error on startup:
VM970:1 Uncaught Unhandled exception:
Unsupported operation: Using the 'angular2' transformer is required.
Please see https://webdev.dartlang.org/angular/tutorial for setup instructions,
and ensure your 'pubspec.yaml' file is configured to invoke the 'angular2'
transformer on your application's entry point.
#0 bootstrap (package:angular/src/platform/bootstrap.dart:107:5)
#1 main (http://localhost:3000/web/main.dart:50:3)
<asynchronous suspension>
And when I try to run pub build it does not recognize ngIf and ngFor :
Error: Template parse errors: line 13, column 11 of UserListPopup: ParseErrorLevel.FATAL: Property binding ngIf not used by any directive on an embedded template
For reference, this is my entire pubspec.yaml now:
name: share_place
description: Collaborate around your documents in a seamless way
version: 0.0.1
environment:
sdk: '>=1.24.0 <2.0.0'
dependencies:
angular: ^4.0.0
angular_router: ^1.0.2
angular_components: ^0.8.0
http: ^0.11.0
stream_transformers: ^0.3.0
http_server: any
js: ^0.6.0
uuid: ^0.5.3
croppie_dart: ^2.4.1
stack_trace: any
source_map_stack_trace: any
source_maps: any
validator: ">=0.0.4 <0.1.0"
dev_dependencies:
browser: ^0.10.0
dart_to_js_script_rewriter: ^1.0.1
transformers:
- angular:
entry_points:
- web/main.dart
- $dart2js:
sourceMaps: true
- dart_to_js_script_rewriter
This is reproducible on twos machines I tested to upgrade dart on (windows and mac). I still didn't try to uninstall reinstall
Here's the content of my main.dart there's nothing special I think:
int version;
Future loadLastVersion() async {
String version = await html.HttpRequest.getString('/sp/util/loadAppVersion');
if (conf.appVersion != version) {
if (conf.isWebApp) {
html.window.alert("you have an old version : ${conf.appVersion} we must load the new version :${version}");
html.window.location.assign("${conf.remoteUrl}/v${version}");
} else {
html.window.alert("A new version ${version} is available! Please download it from : https://www.share.place/downloads");
}
}
}
Future main() async {
loadLastVersion();
Logger.root.level = Level.FINE;
Logger.root.onRecord.listen((LogRecord rec) {
if (rec.level == Level.SEVERE || rec.level == Level.WARNING)
html.window.console.error('${rec.level.name} - ${rec.loggerName} : ${rec.message}');
else if (rec.level == Level.INFO)
html.window.console.info('${rec.level.name} - ${rec.loggerName} : ${rec.message}');
else
html.window.console.debug('${rec.level.name} - ${rec.loggerName} : ${rec.message}');
});
bootstrap(AppComponent, [provide(Client, useClass: BrowserDataService), provide(ExceptionHandler, useClass: ErrorHandler), Environment, EventBus]
// Using a real back end? Import browser_client.dart and change the above to
// [provide(Client, useFactory: () => new BrowserClient(), deps: [])]
);
}
This is not supported anymore
platform_directives:
- 'package:angular2/common.dart#COMMON_DIRECTIVES'
platform_pipes:
- 'package:angular2/common.dart#COMMON_PIPES'
You need to add to #Component(...)
directives: const [COMMON_DIRECTIVES]
pipes: const [COMMON_PIPES]
to every component where you use them.