Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use bloc pattern between two screens

Tags:

flutter

bloc

my main.dart file looks like this.

home: MultiBlocProvider(
      providers: [
        BlocProvider<UserBloc>(
          create: (BuildContext context) =>   UserBloc()..add(GetUser(userId:"5e0b62023b75dd60e22edaad")),
        ),
         BlocProvider<TodoBloc>(
           create: (BuildContext context)=> TodoBloc()..add(AddTodoEvent()),)
      ],
      child: FirstScreen(),
    ),

I want to navigate to the second screen on button press in FirstScreen.

var router = new MaterialPageRoute(
      builder: (BuildContext context){
        return BlocProvider<UserBloc>(
          create: (BuildContext context) =>   UserBloc(),
          child: SecondScreen(),
        );
      });
  Navigator.of(context).push(router);

It works fine,but it will create new UserBloc initial state. What I want is to get the currect state on UserBlog.

I tried this

UserBloc userBloc = BlocProvider.of<UserBloc>(context);
BlocProvider<CounterBloc>(
  bloc: userBloc,
  child: SecondScreen()
 )

bloc gives an error. Is there any way to navigate to the SecondScreen and have the same state.

like image 326
Udith Shalinda Avatar asked Jan 01 '23 09:01

Udith Shalinda


1 Answers

Every time you call BlocProvider, you create new instance of bloc class.

To work with the same bloc instance, you need to create it once, and put it before routing after that you will have access to it via context.

import 'package:bloc/bloc.dart';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider<BlocSample>(
          create: (BuildContext context) => BlocSample(),
        ),
      ],
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: FirstScreen(),
      ),
    );
  }
}

class BlocSample extends Bloc<EventSample, String> {
  @override
  String get initialState => 'initial state';

  @override
  Stream<String> mapEventToState(
    EventSample event,
  ) async* {
    yield 'changed state';
  }
}

class EventSample {}

class FirstScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<BlocSample, String>(
      builder: (context, state) {
        return Scaffold(
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(state),
                RaisedButton(
                  child: Text('change status'),
                  onPressed: () => BlocProvider.of<BlocSample>(context).add(
                    EventSample(),
                  ),
                ),
                RaisedButton(
                  child: Text('change route'),
                  onPressed: () => Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (_) => SecondScreen(),
                    ),
                  ),
                )
              ],
            ),
          ),
        );
      },
    );
  }
}

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<BlocSample, String>(
      builder: (context, state) {
        return Scaffold(
          body: Center(child: Text(state)),
        );
      },
    );
  }
}

enter image description here

like image 92
Kherel Avatar answered Jan 02 '23 23:01

Kherel