Bloc pattern does not show newly added user to sqflite on screen

flutter bloc
flutter streambuilder
flutter bloc dispose
futurebuilder sqflite
flutter moor
sqflite database in flutter
flutter bloc crud
use local database in flutter

I am using sqflite database to save user list. I have user list screen, which shows list of user and it has a fab button, on click of fab button, user is redirected to next screen where he can add new user to database. The new user is properly inserted to the database but when user presses back button and go backs to user list screen, the newly added user is not visible on the screen. I have to close the app and reopen it,then the newly added user is visible on the screen.

I am using bloc pattern and following is my code to show user list

class _UserListState extends State<UserList> {
  UserBloc userBloc;

  @override
  void initState() {
    super.initState();
    userBloc = BlocProvider.of<UserBloc>(context);
    userBloc.fetchUser();
  }

  @override
  void dispose() {
    userBloc?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(

      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.of(context).pushNamed("/detail");
        },
        child: Icon(Icons.add),
      ),
      body: StreamBuilder(
        stream: userBloc.users,
        builder: (context, AsyncSnapshot<List<User>> snapshot) {
          if (!snapshot.hasData) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }

          if (snapshot.data != null) {
            return ListView.builder(
              itemBuilder: (context, index) {
                return Dismissible(
                  key: Key(snapshot.data[index].id.toString()),
                  direction: DismissDirection.endToStart,
                  onDismissed: (direction) {
                    userBloc.deleteParticularUser(snapshot.data[index]);
                  },
                  child: ListTile(
                    onTap: () {
                      Navigator.of(context).push(MaterialPageRoute(
                          builder: (context) => UserDetail(
                               user: snapshot.data[index],
                              )));
                    },
                    title: Text(snapshot.data[index].name),
                    subtitle:
                        Text("Mobile Number ${snapshot.data[index].userId}"),
                    trailing:
                        Text("User Id ${snapshot.data[index].mobileNumber}"),
                  ),
                );
              },
              itemCount: snapshot.data.length,
            );
          }
        },
      ),
    );
  }
}

Following is my bloc code

    class UserBloc implements BlocBase {
  final _users = BehaviorSubject<List<User>>();

  Observable<List<User>> get users => _users.stream;

  fetchUser() async {
    await userRepository.initializeDatabase();

    final users = await userRepository.getUserList();
    _users.sink.add(users);
  }

  insertUser(String name,int id,int phoneNumber) async {
    userRepository.insertUser(User(id, name, phoneNumber));
    fetchUser();
  }

  updateUser(User user) async {
    userRepository.updateUser(user);
  }

  deleteParticularUser(User user) async {
    userRepository.deleteParticularUser(user);
  }

  deleteAllUser() {
    return userRepository.deleteAllUsers();
  }

  @override
  void dispose() {
    _users.close();
  }
}

As Remi posted answer saying i should try BehaviorSubject and ReplaySubject which i tried but it does not help. I have also called fetchUser(); inside insertUser() as pointed in comments

Following is the link of the full example

https://github.com/pritsawa/sqflite_example


Follow up from the comments, it seems you don't have a single instance of your UsersBloc in those two pages. Both the HomePage and UserDetails return a BlocProvider which instantiate a UsersBloc instance. Because you have two blocs instances(which you shouldn't have) you don't update the streams properly.

The solution is to remove the BlocProvider from those two pages(HomePage and UserDetail) and wrap the MaterialApp widget in it to make the same instance available to both pages.

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      bloc: UserBloc(),
      child:MaterialApp(...

The HomePage will be:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return UserList(),
    );
  }
}

Remove the BlocProvider from UserDetail as well. In the UsersBloc then call fetchUser() inside the insertUser() method after the user insertion, to requery the database and update the users stream.

Also as Rémi Rousselet said, use one of the subjects that return previous values.

Flutter: Todo App using BLoC Design Pattern with SQLite, In this article, I will display the making of the classical Todo app using Design Pattern (BLoC); Reactive Programming using Dart streams //main screen card text description: data['description'], //Since sqlite doesn't have boolean our Todo instance into a JSON format that sqflite adapters will use in  Also one can add comment by clicking plus icon and add a new comment. My Screen Structure is as below: PostDetail PostInfoScreen; PostCommentListScreen (This is paginated API call implemented with BLoC Pattern) PostAddNewCommentScreen; Now, the trouble that I'm facing is related to refresh this comment listing when a user add a new comment. (i.e.


The issue is that you're using a PublishSubject.

When a new listener subscribes to a PublishSubject, it does not receive the previously sent value and will only receive the next events.

The easiest solution is to use a BehaviorSubject or a ReplaySubject instead. These two will directly call their listener with the latest values.

How to use Streams, BLoCs, and SQLite in Flutter, Recently, I've been working with streams and BLoCs in Flutter to retrieve and To do this properly, we need to add sqflite and path_provider as In case it doesn't run automatically, run flutter packages get to retrieve the packages. The StreamBuilder allows us to make use of our streams and display. The lyrics fetched from the Genius are displayed on the Webview, and those added by a user are shown on the custom screen with an option to edit them. Removing items is done by swiping them off the list. Getting started. To start working with Flutter’s BLoC library I had to add two dependencies to the pubspec.yaml file.


@override
  void initState() {
    super.initState();
    userBloc = BlocProvider.of<UserBloc>(context);
    userBloc.fetchUser();
  }

The problem is that you have called the userBloc.fetchUser() function in the initState of the page.

Bloc stream emits whenever a new data is added to it and the userBloc.fetchUser() function does exactly that, it adds the userList that you fetch from the Sqflite database.

Whenever you come back to the userlist screen from add user screen, init function is NOT called. It is only called when the userlist screen is created, that is, whenever you push it to the navigation stack.

The workaround is to call userBloc.fetchUser() whenever your StreamBuilder's snapshot data is null.

...
 if (!snapshot.hasData) {
      userBloc.fetchUser();
        return Center(
          child: CircularProgressIndicator(),
        );
      }
...

Flutter sqflite bloc, SQLite is not available in a flutter SDK as Android but we have a plugin sqflite Bloc pattern does not show newly added user to sqflite on screen · dart flutter  SQLite flutter plugin. Contribute to tekartik/sqflite development by creating an account on GitHub.


Getting Started with the BLoC Pattern, This widget is also not optimized and could, in theory, be improved. When a new event is received, the builder closure will be executed, For the stream property, use the of method to retrieve the LocationBloc and add its to add a stream builder and show the results in a list. pubspec Main Flutter Doctor [√] Flutter (Channel master, v0.3.6-pre.25, on Microsoft Windows [Version 10.0.16299.402], locale en-PK) • Flutter version 0.3.6-pre.25 at C:\fluttersdk\flutter • Framework revision d8f2f36935 (68 minutes ago)


Using sqflite in flutter application, Flutter: Login App using REST API and SQFLite. just you can get Roast lines To use this plugin, we need to add dependency to it in the pubspec. Jun 30, 2019 · Benefit Of Using StreamBuilder With BLoC Pattern In Flutter As you can see, When you create a new flutter_web project via stagehand, the latter does not  Start by creating a new Flutter project called flutter_database. Dependencies. Open the pubspec.yaml file and add the following lines to the dependencies section: sqflite: ^1.2.0 path_provider: ^1.5.1


StreamBuilder is not reacting when calling StreamController.sink.add, Bloc pattern does not show newly added user to sqflite on screen. I am using sqflite database to save user list. I have user list screen, which shows list of user  on iOS create the directory of the database if it does not exist; 0.11.2 # add Database.isOpen which becomes false once the database is closed; 0.11.1 # add Sqlflite.hex to allow querying on blob fields; 0.11.0 # add getDatabasesPath to use as the base location to create a database