方法 'setState' 没有为类型 'NasabahDataTableSource' 定义

The method 'setState' isn't defined for the type 'NasabahDataTableSource'

我想在 class“NasabahDataTableSource”中使用 setState 方法,但是当我在此 class 中使用 setState 时无法工作并且错误:方法 'setState' 未定义class 'NasabahDataTableSource'.

这是 mystatefullwidget。

class DataNasabah extends StatefulWidget {
  @override
  _DataNasabahState createState() => _DataNasabahState();
}

class _DataNasabahState extends State<DataNasabah> {
  String nama_debitur = '';
  List<Nasabah> _nasabah = [];


  @override
  void initState() {
    super.initState();
    _loadUserData();
    _getNasabah();
  }

  _loadUserData() async {
    SharedPreferences localStorage = await SharedPreferences.getInstance();
    var user = jsonDecode(localStorage.getString('user'));

    if (user != null) {
      setState(() {
        nama_debitur = user['nama_debitur'];
      });
    }
  }

  _getNasabah() {
    NasabahService.getUser().then((nasabah) {
      if (mounted) {
        setState(() {
          _nasabah = nasabah;
        });
      }
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text('Data Nasabah'),
        backgroundColor: Color(0xff151515),
        // automaticallyImplyLeading: false,
      ),
      body: SingleChildScrollView(
        child: PaginatedDataTable(
          rowsPerPage: 10,
          columns: [
            DataColumn(
              label: Expanded(
                  child: Text(
                'ID Nasabah',
                textAlign: TextAlign.center,
              )),
            ),
            DataColumn(
              label: Expanded(
                  child: Text(
                'Nama Nasabah',
                textAlign: TextAlign.center,
              )),
            ),
            DataColumn(
              label: Expanded(
                  child: Text(
                'Aksi',
                textAlign: TextAlign.center,
              )),
            ),
          ],
          source: NasabahDataTableSource(userData: _nasabah, context: context),
        ),
      ),
    );
  }
}

我想在此 class.but 中使用 setState 方法,不能 use.I comment setState 地点

class NasabahDataTableSource extends DataTableSource {
  BuildContext context;
  NasabahDataTableSource({this.context, this.userData});
  final List<Nasabah> userData;

  @override
  DataRow getRow(int index) {
    return DataRow.byIndex(
      index: index,
      cells: [
        DataCell(Align(
            alignment: Alignment.center,
            child: Text(
              "${userData[index].id}",
            ))),
        DataCell(Align(
          alignment: Alignment.center,
          child: Text("${userData[index].nama_debitur}"),
        )),
        DataCell(
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              IconButton(
                icon: Icon(Icons.navigate_next),
                color: Colors.blueAccent,
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) =>
                          DetailNasabah(
                            nasabah: userData[index],
                          ),
                    ),
                  );
                },
              ),
              IconButton(
                icon: Icon(Icons.delete),
                color: Colors.red,
                onPressed: () {
                  showDialog(
                    context: context,
                    builder: (context) =>
                        AlertDialog(
                          title: Text('Hapus Data Nasabah'),
                          content: Text(
                              'Apakah anda yakin ingin menghapus data nasabah ini?'),
                          actions: [
                            TextButton(
                                child: Text('Yes'),
                                onPressed: () {
                                  NasabahService.deleteUser(userData[index].id);
                                  setState(() {
                                    //Cann't use
                                  });
                                })
                          ],
                        ),
                  );
                },
              )
            ],
          ),
        ),
      ],
    );
  }

我还没有找到那个解决方案。 请帮忙。

您不能在 NasabahDataTableSource 中设置状态,因为它没有扩展 StatefulWidget。只有有状态的人才能设置状态。 但是你可以在无状态的情况下使用 getx 在没有 setstate 的情况下更改变量。

没有 StatefulWidget 就不能使用 setState()。我建议您使用 Function 传递您的操作并通知重建 UI 使用 setState()。需要对您的代码进行一些修改。

  1. Function 参数添加到您的 NasabahDataTableSource
Function onUserDeleted;
  1. 修改您的 NasabahDataTableSource 构造函数。
NasabahDataTableSource({required this.context,required this.userData,required this.onUserDeleted}); // modify your constructor
  1. setState替换为onUserDeleted里面的onPressed
onUserDeleted(); // call onUserDeleted
//setState(() {
       //Cann't use
//});

NasabahDataTableSource完整代码。

class NasabahDataTableSource extends DataTableSource {
  BuildContext context;
  Function onUserDeleted; // add onUserDeleted function
  final List<Nasabah> userData;
  NasabahDataTableSource({required this.context,required this.userData,required this.onUserDeleted}); // modify your constructor

  @override
  DataRow getRow(int index) {
    return DataRow.byIndex(
      index: index,
      cells: [
        DataCell(Align(
            alignment: Alignment.center,
            child: Text(
              "${userData[index].id}",
            ))),
        DataCell(Align(
          alignment: Alignment.center,
          child: Text("${userData[index].nama_debitur}"),
        )),
        DataCell(
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              IconButton(
                icon: Icon(Icons.navigate_next),
                color: Colors.blueAccent,
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) =>
                          DetailNasabah(
                            nasabah: userData[index],
                          ),
                    ),
                  );
                },
              ),
              IconButton(
                icon: Icon(Icons.delete),
                color: Colors.red,
                onPressed: () {
                  showDialog(
                    context: context,
                    builder: (context) =>
                        AlertDialog(
                          title: Text('Hapus Data Nasabah'),
                          content: Text(
                              'Apakah anda yakin ingin menghapus data nasabah ini?'),
                          actions: [
                            TextButton(
                                child: Text('Yes'),
                                onPressed: () {
                                  NasabahService.deleteUser(userData[index].id);
                                  onUserDeleted(); // call onUserDeleted
                                  //setState(() {
                                    //Cann't use
                                  //});
                                })
                          ],
                        ),
                  );
                },
              )
            ],
          ),
        ),
      ],
    );
  }
  1. 通过添加 onUserDeleted 修改您的 DataNasabah 来源并调用 setState
source: NasabahDataTableSource(
                    userData: _nasabah,
                    context: context,
                    onUserDeleted:(){
                      setState((){}); // add setState
                    }),

DataNasabah完整代码。

class DataNasabah extends StatefulWidget {
  @override
  _DataNasabahState createState() => _DataNasabahState();
}

class _DataNasabahState extends State<DataNasabah> {
  String nama_debitur = '';
  List<Nasabah> _nasabah = [];


  @override
  void initState() {
    super.initState();
    _loadUserData();
    _getNasabah();
  }

  _loadUserData() async {
    SharedPreferences localStorage = await SharedPreferences.getInstance();
    var user = jsonDecode(localStorage.getString('user'));

    if (user != null) {
      setState(() {
        nama_debitur = user['nama_debitur'];
      });
    }
  }

  _getNasabah() {
    NasabahService.getUser().then((nasabah) {
      if (mounted) {
        setState(() {
          _nasabah = nasabah;
        });
      }
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text('Data Nasabah'),
        backgroundColor: Color(0xff151515),
        // automaticallyImplyLeading: false,
      ),
      body: SingleChildScrollView(
        child: PaginatedDataTable(
          rowsPerPage: 10,
          columns: [
            DataColumn(
              label: Expanded(
                  child: Text(
                'ID Nasabah',
                textAlign: TextAlign.center,
              )),
            ),
            DataColumn(
              label: Expanded(
                  child: Text(
                'Nama Nasabah',
                textAlign: TextAlign.center,
              )),
            ),
            DataColumn(
              label: Expanded(
                  child: Text(
                'Aksi',
                textAlign: TextAlign.center,
              )),
            ),
          ],
          source: NasabahDataTableSource(
                    userData: _nasabah,
                    context: context,
                    onUserDeleted:(){
                      setState((){}); // add setState
                    }),
        ),
      ),
    );
  }
}