Whenever I try to run flutter packages pub run build_runner watch I get this error message in the Terminal
Failed to precompile build_runner:build_runner:
/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/dart_style-1.3.3/lib/src/dart_formatter.dart:105:30: Error: Too
many positional arguments: 0 allowed, but 1 found.
Try removing the extra positional arguments.
scanner.configureFeatures(featureSet);
^
pub finished with exit code 1
this happend after i update moor_flutter plugin from ^1.6.0 => ^ 3.0.0
There is no errors with the older plugin
This is my code
import 'package:moor_flutter/moor_flutter.dart';
part 'Database.g.dart';
class Users extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get name => text().withLength(min:1,max:50)();
TextColumn get mobile => text().withLength(min:1,max:25)();
DateTimeColumn get birthdate => dateTime()();
}
#UseMoor(tables : [Users ],daos:[UserDao])
class AppDatabase extends _$AppDatabase {
AppDatabase():super(FlutterQueryExecutor.inDatabaseFolder(path: 'db.sqlite',
logStatements: true));
#override
int get schemaVersion =>1;
}
#UseDao(tables:[Users ],)
class UserDao extends DatabaseAccessor<AppDatabase> with _$UserDaoMixin{
final AppDatabase db;
UserDao(this.db):super(db);
Future <List<User>> getAllUsers() => select(users).get();
Stream <List<User>> watchAllUsers() {
return (select(users)
..orderBy([
(p)=> OrderingTerm(expression:p.id,mode:OrderingMode.desc ),
// (p)=> OrderingTerm(expression:p.id,mode:Ordering.desc )
])
)
.watch();
}
Stream <List<User>> watchUsersByName(String txt) {
String qu="SELECT * FROM users where ";
for (int i = 0; i < txt.length-1; i++){
String c = txt[i];
qu=qu+"name like '%"+c+"%' and ";
}
qu=qu+"name like '%"+txt[txt.length-1]+"%' ORDER BY id DESC";
return customSelectStream(
qu,readsFrom: {users}
).map((rows){
return rows.map((row) => User.fromData(row.data,db)).toList();
});
}
Future insertUser(Insertable<User> user) => into(users).insert(user);
Future updateUser(Insertable<User> user) => update(users).replace(user);
Future deleteUser(Insertable<User> user) => delete(users).delete(user);
}
the vs code gives me errors in the Appdatabase constructor and customselectstream function but
I searched the example in their Github repository and found the Appdatabase constructor is the same as mine.
The problem still presists after I commented the watchusersbyname also I tried to remove the arguments from super in the Appdatabase constructor but nothing changed
so can you please tell me what is the problem?
Thanks in advance.
Here is the one command which you need to run and check for the solution
flutter pub upgrade
Related
https://dartpad.dev/?
import 'package:starter/stack.dart';
void main() {
print (calculation("(2+2*6"));
}
calculation(expression){
var tokens = expression.split(" ");
Stack values = Stack();
Stack ops = Stack();
}
note that if I remove the import (first line) I get this error message "The function 'Stack' isn't defined."
and when I add the import the error message is "Unsupported import(s): (package:starter/stack.dart)".
Stack is not built in the dart. But we can make a generic class with its methods(get, push, pop) implementation using list.
class CustomStack<T> {
final _list = <T>[];
void push(T value) => _list.add(value);
T pop() => _list.removeLast();
T get top => _list.last;
bool get isEmpty => _list.isEmpty;
bool get isNotEmpty => _list.isNotEmpty;
#override
String toString() => _list.toString();
}
Just put the above class somewhere in the project lib directory.
And use it like.
CustomStack<String> plates = CustomStack();
//Add plates into the stack
plates.push("Plate1");
plates.push("Plate2");
plates.push("Plate3");
// delete the top plate
plates.pop();
I have a Flutter class that uses Freezed to create a sealed union that represents either data or an error:
#freezed
class DataOrError<T, E> with _$DataOrError {
const factory DataOrError.loading() = Loading;
const factory DataOrError.data(T data) = DataOrE<T, E>;
const factory DataOrError.error(E error) = DOrError<T, E>;
static DataOrError<T, E> fromEither<T, E>(Either<E, T> val) {
final result = val.fold(
(l) => DataOrError<T, E>.error(l), (r) => DataOrError<T, E>.data(r));
return result;
}
}
I use riverpod so I have a riverpod StateNotifier that looks like:
class RolesNotifier
extends StateNotifier<DataOrError<List<Role>, RoleFailure>> {
final Ref _ref;
StreamSubscription? sub;
RolesNotifier(Ref ref)
: _ref = ref,
super(const DataOrError.loading());
/// Will run the fetch
void fetch() {
// fetch roles
state = const DataOrError.loading();
sub = _ref.read(firebaseRoleService).getRoles().listen((event) {
state = DataOrError.fromEither<List<Role>, RoleFailure>(event);
});
}
// ... this class has been shortened for simplicity.
}
final rolesProvider = StateNotifierProvider.autoDispose<RolesNotifier,
DataOrError<List<Role>, RoleFailure>>((ref) {
return RolesNotifier(ref);
});
When I consume this provider; however, the types for DataOrError are gone:
ref
.read(rolesProvider)
.when(loading: (){}, data: (d) {
// d is dynamic type not List<Role>
}, error: (e){});
For some reason both d and e are dynamic types and not List<Role> & RoleFailure respectively. Everything appears to be typed correctly so why is this not working? I'm not sure if the error is with Freezed or Riverpod. I would like to avoid type casting (i.e. d as List<Role>) because that defeats the purpose of the generics.
The mixin has to be defined with the same generic types Like
class DataOrError<T, E> with _$DataOrError<T,E>
Although if you did not explicitly define the mixin generics ,the runner will mimic the original class types but in that case there will be no relation between them. in our case it will be a different set of T and E that is why it will be dynamic , bottom line is that you have to tell the mixin that it is indeed the same set of types.
Your code seems to be setup correctly, my intuition is that the types are not being inferred because you are using ref.read. This may be intentional in riverpod for some reason.
Finally, using ref.read inside the build method is an anti-pattern and your UI will not change whenever the state notifier updates.
Replace ref.read(rolesProvider) with:
ref.watch(rolesProvider).when(
loading: (){},
data: (d) {}, // Types should be inferred correctly now
error: (e){},
);
Working with flutter I'm straggling with notifying a model class parameters about changes coming from the firestore DB.
I'm trying to use plugin property_change_notifier
Using the example:
// ignore: mixin_inherits_from_not_object
class MyModel with PropertyChangeNotifier<String> {
int _foo = 0;
int _bar = 0;
int get foo => _foo;
int get bar => _bar;
set foo(int value) {
_foo = value;
notifyListeners('foo');
}
set bar(int value) {
_bar = value;
notifyListeners('bar');
}
}
I've added the ignore remark and even tried to set the analysis_option.yaml with this rule
I still get the message:
The class 'PropertyChangeNotifier' can't be used as a mixin because it extends a class other than Object.dart(mixin_inherits_from_not_object)
When I try to build the project it then shows the following error:
- 'BuildContext' is from 'package:flutter/src/widgets/framework.dart' ('/C:/ngplayground/flutter/packages/flutter/lib/src/widgets/framework.dart').
Try correcting the name to the name of an existing method, or defining a method named 'ancestorWidgetOfExactType'.
return nullCheck(context.ancestorWidgetOfExactType(type) as PropertyChangeModel);
^^^^^^^^^^^^^^^^^^^^^^^^^
2
FAILURE: Build failed with an exception.
* Where:
Script 'C:\ngplayground\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 991
* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
What is wrong here?
you just need to change
class MyModel with PropertyChangeNotifier<String>
to
class MyModel extends PropertyChangeNotifier<String>
and it should work
I have a simple data class that represents a task:
class Task {
String name;
String userId;
}
And a stream of tasks:
class TaskDataSource {
Stream<List<Task>> getAll() {
}
For every task I want to also fetch a user that is assigned to it:
class UsersDataSource {
Stream<User> getById(String userId);
}
And finally combine a task with a user to create an object that contains user's data as well as task's data. I was playing with zip function as well as flatMap but couldn't find a working solution. Any help would be appreciated.
Use Rx.forkJoinList:
class UserAndTasks {
final User user;
final Task task;
UserAndTasks(this.user, this.task);
}
void main() {
UsersDataSource usersDataSource;
TaskDataSource taskDataSource;
taskDataSource
.getAll()
.flatMap(
(tasks) => Rx.forkJoinList(tasks
.map((task) => usersDataSource
.getById(task.userId)
.map((user) => UserAndTasks(user, task)))
.toList()),
)
.listen((List<UserAndTasks> event) => print(event));
}
In java it would be something like this ...
public Request compose(LoginDevice login) {
JSONObject params = new JSONObject();
try {
if (login.granType != null)
params.put("grant_type", login.granType);
if (login.clientId != null)
params.put("client_id", login.clientId);
} catch (JSONException e) {
e.printStackTrace();
}
return (Request)new BaseRequest("oauth/v2/token", params.toString(), new HashSet());
}
And in Dart and tried something similar but it doesn't work... the parameter 'put' does not exist in JsonObjectLite...
Request compose(LoginDevice login)
{
JsonObjectLite params = new JsonObjectLite();
try {
if (login.granType != null) {
params.put("grant_type", login.granType);
}
if (login.clientId != null) {
params.put("client_id", login.clientId);
}
} on JsonObjectLiteException catch (e) {
print(e);
}
return new BaseRequest("oauth/v2/token", params.toString(), new HashSet());
}
How could I do it? Thank you
The class JsonObjectLite doesn't contain the method put.
How you can understand dart doesn't is Java, in this cases your the class JsonObjectLite has a method called putIfAbsent, the implementation is the following
/// If [isImmutable] is false, or the key already exists,
/// then allow the edit.
/// Throw [JsonObjectLiteException] if we're not allowed to add a new
/// key
#override
void putIfAbsent(dynamic key, Function() ifAbsent) {
if (isImmutable == false || containsKey(key)) {
_objectData.putIfAbsent(key, ifAbsent);
} else {
throw const JsonObjectLiteException('JsonObject is not extendable');
}
}
look also the Source code
So an example of code should be the following
import 'package:json_object_lite/json_object_lite.dart';
class AuthorAnswer {
var _username;
var _status;
AuthorAnswer(this._username, this._status);
String get username => _username;
String get status => _status;
}
int main() {
var author = '#vincenzopalazzo';
var sentences = 'Follow me on Github';
var authorObject = AuthorAnswer(author, sentences);
try{
JsonObjectLite params = new JsonObjectLite();
params.isImmutable = false;
params.putIfAbsent("author", () => authorObject.username);
params.putIfAbsent("sencence", () => authorObject.status);
print(params.toString());
} on JsonObjectLiteException catch (err){
print('--------- ERROR ----------');
print(err);
}
return 0;
}
You should be set the params.isImmutable = false and after you can add your propriety, with your logic.
In my opinion, I don't see any motivation to use this library, dart have 2 types of the module to implement the serialization, and I think should better use it because on the web exist the documentation, like this dart json, flutter json
Inside the flutter app, there are also the line guides, for the small application you can use dart:convert:json also for the other you can use the json_serializable
I want to add also an example of dart:convert
/**
*
*/
import "dart:core";
import "dart:convert";
class ClassToJsonOne {
var _propOne;
var _propTwo;
ClassToJsonOne(this._propOne, this._propTwo);
Map<String, dynamic> toJSon() => {
'prop_one': _propOne,
'prop_two': _propTwo
};
ClassToJsonOne.fromJson(Map<String, dynamic> json):
_propOne = json['prop_one'],
_propTwo = json['prop_two'];
#override
String toString() => 'First Class: $_propOne, $_propTwo';
}
class ClassToJsonTwo{
var _propOne;
var _propTwo;
ClassToJsonTwo(this._propOne, this._propTwo);
Map<String, dynamic> toJSon() => {
'prop_one': _propOne,
'prop_two': _propTwo
};
ClassToJsonTwo.fromJson(Map<String, dynamic> json):
_propOne = json['prop_one'],
_propTwo = json['prop_two'];
#override
String toString() => 'Second Class: $_propOne, $_propTwo';
}
main(List<String> args) {
print('------- Declare Objecr -------\n');
var objectToJsonOne = ClassToJsonOne('I am the fist object', 'empty');
var objectToJsonTwo = ClassToJsonTwo('I contains the first object', 'empty');
String jsonStringObjOne = jsonEncode(objectToJsonOne.toJSon());
print('\n---------- Object one JSON format ---------\n');
print(jsonStringObjOne);
String jsonStringObjTwo = jsonEncode(objectToJsonTwo.toJSon());
print('\n---------- Object one JSON format ---------\n');
print(jsonStringObjTwo);
print('\n---------- DECODE JSON to OBJECT ---------\n');
var fromJsonObjectOne = jsonDecode(jsonStringObjOne);
print(fromJsonObjectOne.toString());
var fromJsonObjectTwo = jsonDecode(jsonStringObjTwo);
print(fromJsonObjectTwo.toString());
}
Inside the classes, you can see the following methods
Map<String, dynamic> toJSon() => {
'prop_one': _propOne,
'prop_two': _propTwo
};
ClassToJsonTwo.fromJson(Map<String, dynamic> json):
_propOne = json['prop_one'],
_propTwo = json['prop_two'];
The result of the method toJSon, you should be pass to the method of the library jsonEncode and when you go to deserialize you can use the library method jsonDecode(youtStringJSOn) and the result you can pass to the method of your class fromJson.
In addition, you can configure the library json_serializable.
In conclusion, I want to fix my comment
I think the json_serializable worked how GSON, I can make an example for you, on this day.
On flutter, documentation has reported this text
Is there a GSON/Jackson/Moshi equivalent in Flutter?
The simple answer is no.
Such a library would require using runtime reflection, which is disabled in Flutter. Runtime reflection interferes with tree shaking, which Dart has supported for quite a long time. With tree shaking, you can “shake off” unused code from your release builds. This optimizes the app’s size significantly.
Since reflection makes all code implicitly used by default, it makes tree shaking difficult. The tools cannot know what parts are unused at runtime, so the redundant code is hard to strip away. App sizes cannot be easily optimized when using reflection.
Although you cannot use runtime reflection with Flutter, some libraries give you similarly easy-to-use APIs but are based on code generation instead. This approach is covered in more detail in the code generation libraries section.
you can found the source code inside this answer here