0

I'm trying to build Tic Tac Toe game, but whenever I click on the box in matrix it shows me the error.

This is the Emulator Screen. https://drive.google.com/file/d/1DnSVT-snvKfe-2BHUGmeBpK4UlJAO6lV/view?usp=sharing

    ======== Exception caught by gesture ===============================================================
The following NoSuchMethodError was thrown while handling a gesture:
The method '[]' was called on null.
Receiver: null
Tried calling: [](0)

When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1      _MyHomePageState._buildElement.<anonymous closure>.<anonymous closure> (package:tic_tac_toe/main.dart:92:22)
#2      State.setState (package:flutter/src/widgets/framework.dart:1267:30)
#3      _MyHomePageState._buildElement.<anonymous closure> (package:tic_tac_toe/main.dart:91:9)
#4      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#ffb93
  debugOwner: GestureDetector
  state: possible
  won arena
  finalPosition: Offset(83.6, 315.3)
  finalLocalPosition: Offset(37.3, 56.5)
  button: 1
  sent tap down
====================================================================================================

This is the code I'm using.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Tic Tac Toe',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  List<List> _matrix;
  @override
  void initState() {
    List<List> _matrix = new List<List> ();

  }
  MyHomePage() {
    _matrix = List<List>(3);
    for (var i = 0; i < _matrix.length; i++) {
      _matrix[i] = List(3);
      for (var j = 0; j < _matrix.length; j++) {
        _matrix[i][j] = ' ';
      }
    }
  }

  @override

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Tic Tac Toe",
        ),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _buildElement(0, 0),
                _buildElement(0, 1),
                _buildElement(0, 2),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _buildElement(1, 0),
                _buildElement(1, 1),
                _buildElement(1, 2),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _buildElement(2, 0),
                _buildElement(2, 1),
                _buildElement(2, 2),
              ],
            ),
          ],
        ),
      ),
    );
  }

  String lastChar = '0';
   _buildElement(int i, int j) {
    return GestureDetector(
      onTap: () {
        setState(() {
          if (_matrix[i][j] == ' ') {
            if (lastChar == 'o') {
              _matrix[i][j] = 'x';
            } else {
              _matrix[i][j] = 'o';
            }
            lastChar = _matrix[i][j];
          }
          for (var k = 0; k < _matrix.length; k++) {
            var str = '';
            for (var m = 0; m < _matrix[k].length; m++) {
              str += _matrix[k][m];
            }
          }
        });
      },
      child: Container(
        decoration: BoxDecoration(
          border: Border.all(
            color: Colors.black,
          ),
        ),
        height: 100,
        width: 100,
        child: Text(
          " ",
          style: TextStyle(
            fontSize: 100.0,
          ),
        ),
      ),
    );
  }
}

Thanks for the help, if you need more information let me know.

Alee
  • 1
  • Does this answer your question? [Flutter - The method was called on null](https://stackoverflow.com/questions/52046870/flutter-the-method-was-called-on-null) – Md. Yeasin Sheikh Dec 31 '21 at 14:30
  • Does this answer your question? [What is a NoSuchMethod error and how do I fix it?](https://stackoverflow.com/questions/64049102/what-is-a-nosuchmethod-error-and-how-do-i-fix-it) – nvoigt Apr 18 '22 at 09:37

1 Answers1

0

So there were a few little issues in your code. I believe you were trying to initialize _matrix in a constructor:

  MyHomePage() {
    _matrix = List<List>(3);
    for (var i = 0; i < _matrix.length; i++) {
      _matrix[i] = List(3);
      for (var j = 0; j < _matrix.length; j++) {
        _matrix[i][j] = ' ';
      }
    }
  }

But the class scope you are in there is actually _MyHomePageState. Therefore that is not a constructor, but a function that is never called. Therefore your _matrixis null.

I suggest you move that logic into initState, since initial setup of variables is exactly what initStateis there for. I took the liberty to write up the changed function here:

  @override
  void initState() {
    super.initState();
    List<List<String>> newMatrix = new List<List<String>>(3);
    for (var i = 0; i < newMatrix.length; i++) {
      newMatrix[i] = new List<String>(3);
      for (var j = 0; j < newMatrix.length; j++) {
        newMatrix[i][j] = ' ';
      }
    }

    _matrix = newMatrix;
  }

I also cleaned your code a bit, for instance setState should always call super.initState.

EDIT: Just to clarify:

  MyHomePage() {
  //This is a function called "MyHomePage"
  //In a class named "MyHomePage" this would be a constructor
  }

  _MyHomePageState() {
  //This is a constructor in your class "_MyHomePageState"
  }
Dharman
  • 30,962
  • 25
  • 85
  • 135
Benedikt J Schlegel
  • 1,707
  • 1
  • 10
  • 23