Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR DART

how to use same bloc in multiple widgets in flutter

class CounterPage extends StatefulWidget {
  @override
  _CounterPageState createState() => _CounterPageState();
}

class _CounterPageState extends State<CounterPage> {
  CounterBloc counterBloc;

  @override
  void initState() {
    super.initState();
    counterBloc = BlocProvider.of<CounterBloc>(context);
  }

  @override
  void dispose() {
    counterBloc.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Counter')),
      body: BlocBuilder<CounterBloc, int>(
        builder: (_, count) {
          return Column(
            children: <Widget>[
              Text(
                '$count',
                style: const TextStyle(fontSize: 24.0),
              ),
              RaisedButton(
                child: Text("Recreating state"),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => BlocProvider<CounterBloc>.value(
                        value: counterBloc,
                        child: ThirdPage(),
                      ),
                    ),
                  );
                },
              ),
              RaisedButton(
                child: Text("Getting errorBlocProvider.of() called  "),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => BlocProvider<CounterBloc>.value(
                        value: counterBloc,
                        child: FourthPage(),
                      ),
                    ),
                  );
                },
              )
            ],
          );
        },
      ),
      // ....
    );
  }
}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #bloc #multiple #widgets #flutter
ADD COMMENT
Topic
Name
3+8 =