Почему мой обратный вызов onPressed не может вызвать мой блок с помощью блока? - PullRequest
0 голосов
/ 25 октября 2019

Я использую библиотеку Bloc от felangel, в частности Flutter_bloc, но с помощью BlocProvider я не могу передать экземпляр блока моему нажатому методу для нажатия кнопки

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.

1 Ответ

0 голосов
/ 25 октября 2019

Попробуйте поставить BlocProvider поверх вашего проекта (Parent of MyHomePage или MaterialApp).

...