为什么我的onPressed回调不能使用Bloc调用我的Bloc?

时间:2019-10-25 07:57:31

标签: flutter dart bloc

我正在使用felangel的Bloc库,特别是Flutter_bloc,但是使用BlocProvider时,我无法将bloc实例传递给按下按钮时的onpressed方法

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();
  }
}

基本上,每当我运行代码时,它都会引发以下异常:使用上下文不包含Bloc类型的Bloc调用BlocProvider.of()。

1 个答案:

答案 0 :(得分:0)

尝试将BlocProvider放在项目的顶部(MyHomePage或MaterialApp的父项)。