【问题标题】:Why couldn't my onPressed callback call my Bloc using Bloc?为什么我的 onPressed 回调不能使用 Bloc 调用我的 Bloc?
【发布时间】:2020-02-21 13:34:02
【问题描述】:

我正在使用 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。

【问题讨论】:

  • 您的上下文不包含该块,请尝试使用本地块。
  • 抱歉,您能解释一下吗?为什么我的上下文不包含集团?什么是本地集团?是来自库还是您的意思是创建一个 bloc 变量?
  • 因为你在_onPressed中使用的上下文没有携带bloc,就是这样。在_bloc 这样的状态下创建了一个变量,称为local bloc,您可以直接使用它而不会出现任何问题。仅当您需要传递给扩展 StatelessWidgetStatefulWidget 的自定义子小部件时才使用 BlocProvider
  • 如果你仍然对为什么它没有携带上下文感到困惑,你可以看到这个post。当你不熟悉它时,上下文问题会被混淆。
  • 你是对的,如果我创建一个变量并使用它而不是 Blocprovider.of(context),它就可以工作。但是为什么我不能使用 blocprovider?我的小部件不是正在传递给自定义子小部件吗?

标签: flutter dart bloc


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-10-24
    • 2021-02-08
    • 2019-09-12
    • 1970-01-01
    • 2019-11-13
    • 2020-05-20
    • 2020-08-21
    • 1970-01-01
    • 2020-08-12
    相关资源
    最近更新 更多