Giter Site home page Giter Site logo

Comments (14)

MichalNemec avatar MichalNemec commented on September 15, 2024 1

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.

davidmartos96 avatar davidmartos96 commented on September 15, 2024 1

@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.

davidmartos96 avatar davidmartos96 commented on September 15, 2024

@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.

davidmartos96 avatar davidmartos96 commented on September 15, 2024

@MichalNemec You can have more context here: https://stackoverflow.com/questions/52249578/how-to-deal-with-unwanted-widget-build

from electric_dart.

MichalNemec avatar MichalNemec commented on September 15, 2024

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.

davidmartos96 avatar davidmartos96 commented on September 15, 2024

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.

MichalNemec avatar MichalNemec commented on September 15, 2024

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.

davidmartos96 avatar davidmartos96 commented on September 15, 2024

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.

MichalNemec avatar MichalNemec commented on September 15, 2024

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.

davidmartos96 avatar davidmartos96 commented on September 15, 2024

@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.

davidmartos96 avatar davidmartos96 commented on September 15, 2024

@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.

davidmartos96 avatar davidmartos96 commented on September 15, 2024

@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.

MichalNemec avatar MichalNemec commented on September 15, 2024

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.

davidmartos96 avatar davidmartos96 commented on September 15, 2024

@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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.