Home > Mobile >  How to call method in class from another class in Flutter?
How to call method in class from another class in Flutter?

Time:05-03

I have created Convertor.dart class and there is a function _convertor.It is used to convert Km to m.And I want to call this function in the TextButton (onPressed method) of convertingscreen.dart .Then I want to user after press the button, show the answer in the Text widget. but there is an error showed.

And code is given below:

Convertor.dart

class Convertor{


  static _convert(uValue, rValue, num1) {
    if(uValue == 'Km' && rValue == 'm') {
      var result = num1 * 1000;
      return result;
    }
  }

}

convertingscreen.dart

import 'package:flutter/material.dart';

import '../Convertor.dart';


class ConvertingScreen extends StatefulWidget {
  const ConvertingScreen({Key? key}) : super(key: key);
  static const routName = 'converting-screen';

  @override
  State<ConvertingScreen> createState() => _ConvertingScreenState();
}

class _ConvertingScreenState extends State<ConvertingScreen> {
  final units = ['Km','m'];
  String? value;
  String? resultValue;
  String? result;
  TextEditingController enterValue = TextEditingController();
  final Convertor convertor = Convertor();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [

            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Expanded(child:_buildValue(),),

                DropdownButton<String>(
                  items: units.map(buildMenuUnit).toList(),
                  onChanged: (value)=> setState(()=>
                    this.value = value),
                  value: value,
                ),



              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Expanded(child: Text('$result')),

                DropdownButton<String>(
                  items: units.map(buildMenuUnit).toList(),
                  onChanged: (resultValue)=> setState(()=>
                  this.resultValue = resultValue),
                  value: resultValue,
                ),



              ],
            ),
            TextButton(
                onPressed: (){
               
                  var r = Convertor._convert(value, resultValue, enterValue.text);
                    print(value);
                    print(resultValue);
                    print(enterValue.text);
                    setState(() {
                      result = r;
                    });

                },
                child: Container(
                  padding: EdgeInsets.symmetric(
                      vertical: 6, horizontal: 6),
                  width: double.infinity,
                  child: const Center(
                    child: Text(
                      'Convert',
                      textAlign: TextAlign.center,
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
                style: ButtonStyle(
                    shape: MaterialStateProperty.all<
                        RoundedRectangleBorder>(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(27),
                        )),
                    backgroundColor: MaterialStateProperty.all(
                        const Color(0xff102248))))

          ],
        ),
      ),
    );

  }
  DropdownMenuItem<String> buildMenuUnit(String unit)=>
      DropdownMenuItem(value: unit, child: Text(
        unit,
        style: TextStyle(
          fontWeight: FontWeight.bold,
          fontSize: 20
        ),
      ),);
  DropdownMenuItem<String> buildMenuResultUnit(String unit)=>
      DropdownMenuItem(value: unit, child: Text(
        unit,
        style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 20
        ),
      ),);




  Widget _buildValue(){
    return Container(
      margin: EdgeInsets.symmetric(vertical: 5, horizontal: 40),
      child: TextFormField(
        controller: enterValue,
        keyboardType: TextInputType.number,
        textAlign: TextAlign.center,
        decoration: InputDecoration(
            contentPadding:
            EdgeInsets.symmetric(vertical: 5, horizontal: 5),
            hintText: "Enter value",
            border:
            OutlineInputBorder(borderRadius: BorderRadius.circular(30))),
      ),
    );

  }


}

CodePudding user response:

Unlike Java or C#, Dart doesn’t have the keywords public, protected, and private. If an identifier starts with an underscore _, it’s private.

So, change the function name from _convert to convert and call it like Convertor.convert(value, resultValue, enterValue.text);

class Convertor{
  static convert(uValue, rValue, num1) {
    if(uValue == 'Km' && rValue == 'm') {
      var result = num1 * 1000;
      return result;
    }
  }
}

CodePudding user response:

Currently your function is Multiplying a String 1000 times which means it will show same string i.e. your input value 1000 times.

So, in order to get the desired output , add type to your convert() function parameters and result variable.

You can also try using int

Like this:

static _convert(uValue, rValue, double num1) {
    if(uValue == 'Km' && rValue == 'm') {
      double result = num1 * 1000;
      return result;
    }
  }

Also convert your double value to String to pass to Text Widget. Or else, it will throw error saying 'The argument type 'String' can't be assigned to the parameter type 'double'.

var r = Convertor._convert(value, resultValue, double.parse(enterValue.text)).toString();

For large text values after conversion, screen size may not be sufficient and it will throw 'BottomOverFlow Error'

To prevent this

Wrap your body : Center with SingleChildScrollView

body: SingleChildScrollView(
        child: Center(
  • Related