在Dart/Flutter中,我如何使用方法中的变量,以便将其输出到文本字段



希望有人能帮忙——几周前我遇到了这个死胡同,认为我已经在有限的知识范围内尝试了一切。

我已经建立了一个工作正常的数据库,也就是说,我可以在一个屏幕上添加数据,查看数据,并在另一个屏幕中编辑数据。现在,我想将在"debugPrint"中验证过的其中一列(牛肉(汇总到控制台。我想从"sumBeef"方法访问这个变量"beefTotal",并在UI的文本字段中打印显示它。不过我就是应付不了。它只是返回null。

提前感谢您的帮助。

import 'package:flutter/material.dart';
import 'package:take_note/utils/database_helper.dart';
class Info extends StatefulWidget {
@override
State<StatefulWidget> createState() => _InfoState();
}
DatabaseHelper helper = DatabaseHelper();
var database = DatabaseHelper();
class _InfoState extends State<Info> {
List beefTotal;
@override
Widget build (BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Beef Info"),
backgroundColor: Colors.lightBlueAccent,
),
body: Container(
child: Column(
children: <Widget>[
Expanded(
child: Center(
child: RaisedButton(
onPressed: (){
sumBeef();
},
),
),
),
Expanded(
child: Center(
child: Text("Total Beef is: £ $beefTotal", style: TextStyle(
color: Colors.lightBlueAccent,
fontSize: 30.0,
fontWeight: FontWeight.w400
),),
),
),
],
),
)
);
}
void sumBeef () async {
beefTotal = await database.addBeef();
debugPrint("Total beef: $beefTotal");
}
}

下面的代码来自一个名为DatabaseHelper的类,方法sumBeef((使用

Future<List<Map<String, dynamic>>> addBeef()async{
Database db = await this.database;
var result = await db.rawQuery("SELECT SUM(beef) FROM $table");
return result;
}
```[enter image description here][1]

[1]: https://i.stack.imgur.com/L46Gj.png

只需调用setState({

});

void sumBeef () async {
beefTotal = await database.addBeef();
setState(() {});
debugPrint("Total beef: $beefTotal");
}

和你的好!无论何时进行更改,都必须调用setState方法来更新flutters情况下的ui(重建(

最新更新