gpt4 book ai didi

sqlite - 如何从数据库初始化列表(sqflite)

转载 作者:行者123 更新时间:2023-12-03 04:37:45 28 4
gpt4 key购买 nike

我得到了sqflite函数Future<List<Sentence>>返回的getSentences(句子是具有int id和String句子的类)。现在我要在我的主窗口小部件树中列出该列表。因此,我创建了此功能:

 Future<void> initializeSentences() async {
sentences = await getSentences();
}
而且它严重地满足了我的需求。当执行该函数时,我的列表 sentences充满了数据库中的句子。但是问题是,我不知道在哪里调用该函数。
我已经在 initState()及以下 Widget build(BuildContext context) {中尝试过它,但是如果我启动该应用程序,则总是需要做一些触发 setState()的操作才能查看加载的列表。
如何在应用程序开始时初始化该列表,并显示该列表?

最佳答案

如果您使用Stateless小部件,则应通过以下构造函数初始化值。

class MyApp extends StatelessWidget {
final List<String> sentences;

const MyApp({Key key, this.sentences}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [Text(sentences[0]), Text(sentences[1])],
),
);
}
}
如果您使用的是 StatefullWidget,则应通过 initState()方法进行初始化,或者使用如下所示的 FutureBuilder()
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';

@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}

class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);

@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
Future<String> _calculation = Future<String>.delayed(
Duration(seconds: 2),
() => 'Data Loaded',
);

Widget build(BuildContext context) {
return DefaultTextStyle(
style: Theme.of(context).textTheme.headline2,
textAlign: TextAlign.center,
child: FutureBuilder<String>(
future: _calculation, // a previously-obtained Future<String> or null
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
List<Widget> children;
if (snapshot.hasData) {
children = <Widget>[
Icon(
Icons.check_circle_outline,
color: Colors.green,
size: 60,
),
Padding(
padding: const EdgeInsets.only(top: 16),
child: Text('Result: ${snapshot.data}'),
)
];
} else if (snapshot.hasError) {
children = <Widget>[
Icon(
Icons.error_outline,
color: Colors.red,
size: 60,
),
Padding(
padding: const EdgeInsets.only(top: 16),
child: Text('Error: ${snapshot.error}'),
)
];
} else {
children = <Widget>[
SizedBox(
child: CircularProgressIndicator(),
width: 60,
height: 60,
),
const Padding(
padding: EdgeInsets.only(top: 16),
child: Text('Awaiting result...'),
)
];
}
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: children,
),
);
},
),
);
}
}

关于sqlite - 如何从数据库初始化列表(sqflite),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63826833/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com