Home > Mobile >  How to pass controller through parameters when calling a function from provider?
How to pass controller through parameters when calling a function from provider?

Time:06-18

I have a functionality in my application. Based on the date keyed into the search bar, it will calculate total calories consumed by the user from a list view and display it on the same page when I click the search icon. https://i.stack.imgur.com/Pl2df.png https://i.stack.imgur.com/y7pui.png

I am able to print the total calories in the console but I can't seem to get it to print on the screen. I have tried controller.text, controller.toString() in the parameters but it both gave me errors.

Controller.toString() Trying to read d from TextEditingController#2f2ca(TextEditingValue(text: ┤├, selection: TextSelection.invalid, composing: TextRange(start: -1, end: -1))) at position 0 Controller.text Trying to read d from at position 0

https://i.stack.imgur.com/5Q1VW.png

Code screen where the date is entered:

import 'package:flutter/material.dart';
import 'package:my_plate/models/calories.dart';
import 'package:my_plate/providers/all_calories.dart';
import 'package:my_plate/screens/home_screen.dart';
import 'package:my_plate/screens/login_screen.dart';
import 'package:my_plate/widgets/app_drawer.dart';
import 'package:provider/provider.dart';

class RecordsPage extends StatelessWidget {
  final controller = TextEditingController();
  // void dispose() {
  //   // Clean up the controller when the widget is disposed.
  //   controller.dispose();
  //   //super.dispose();
  // }

  static String routeName = '/records';
  @override
  Widget build(BuildContext context) {
    AllCalories myCalories = Provider.of<AllCalories>(context);
    return Scaffold(
        resizeToAvoidBottomInset: true,
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: Text('Previous Records'),
          elevation: 0,
          brightness: Brightness.light,
          backgroundColor: Color(0xff588157),
          leading: IconButton(
            onPressed: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => MainScreen(),
                  ));
            },
            icon: Icon(
              Icons.arrow_back,
              size: 20,
              color: Colors.white,
            ),
          ),
        ),
        body: SingleChildScrollView(
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 40),
            child: Column(children: [
              Image.asset('images/date.png', alignment: Alignment.topCenter),
              TextField(
                controller: controller,
                decoration: InputDecoration(
                    enabledBorder: UnderlineInputBorder(
                      borderSide: BorderSide(color: Color(0xff588157)),
                    ),
                    focusedBorder: UnderlineInputBorder(
                      borderSide: BorderSide(color: Color(0xff588157)),
                    ),
                    hintText: 'Enter a search term',
                    suffixIcon: IconButton(
                        onPressed: () {
                          myCalories.getTotal(controller.text);
                        },
                        icon: Icon(Icons.search))),
              ),
              Row(
                children: [
                  Text(
                    myCalories.getTotal(controller
                        .toString()), // error lies here controller.text & controller.toString()
                    textAlign: TextAlign.center,
                    style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
                  ),
                ],
              ),
            ]),
          ),
        ),
        drawer: AppDrawer());
  }
}

Code for provider

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:my_plate/models/calories.dart';

class AllCalories with ChangeNotifier {
  List<Calories> myCalories = [];

  List<Calories> getMyCalories() {
    return myCalories;
  }

// String controller
  getTotal(String controller) {
    var dateTime = DateFormat('d/M/y').parse(controller);
    var tmrDate = dateTime.add(const Duration(days: 1));

    List<Calories> date = myCalories.where((o) {
      print(o.consumptionDate);
      if ((o.consumptionDate).isAfter(dateTime) &&
          (o.consumptionDate).isBefore(tmrDate)) {
        print(dateTime);
      }
      return (o.consumptionDate).isAfter(dateTime) &&
          (o.consumptionDate).isBefore(tmrDate);
    }).toList();
    double sum = 0;
    for (var i = 0; i < myCalories.length; i  ) {
      sum  = myCalories[i].numCalories;
      print(sum);
      print(myCalories[i].numCalories);
      print(date);
    }
    return (sum);
  }
}

CodePudding user response:

You can just pass the controller. specify the TextEditingController object you want in the getTotal method like

   getTotal(TextEditingController controller)
{
 ///you can use the controller value here by the controller.text 
}

CodePudding user response:

You might wanna do it like this:

class AllCalories with ChangeNotifier {
  List<Calories> myCalories = [];
  //declare a holder of your data
  double totalCalories = 0;

  List<Calories> getMyCalories() {
    return myCalories;
  }

  getTotal(String controller) {
    var dateTime = DateFormat('d/M/y').parse(controller);
    var tmrDate = dateTime.add(const Duration(days: 1));

    List<Calories> date = myCalories.where((o) {
      print(o.consumptionDate);
      if ((o.consumptionDate).isAfter(dateTime) &&
          (o.consumptionDate).isBefore(tmrDate)) {
        print(dateTime);
      }
      return (o.consumptionDate).isAfter(dateTime) &&
          (o.consumptionDate).isBefore(tmrDate);
    }).toList();
    for (var i = 0; i < myCalories.length; i  ) {
      totalCalories  = myCalories[i].numCalories;
      print(totalCalories);
      print(myCalories[i].numCalories);
      print(date);
    }
    //add listener here
    notifyListeners();
  }
}

Then, to display the data:

Row(
            children: [
              Text(
                Provider.of<AllCalories>(context).totalCalories,
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
              ),
            ],
          ),
  • Related