未为类型 'List' 定义运算符“[]”。尝试定义运算符 '[]'

The operator '[]' isn't defined for the type 'List'. Try defining the operator '[]'

我想在 BottomNavigationBarItem 中添加 lists.dart 时遇到这个问题。在脚手架底部显示红色下划线- body: _children[_currentIndex],

但不知道实际问题是什么。

是什么意思

The operator '[]' isn't defined for the type 'List'

?

这是main.dart

的完整代码
void main() {
  runApp(Main());
}

class Main extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.deepPurple,
      ),
      home: MainPage(),
    );
  }
}

class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  late SharedPreferences sharedPreferences;
  int _currentIndex = 0;
  final List _children = [
    Home(),
    OrganizationData(),
    Notifications(),
    More(),
  ] as List;

  void onTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  void initState() {
    super.initState();
    checkLoginStatus();
  }

  checkLoginStatus() async {
    sharedPreferences = await SharedPreferences.getInstance();
    if (sharedPreferences.getString("token") == null) {
      Navigator.of(context).pushAndRemoveUntil(
          MaterialPageRoute(builder: (BuildContext context) => LoginPage()),
          (Route<dynamic> route) => false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leadingWidth: 80,
        toolbarHeight: 80,
        titleSpacing: -15.0,
        title: ListTile(
          title: Text(
            "FAYZULLAH",
            style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 14,
            ),
          ),
          subtitle: Text(
            "Jr. executive",
            style: TextStyle(
              fontSize: 12,
            ),
          ),
        ),
        leading: GestureDetector(
          onTap: () {},
          child: Container(
            padding: EdgeInsets.all(10.0),
            margin: EdgeInsets.all(10.0),
            decoration: new BoxDecoration(
              borderRadius: BorderRadius.all(
                Radius.circular(50.0),
              ),
              border: Border.all(
                width: 1,
                style: BorderStyle.solid,
                color: Colors.black12,
              ),
              image: DecorationImage(
                image: AssetImage('assets/fozuda.png'),
              ),
            ),
          ),
        ),
        actions: [
          IconButton(
            icon: Icon(
              Icons.logout_rounded,
              size: 20,
            ),
            color: Colors.black,
            onPressed: () {
              sharedPreferences.clear();
              sharedPreferences.commit();
              Navigator.of(context).pushAndRemoveUntil(
                  MaterialPageRoute(
                      builder: (BuildContext context) => LoginPage()),
                  (Route<dynamic> route) => false);
            },
          ),
        ],
        backgroundColor: Colors.yellow,
      ),
      bottomNavigationBar: BottomNavigationBar(
        onTap: onTapped,
        currentIndex: _currentIndex,
        type: BottomNavigationBarType.fixed,
        // backgroundColor: Colors.yellow,
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.list),
            label: 'Lists',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.notifications),
            label: 'Notification',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.more_horiz_rounded),
            label: 'More',
          ),
        ],
      ),
      body: _children[_currentIndex],
    );
  }
}

这是 lists.dart 代码

class OrganizationData extends StatefulWidget {
  const OrganizationData({Key? key}) : super(key: key);

  @override
  _OrganizationDataState createState() => _OrganizationDataState();
}

class _OrganizationDataState extends State<OrganizationData> {
  late Future<List> futureAlbum;

  @override
  void initState() {
    super.initState();
    futureAlbum = listData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: FutureBuilder<List>(
          future: futureAlbum,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              // print(snapshot.data);
              return Text(snapshot.data!.fullName);
            } else if (snapshot.hasError) {
              return Text('${snapshot.error}');
            }
            return const CircularProgressIndicator();
          },
        ),
      ),
    );
  }
}


Future<List> listData() async {

  Dio dio = new Dio();
  dio.options.headers['Content-Type'] = 'application/json';
  final body = {'limit': 1, 'orderBy': 'idEmployee', 'orderType': 'DESC'};
  final response = await dio.post(url, data: body);
  if (response.statusCode == 200) {
    return List.fromJson(response.data["data"]["data"][0]);
  } else {
    throw Exception('Failed!');
  }
}

class List {
  final int idEmployee;
  final String fullName;

  List({
    required this.idEmployee,
    required this.fullName,
  });

  factory List.fromJson(Map<String, dynamic> json) {
    return List(
      idEmployee: json['idEmployee'],
      fullName: json['fullName'],
    );
  }
}

This is run console

lists.dart 中的 List class 重命名为其他名称,并在您使用 List class.[=15= 的任何地方更正名称]

因为有一个名为 List 的内置对象 因此,您不能将 classes 命名为“列表”。

命名您自己的 classes“列表”将覆盖内置 List class。这就是为什么 dart 会提示“运算符 '[]' 没有为 'List' 类型定义”。

因此,在您使用 class 的所有地方更改您的 class 名称。