Field '_areas' should be initialized because its type 'List<Area>' doesn't allow null

Flutter shows error Non-nullable instance field ‘_areas’ must be initialized.
Maybe this is because of not defining null in lists areas what when defining null Like List? _areas;
it shows an error on the index

Error: Field ‘_areas’ should be initialized because its type ‘List’ doesn’t allow null.

Error Line: List _areas;

Here is my code Please Help me out

import 'package:flutter/material.dart';
import 'dart:math';

 void main() {
  runApp(new MaterialApp(
   home: new MyApp(),

class MyApp extends StatefulWidget {
  _State createState() => new _State();

class Area {
  int index;
  String name;
  Color color;
  Area({this.index: -1, 'Area', this.color: Colors.lightBlueAccent});

class _State extends State<MyApp> {

 int _location = 0;
 List<Area> _areas;

void initState() {
 //_areas = new List<Area>();
 List _areas = [];
  for(int i = 0; i<16; i++){
    _areas.add(new Area(index: i, name: 'Area ${i}'));
 var rng = new Random();
 _location = rng.nextInt(_areas.length);

Widget _generate(int index){
 return new GridTile(
    child: new Container(
      padding: new EdgeInsets.all(5.0),
      child:  new RaisedButton(
          onPressed: () => _onPressed,
          color: _areas[index].color,
          child: new Text(_areas[index].name, textAlign:,),

void _onPressed(int index){
  if(index == _location) {
    _areas[index].color =;
    //You won
  } else {
    _areas[index].color =;

 Widget build(BuildContext context) {
 return new Scaffold(
  appBar: new AppBar(
    title: new Text('Grid'),
    backgroundColor: Colors.deepPurpleAccent,

  body: new Container(
      padding: new EdgeInsets.all(32.0),
      child: new Center(
          child: new GridView.count(
            crossAxisCount: 4,
            children: new List<Widget>.generate(16, _generate),


I change it From ( List _areas; to List? _areas; ) but it again shows error

>Solution :

Remove the List declaration inside your initState method, and that should fix it.

But remember to add the nullable operator to the class property:

List<Area>? _areas;

In general, though, it is better to not use nullable lists. Instead, you can initiate the property with an empty list and just add values to it later.

List<Area> _areas = [];

void initState() {
  for(int i = 0; i < 16; i++) {
    _areas.add(Area(index: i, name: 'Area ${i}'));

 _location = Random().nextInt(_areas.length);

A more elegant way of building a list is like this:

List<Area> = List<Area>.generate(
  (int i) => Area(index: i, name: 'Area $i'),

BTW, you don’t need the new keyword in Dart (Flutter).

Leave a Reply