Flutter – How set double value to Bloc?

Issue

In my application there is a field for input of a certain value in double format, but this is not working.

What am I doing wrong?

My Bloc

 class BudgetBloc extends BlocBase {
   String _documentId;
   double _movimentos;

   BudgetBloc() {
     _movimentosController.listen((value) => _movimentos = value);
   }

   void setBudget(Budget budget) {
     _documentId = budget.documentId();
     setMovimentos(budget.movimentos);
   }

   var _movimentosController = BehaviorSubject<double>();
   Stream<double> get outMovimentos => _movimentosController.stream;

   void setMovimentos(double value) => _movimentosController.sink.add(value);

   bool insertOrUpdate() {
      var budget = Budget()
     ..movimentos = _movimentos;

     if (_documentId?.isEmpty ?? true) {
       _repository.add(budget);
     } else {
       _repository.update(_documentId, budget);
     }

    return true;
  }

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

My BudgetPage

 class BudgetPage extends StatefulWidget {

   BudgetPage(this.budget);
   final Budget budget;

   @override
   _BudgetPageState createState() => _BudgetPageState();
 }
 class _BudgetPageState extends State<BudgetPage> {

   TextEditingController _movimentosController;
   final _bloc = BudgetBloc();

   @override
   void initState() {
   _movimentosController =
      TextEditingController(text: widget.budget.movimentos.toString());
   super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Add Movimento"),
      ),
      body: Container(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: ListView(
          children: <Widget>[

            Container(
              child: TextField(
                decoration: InputDecoration(labelText: "Movimento"),
                controller: _movimentosController,
                onChanged: _bloc.setMovimentos,
              ),
            ),

            Container(
              height: 20,
            ),

            RaisedButton(
              child: Text("Save"),
              onPressed: () {
                if (_bloc.insertOrUpdate()) {
                  Navigator.pop(context);
                }
              },
            )
          ],
        ),
      ),
    ),
  );
 }

 }

Thanks

Solution

Function(double) can’t be assigned to the parameter type void Function(String)

The error is telling you that you are providing a String when it expects a double.

I would try passing a double to the BLoC, something like this:

onChanged: (value) => _bloc.setMovimentos(double.parse(value)),

Answered By – Frank Treacy

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.