Flutter method was called on null?

Issue

When i call the method from the same class then it works perfectly but when I made the method in separate class it gives me an error.

The method ‘add’ was called on null.
Receiver: null

import 'package:flutter/material.dart';
import 'package:logic_conversion/custom_widgets/custom_appbar.dart';
import 'package:logic_conversion/image_to_text/img-to-text.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  int a = 10, b = 20;
  Method m;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: Custom_Appbar('Sample Page'),
      body: Column(
      children: <Widget>[
        RaisedButton(onPressed: ()=>m.add(a, b),child: Text('Add'))
      ]
    ),);
  }
}

Where “m” is the object of Method class and I call method as

m.add(a, b)

Method Class is given as:

    class Method{
       int add(int a, int b){
       int c;
       c = a+b;
       print(c);
     }
   }

Solution

You haven’t instantiated the Method class, ie Method m = Method(). Therefore your m variable is null.

Answered By – Luke Greenwood

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.