应初始化字段“_areas”,因为其类型 'List<Area>' 不允许为空

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

Flutter 显示错误 Non-nullable instance field '_areas' must be initialized。 也许这是因为没有在列表区域中定义 null 定义 null Like List 时怎么办? _地区; 它显示索引错误

错误:应初始化字段“_areas”,因为其类型 'List' 不允许为空。

错误行:列表_areas

这是我的代码请帮帮我

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

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

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

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

class _State extends State<MyApp> {

 int _location = 0;
 List<Area> _areas;

@override
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: TextAlign.center,),
      ),
    )
 );
}

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

@override
 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),
          )
      )
   ),
 );
}


}

我将其从 ( List _areas; 更改为 List?_areas; ) 但它再次显示错误

你好我认为你声明2个_areas的问题你必须删除iniState方法中_areas之前的List词

删除 initState 方法中的 List 声明,这样应该可以解决问题。

但记得在 class 属性:

中添加可空运算符
List<Area>? _areas;

不过,一般来说,最好不要使用可空列表。相反,您可以使用空列表启动 属性,稍后再向其添加值。

List<Area> _areas = [];

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

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

构建列表的更优雅的方式是这样的:

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

顺便说一句,在 Dart (Flutter) 中不需要 new 关键字。

请参考这个:

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

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  _State createState() => _State();
}

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

class _State extends State<MyApp> {
  int _location = 0;
  List<Area> _areas = [];

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

  Widget _generate(int index) {
    return GridTile(
        child: Container(
      padding: EdgeInsets.all(5.0),
      child: ElevatedButton(
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(Colors.blue),
        ),
        onPressed: () => _onPressed(index),
        child: Text(
          _areas[index].name,
          textAlign: TextAlign.center,
        ),
      ),
    ));
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Grid'),
        backgroundColor: Colors.deepPurpleAccent,
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          print(_areas.length.toString());
        },
      ),
      body: Container(
        padding: const EdgeInsets.all(32.0),
        child: Center(
          child: GridView.count(
            crossAxisCount: 4,
            children: List<Widget>.generate(16, _generate),
          ),
        ),
      ),
    );
  }
}

请这样使用latelate List<Area> _areas