Comments (14)
todos is working when its stripped down, so i can go from that, i added on git for you to see, so that there can be implementation without any extra libraries.
https://github.com/MichalNemec/electric-todos
from electric_dart.
@MichalNemec There could be something with how the DaoAccessor works with the autogenerated electric drift schema. Will have to try.
Regarding the example, I can agree to some extent. The quickstart in the package README contains basically the necessary steps, but for completeness the example app includes several other pieces like local state removal, connectivity to the service via a button, connection state...
All that is easier to manage with some sort of state management, in this case is with riverpod and hooks.
from electric_dart.
@MichalNemec Your snippet above has one of the most common issues when building Flutter apps.
You are creating a new stream in every build, so after the load is done, your app rebuilds and you are instantiating a new stream by calling watchStat(), so the builder goes again to loading state
On plain Flutter you would need to create a StatefulWidget and store the Stream instance in your State class and instantiate it during initState.
This is one of the things flutter_hooks simplify with (useMemoized + useStream) or riverpod by caching the Stream you are using
from electric_dart.
@MichalNemec You can have more context here: https://stackoverflow.com/questions/52249578/how-to-deal-with-unwanted-widget-build
from electric_dart.
if i do init state and call save the stream to field, its working exactly the same.
Its not updating the ui with new value, for example, upon loading it shows 100, when i update the value in backend database to 10, i see in log flutter: [2024-04-11 14:08:23.181404 | Electric | INFO] Notifying table changes to drift: {Stats}
but ui has still 100.
from electric_dart.
If you are seeing notifying drift it's likely that the local db has been changed, so possibly just an issue with how you are listening.
Could you create a repository with a reproducible example? Hard to tell otherwise
from electric_dart.
I followed this exactly https://github.com/SkillDevs/electric_dart/blob/master/docs/quickstart.md and the only thing that is changed is this.
class Electric {
static final Electric _instance = Electric._internal();
factory Electric() {
return _instance;
}
Electric._internal();
MyDatabase? myDb;
DriftElectricClient<MyDatabase>? myElectric;
init() async {
myDb = MyDatabase();
myElectric = await electrify<MyDatabase>(
dbName: 'my_db',
db: myDb!,
migrations: kElectricMigrations,
config: ElectricConfig(
url: 'http://192.168.0.117:5133',
logger: LoggerConfig(
level: Level.debug,
),
),
);
await myElectric!.connect(insecureAuthToken({'sub': AuthData().getUserId()})); //uuid
_defaultSync();
}
_defaultSync() async {
await myElectric?.syncTables(
[
'Stats',
],
);
}
When user is logged in, i call await Electric().init();
In DAO i have
Stream<Stat> watchStat() {
final query = select(stats);
query.where((m) => m.id.equals(1));
query.limit(1);
return query.watchSingle();
}
from electric_dart.
That looks ok. But there are many moving pieces so it's impossible to tell from that snippet alone.
If you run the todos example you can test deleting entries from Postgres side and the UI should react to those changes.
There could be some issue with how you are rendering the widget and listening to the query.
You could even do the following to be sure. If it works we can discard it being an issue with electric.
void initState() {
dao.watch().listen((data) {
print("NEW DATA $data");
});
}
from electric_dart.
i see it only upon entering the page.
NEW DATA [Stat(id: 1, content: "100")]
when i update on backend db or in local db (not in app) then i see electric notifies, but its not triggering this listener.
I think its because of the hooks and riverpod, that its not working.
Another thing that could be the culprit is that im doing this in my dao:
@DriftAccessor(
tables: [
Stats,
],
)
class StatsDAO extends DatabaseAccessor<MyDatabase> with _$StatsDAOMixin {
StatsDAO(super.db);
Stream<Stat> watchStat() {
final query = select(stats);
query.where((m) => m.id.equals(1));
query.limit(1);
return query.watchSingle();
}
}
I dont see something like this in todo example.
I have working todos example, maybe i can try to strip it down from hooks and riverpod and see if its working. I could use riverpod, but not hooks unfortunately.
from electric_dart.
@MichalNemec I'm fine if you can share a minimal example using riverpod. If electric notifies and then it reaches "drift-land", there should be something on the Flutter+Drift side of things.
from electric_dart.
@MichalNemec Have you tried moving the watchStat
function to the drift database class? The one that has the annotation: @DriftDatabase(tables: kElectrifiedTables)
from electric_dart.
@MichalNemec Did you find what was causing the problem? If so, it would be great if you could share, in case someone else encounters a similar issue and finds this.
from electric_dart.
Seriously, i didnt. I tried multiple things, but the best one was to just strip todos example down and port code over. Subscriptions now work as intended and im following the TodosRepository instead of generated DAOs from drift (what i posted above with @driftaccessor) and now its working. So i guess the advice would be to just use the example and build upon that.
What i would find beneficial right from the start, would be to have a completely barebones client, so anyone can adapt it to their preferred state management etc..
from electric_dart.
@MichalNemec I've just tried a simple example with DriftAccessor and it works correctly.
On top of the todos example in version 0.5.3 I added a watch query that watches the current number of todos.
I'm not entirely sure how you had your previous example configured. I used a simple stateful widget with a cached Stream<int>
Widget
class NumTodosIndicator extends StatefulWidget {
const NumTodosIndicator({super.key, required this.db});
final AppDatabase db;
@override
State<NumTodosIndicator> createState() => _NumTodosIndicatorState();
}
class _NumTodosIndicatorState extends State<NumTodosIndicator> {
late Stream<int> numTodosStream;
@override
void initState() {
super.initState();
numTodosStream = TodosDAO(widget.db).watchNumTodos();
}
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: numTodosStream,
initialData: null,
builder: (BuildContext context, AsyncSnapshot<int?> snapshot) {
if (!snapshot.hasData) {
return Text("Loading");
}
return Text("Number of todos: ${snapshot.data}");
},
);
}
}
DAO
import 'package:drift/drift.dart';
import 'package:todos_electrified/database/drift/database.dart';
import 'package:todos_electrified/generated/electric/drift_schema.dart';
part 'todos_dao.g.dart';
@DriftAccessor(
tables: [
Todo,
],
)
class TodosDAO extends DatabaseAccessor<AppDatabase> with _$TodosDAOMixin {
TodosDAO(super.db);
Stream<int> watchNumTodos() {
final numTodos = countAll();
final query = selectOnly(todo)..addColumns([numTodos]);
return query.map((p0) => p0.read(numTodos)!).watchSingle();
}
}
from electric_dart.
Related Issues (16)
- Supabase support HOT 21
- Schema versioning conflicts HOT 1
- Version solving failed in todos example HOT 3
- Supabase example
- Offine First, Sync Optional HOT 4
- Show us your projects using electric_dart HOT 1
- Electric custom types (eg, Postgres date type) not generating correct SQL for query. HOT 3
- [How to] Use the latest master version, skipping the pub.dev HOT 2
- Todos_flutter errors HOT 3
- [CLI] cant use custom .env file HOT 2
- Bad state: No element when generating tables. HOT 8
- Error when Satellite performs a Snapshot after DB Connection has been closed HOT 7
- Error connecting to Electric: errorType: INVALID_REQUEST when pressing back button on main screen and reopening the app HOT 12
- Issue after upgrade `_electric_trigger_settings has no column named namespace` HOT 5
- MODULE ERROR: Electric.Replication.PostgresConnector when trying to connect to Supabase HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from electric_dart.