如何从外部类访问静态变量? 这是我的代码,Url使用sqflite保存在本地存储中,我想获取值并打印。 打印结果为空
DatabaseHandler.dart
//GET URL
Future<List<Url>> getUrl() async{
var db_connection = await db;
List<Map> list = await db_connection.rawQuery("SELECT * FROM Url");
List<Url> urls = List();
for(int i = 0; i < list.length; i++){
Url url = Url();
url.id = list[i]['id'];
url.uniform_resource_locator = list[i]['uniform_resource_locator'];
urls.add(url);
}
return urls;
}
readUrl.dart
import '...'
Future<List<Url>> getUrlFromCache() async {
var dbHelper = DBHandlerUrl();
Future<List<Url>> urls = dbHelper.getUrl();
return urls;
}
class readUrlTesting extends StatelessWidget {
static var url;
@override
Widget build(BuildContext context) {
return FutureBuilder<List<Url>>(
future: getUrlFromCache(),
builder: (context, snapshot) {
if (snapshot.data != null) {
if (snapshot.hasData) {
url = snapshot.data[1].uniform_resource_locator;
return Text(url);
}
return Container(
alignment: AlignmentDirectional.center,
child: CircularProgressIndicator(),
);
}
});
}
}
LoginScreen.dart
如果用户按下按钮,我想在控制台中显示Url。
child: RaisedButton(
onPressed: ()
print(readUrlTesting.url);),
答案 0 :(得分:0)
根据FutureBuilder documentation,将来应该在StatelessWidget.build方法(您正在使用)中获得。您将不得不将future传递给此小部件的构造函数,或者将小部件更改为StatefulWidget并通过State.initState方法获取Future。
希望有帮助。
此外,您是否使用FutureBuilder只是为了从期货中获取价值?如果是这样,则可以在异步方法中使用#include <boost/optional.hpp>
#include <QFile>
template <typename T>
using Opt = boost::optional<T>; // or equivalent
// Choose better name for Serializer or even split it up
class AbcdSerializer final
{
public:
AbcdSerializer(QFile& file)
: _file(file)
{
}
// You may also throw an exception instead of returning optional
Opt<Abcd> TryDeserializeAbcd()
{
long rX;
long rY;
long count;
if (ReadValue(rY) && ReadValue(rX) && ReadValue(count))
{
return Abcd(rX, rY, count);
}
return {};
}
bool SerializeAbcd(const Abcd& abcd)
{
return WriteValue(abcd.GetRY()) && WriteValue(abcd.GetRX()) && WriteValue(abcd.GetCount());
}
private:
template <typename T>
bool ReadValue(T& value)
{
constexpr auto ValueSize = sizeof(value);
return _file.read(reinterpret_cast<char*>(&value), ValueSize) != ValueSize;
}
template <typename T>
bool WriteValue(const T& value)
{
constexpr auto ValueSize = sizeof(value);
return _file.write(reinterpret_cast<const char*>(&value), ValueSize) != ValueSize;
}
QFile& _file;
};
或在将来的对象上使用await
。