Flutter/Dart - 如何在类之间传递变量?

Flutter/Dart - How to pass variables between classes?

我是编程新手,我正在尝试将变量 (jsonData) 从一个未来传递到另一个 class 中的另一个未来,因此来自变量的数据可以存储在数据库中。不要混淆,我正在使用 API 来获取必要的数据,这工作得很好。关于如何访问变量 jsonData 以插入数据的任何提示?

//first class gets the json data
class getJSONData {

Future<void> makeRequest() async {
var url = "some url";

Map inputData = {
  "Password": example,
  "SQL": sql query,
  "db_server": "server",
  "db_table": "table",
};

var body = json.encode(inputData);

var putRequest = await http.put(
    Uri.encodeFull(url), headers: {"Content-Type": "application/json"},
    body: body);

//this variable has to be stored
var jsonData = json.decode(putRequest.body);
  }
}


//data needs to be inserted here

class Database {

Future<void> insertJSON() async {
db = await openDatabase(
  join(await getDatabasesPath(), tableName),
  onCreate: (db, version) {
    return db.execute('''
     INSERT INTO $tableName(column1, column2, etc) VALUES (${jsonData["Records].data1}, ${jsonData["Records].data2}, etc)
     ''');
     }
   );
 }
}

下面我将向您展示如何在两个屏幕之间传递数据:

屏幕 1:

class HomeScreenTopContainer extends StatefulWidget {
  @override
  _HomeScreenTopContainerState createState() => _HomeScreenTopContainerState();
}

class _HomeScreenTopContainerState extends State<HomeScreenTopContainer> {


  @override
  void initState() {
    // TODO: implement initState
    super.initState();

  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
       Inkwell(onTap:(){
                  Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => ParentLanding(parameter:"pass your value here")),
        );
       },child:Text("Tap Here and pass data")),
        
      ],
    );
  }
}

屏幕 2:

 class ParentLanding extends StatefulWidget {
String parameter;
 ParentLanding({Key key,String parameter}) : super(key: key,parameter:parameter);
      @override
      _ParentLandingState createState() => _ParentLandingState();
    }
    
    class _ParentLandingState extends State<ParentLanding> {
    
    
      @override
      void initState() {
        // TODO: implement initState
        super.initState();
    
      }
    
      @override
      Widget build(BuildContext context) {
        return Stack(
          children: <Widget>[
           Inkwell(onTap:(){
                     // you can use this parameter like this.
           },child:Text(**Widget.parameter**)),
            
          ],
        );
      }
    }

传递任何值的最简单方法是使用参数。 值可以发送为:

 Keys.navKey.currentState.pushNamed(
      Routes.gameViewScreen, arguments: jsonData );

在另一个class中,它可以检索为:

var jsonData = ModalRoute.of(context).settings.arguments;

你有很多选择。 我给你推荐一个。 更改这两种方法的签名。
例子

你的 HttpClient class

Future<Map<String, dynamic>> makeRequest() async {
    // ... your code
    var jsonData = json.decode(putRequest.body);
    return jsonData;
}

你的数据库Class

    Future<void> insertJSON(Map<String, dynamic> jsonData) async {
        db = await openDatabase(
        join(await getDatabasesPath(), tableName),
        onCreate: (db, version) {
        return db.execute('''
           INSERT INTO $tableName(column1, column2, etc) VALUES 
            (${jsonData["Records].data1}, ${jsonData["Records].data2}, etc)
          ''');
     }
   );
 }

使用第三个 Class/object/method 调用 api,获取结果并将其传递给数据库 class:

main() async {
    HttClient http = HttpClient();
    Database db = Database();
    final json = await http.makeRequest();
    await db.insertJSON(json);
}