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

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

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

最佳答案

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

关于flutter - 为什么我的onPressed回调不能使用Bloc调用我的Bloc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58554438/

相关文章:

android - Flutter:如何消除代码中其他地方的刷新栏?

json - 如何让所有Json Body的 child 振作起来

flutter - Null 相关错误 - 无法将参数类型 'String? Function(String)' 分配给参数类型 'String? Function(String?)?'

Flutter Bloc - 有没有办法在屏幕中提供 block 的不同实例

flutter - 如何在Flutter中的AnimationController.repeat()之间增加一些延迟

firebase - 如何在 Cloud Firestore 中使用 Stream 回调

在同一属性上 flutter 交错动画

flutter - 如何在 flutter 中呈现一个空 View ?

flutter - 方法 'bloc' 没有为类型 'BuildContext' 定义

flutter - Dart/Flutter 中 BLoC 模式的最佳实践