简体   繁体   English

flutter中如何调用setState子类?

[英]How call setState subclass in flutter?

how to call setState function in subclass如何在子类中调用setState function

Hi, here page open time api call first then response i used sub class split values, then i need page refresh (reason: api response received after only i got value in sub class).嗨,这里页面打开时间 api 先调用然后响应我使用子 class 拆分值,然后我需要页面刷新(原因:api 响应仅在我在子类中获得值后收到)。 Please anyone help me how to call page refresh in subclass请任何人帮助我如何在子类中调用页面刷新

Unhandled Exception: Null check operator used on a null value _DemoClassState.getprefvalues未处理的异常:Null 检查运算符用于 null 值 _DemoClassState.getprefvalues

class view_member extends StatefulWidget {
      @override
      _DemoClassState createState() => _DemoClassState();
    }
    
    class _DemoClassState extends State<view_member> {
    //call api & Getunload here
    
    }
    
    
    class Getunload {
      String quan='';
      String rate='';
      String amt='';
    
    
      Getunload(this.quan,
          this.rate,
          this.amt,
          );
    
      Getunload.fromJson(Map<String, dynamic> json)
      {
        quan= json['quan'];
        print("quanzzzunload"+quan);
        rate= json['rate'];
        amt= json['amt'];
      }
    
      Map<String, dynamic> toJson() =>
          {
            'quan' : quan,
            'rate': rate,
            'amt': amt,
    
          };
      Future<void> setprefval() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString(UNLOAD_QTY, quan);
        prefs.setString(UNLOAD_RATE, rate);
        prefs.setString(UNLOAD_TOTAL, amt);
      }
    }
    class Getdetention {
      String quan='';
      String rate='';
      String amt='';
    
    
      Getdetention(this.quan,
          this.rate,
          this.amt,
          );
    
      Getdetention.fromJson(Map<String, dynamic> json)
      {
        quan= json['quan'];
        print("quandeten"+quan);
        rate= json['rate'];
        amt= json['amt'];
      }
    
      Map<String, dynamic> toJson() =>
          {
            'quan' : quan,
            'rate': rate,
            'amt': amt,
    
          };
      Future<void> setprefval() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString(DETENTION_QTY, quan);
        prefs.setString(DETENTION_RATE, rate);
        prefs.setString(DETENTION_TOTAL, amt);
          setState(() {// showing error 'The method 'setState' isn't defined for the type 'Getdetention''
    
          });
    
      }
    
    }

Try moving the method Future<void> setprefval() async {...} to a class _DemoClassState and then your setState(() {});尝试将方法Future<void> setprefval() async {...}移动到 class _DemoClassState然后是你的setState(() {}); will have to work.将不得不工作。 An example of how I want to do it:我想怎么做的一个例子:

class _DemoClassState extends State<view_member> {
//call api & Getunload here

  Future<void> setprefval() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString(DETENTION_QTY, quan);
    prefs.setString(DETENTION_RATE, rate);
    prefs.setString(DETENTION_TOTAL, amt);
      setState(() {// showing error 'The method 'setState' isn't defined for the type 'Getdetention''

      });

  }
}

If I were you, I would do it differently.如果我是你,我会做不同的事情。 First, because you are using Shared Preferences , you would create a class that regulates the insertion and receiving of data, and then call its methods in the right places.首先,因为您正在使用Shared Preferences ,您将创建一个 class 来规范数据的插入和接收,然后在正确的位置调用它的方法。 I have a code example using Flutter Secure Storage (almost the same as Shared Preferences, but better) so you can see what I'm talking about:我有一个使用Flutter 安全存储的代码示例(几乎与共享首选项相同,但更好)所以你可以看到我在说什么:

pubspec.yaml: pubspec.yaml:

  flutter_secure_storage: ^5.0.2

secure_storage.dart:安全存储.dart:

import 'package:flutter_secure_storage/flutter_secure_storage.dart';

class SecureStorage {
  // Create an instance and enable secure encryption:
  static const storage = FlutterSecureStorage(
      aOptions: AndroidOptions(encryptedSharedPreferences: true));

  static Future<void> saveData(String key, String value) async {
    await storage.write(key: key, value: value);
  }

  static Future<String?> readData(String key) async {
    return await storage.read(key: key);
  }

  static Future<Map<String, String>> readAllData(String key) async {
    return await storage.readAll();
  }

  static Future<bool> containsData(String key) async {
    return await storage.containsKey(key: key);
  }

  static Future<void> deleteData(String key) async {
    await storage.delete(key: key);
  }

  static Future<void> deleteAllData() async {
    await storage.deleteAll();
  }
}

And then you can access the database class whenever you want because it has static methods:然后你可以随时访问数据库 class 因为它有 static 方法:

SecureStorage.saveData("valueKey", valueData);

Example of read:读取示例:

  static var valueData; // Declare a variable

  @override
  void initState() {
    super.initState();
    initSettings(); // Call initialization in initState()
  }

  void initSettings() async {
    valueData = await SecureStorage.readData("valueKey"); // Read value
    setState(() {});
  }

And if you want to call the setState(() {});如果你想调用setState(() {}); then call it in classes inherited from StatefulWidget when receiving data from the database.然后在从 StatefulWidget 继承的类中调用它,当从数据库接收数据时。

This is the simplest solution to usage of your setState(() {});这是使用setState(() {});最简单的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM