1

I'm using the Bloc Library by felangel, specifically Flutter_bloc, but using BlocProvider I'm unable to pass the bloc instance to my onpressed method for when a button is pressed

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Bloc Demo',
      theme: ThemeData(
        primarySwatch: Colors.red,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> {
  double temp;
  String _formText = "";
  final _formKey = GlobalKey<FormState>(debugLabel: "City name should be here");

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Hello, title here"),
      ),
      body: BlocProvider<WeatherBloc>(
        builder: (BuildContext context) => WeatherBloc(),
        child: BlocBuilder<WeatherBloc, WeatherState>(
          builder: (BuildContext context, WeatherState state) {

            if (state is InitialWeatherState) {
              return buildInitialWeather();
            }
            else if (state is WeatherStateLoading) {
              return buildLoading();
            } else if (state is WeatherStateLoaded) {
              return buildColumn(state.weather);
            } else throw Exception("Something went wrong here");
            }
            ),

      ),
    );
  }

  Widget buildInitialWeather() {
    return Center(
      child: Column(children: <Widget>[
        Padding(
            padding: const EdgeInsets.symmetric(horizontal: 32.0),
            child: Form(
                key: _formKey,
                child: TextFormField(
                  decoration: InputDecoration(hintText: "Enter your city"),
                  onSaved: (value) {
                    setState(() {
                      _formText = value;
                    });
                  },
                )),
          ),
          new RaisedButton(
            onPressed: _onPressed,
            child: Text("Click Me!"),
            splashColor: Colors.pink,
          )
      ],),
    );
  }

  Widget buildLoading() {
    return Center(
      child: CircularProgressIndicator(),
    );
  }

  Column buildColumn(Weather weather) {
    return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            'Geo Locator for:'+weather.cityName,
            style: TextStyle(fontSize: 20.0),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Text(
              weather.temp.toString(),
              style: TextStyle(fontSize: 20.0),
            ),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 32.0),
            child: Form(
                key: _formKey,
                child: TextFormField(
                  decoration: InputDecoration(hintText: "Enter your city"),
                  onSaved: (value) {
                    setState(() {
                      _formText = value;
                    });
                  },
                )),
          ),
          new RaisedButton(
            onPressed: _onPressed,
            child: Text("Click Me!"),
            splashColor: Colors.pink,
          )
        ],
      );
  }

  void _onPressed() {

    _formKey.currentState.save();
    print(_formText);
// This line fails. I don't know why.
    BlocProvider.of<WeatherBloc>(context).dispatch(GetWeather(_formText));
  }

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

Basically whenever I run the code it throws the following exception: BlocProvider.of() called with a context that does not contain a Bloc of type Bloc.

Shazamo Morebucks
  • 478
  • 1
  • 8
  • 19
  • Your context doesn't contain that bloc, try using local bloc instead. – Tokenyet Oct 25 '19 at 08:49
  • Sorry could you please explain? Why doesnt my context contain the bloc? And what's local bloc? Is that from the library or do you mean creating a bloc variable? – Shazamo Morebucks Oct 25 '19 at 09:12
  • Becasue the context you used in `_onPressed` is not carried `bloc`, that's It. Made a variable in state like `_bloc` is called [local bloc](https://github.com/felangel/bloc/blob/a6fb074e91632ade2cd6bd663ad9411914420a2d/packages/flutter_bloc/README.md), you could use that directly without any issue. Only use `BlocProvider` when you need to pass to a custom child widget that extends `StatelessWidget` or `StatefulWidget`. – Tokenyet Oct 25 '19 at 09:25
  • If you still confuse why It's not carried context, you could see this [post](https://stackoverflow.com/questions/51304568/scaffold-of-called-with-a-context-that-does-not-contain-a-scaffold). The context issue would be confused when you are not familiar with It. – Tokenyet Oct 25 '19 at 09:30
  • You are right, it works if I create a variable and use it instead of Blocprovider.of(context). But why cant I use blocprovider? Aren't my widgets im passing to custom child widgets? – Shazamo Morebucks Oct 25 '19 at 09:48
  • You could use It, If you pass the context that existed the bloc. you might want to read the post I posted above, and figure out the scope of the context. – Tokenyet Oct 25 '19 at 10:24

1 Answers1

0

Try to put BlocProvider in top of your project (Parent of MyHomePage or MaterialApp).

minhnhatvdl
  • 43
  • 1
  • 6