Replacing an instance of a Bloc in a blocprovider

Issue

I’m trying to find a way to create a new instance of a bloc and have it reflected in the multibloc provider.

currently I have the following :

Scaffold(
        appBar: AppBar(),
        body: MultiBlocProvider(
          providers: [
            BlocProvider<BlocABloc>(
              create: (BuildContext context) => _aBloc,
            ),
            BlocProvider<BlocBBloc>(
              create: (BuildContext context) => _bBloc,
            ),
          ]...

I’m then trying to create a new instance of BlocABloc and also BlocBBloc as :

generateNew(){
setState(() {
 _aBloc = BlocABloc();
 _bBloc = BlocBBloc();
});
}

I was expecting the build function to re-execute and new instance is used in the BlocProvider. However, I’m finding that the BlocBuilder is still getting states from the previous instance of the Blocs.

Is there a way to do handle this scenario ?

Solution

I don’t know the reason why you want to do this. But you can force BlocProvider create method to be executed again by using key. Here is an example how you can do it.

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  BlocA _blocA;

  @override
  void initState() {
    super.initState();
    _blocA = BlocA(1);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: MultiBlocProvider(
        providers: [
          BlocProvider<BlocA>(
            key: ValueKey(_blocA.state),
            create: (context) {
             return _blocA;
            },
          ),
        ],
        child: BlocBuilder<BlocA, int>(builder: (context, int state) {
          return Column(
            children: <Widget>[
              SizedBox(
                height: 16,
              ),
              Text("Bloc stat: $state"),
              SizedBox(
                height: 16,
              ),
              Center(
                child: RaisedButton(
                  child: Text("Create New Bloc"),
                  onPressed: _generateNew,
                ),
              )
            ],
          );
        }),
      ),
    );
  }

  _generateNew() {
    setState(() {
      _blocA.close();
      _blocA = BlocA(2);
    });
  }
}

Answered By – Zakir

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *