【发布时间】:2019-05-19 04:55:01
【问题描述】:
我有数据库 sqlite 数据,我想在下拉列表中显示我的数据,并更改表中行的 id,因为将来我想创建另一个下拉列表以更改为第一个下拉列表的值,任何人都可以提供帮助吗?
【问题讨论】:
标签: list sqlite dart flutter dropdown
我有数据库 sqlite 数据,我想在下拉列表中显示我的数据,并更改表中行的 id,因为将来我想创建另一个下拉列表以更改为第一个下拉列表的值,任何人都可以提供帮助吗?
【问题讨论】:
标签: list sqlite dart flutter dropdown
要从 SQLite 数据库收集数据,您可以使用 sqflite plugin(如果是 iOS 或 Android 设备,则独立)。您必须将依赖项添加到您的pubspec.yaml。
dependencies:
...
sqflite: any
当您想使用 sqflite 时,您必须导入库。
import 'package:sqflite/sqflite.dart';
接下来,你必须打开一个到 SQLite 的连接,这里我们创建一个表以防你没有一个表
Database database = await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute(
'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
});
您可以使用database.rawQuery 插入或检索数据。
插入:
int primaryKeyInsertedRow = await database.rawQuery('INSERT INTO Test(name, value, num) VALUES("some name", 1234, 456.789)');
选择:
List<Map> list = await database.rawQuery('SELECT * FROM Test');
完成后记得关闭数据库。
await database.close();
为了显示您首先检索到的数据,您必须创建一个扩展 StatefulWidget 的类,覆盖 createState() 方法,并设置您自己的状态(在本例中为 SettingWidgetState)
@override
_SettingsWidgetState createState() => new _SettingsWidgetState();
其次,您应该为它定义一个状态,定义一个扩展State<NameOfYourWidget> 的类。在该类中,您应该有一个 DropdownMenuItem<String> 列表和当前选定元素的字符串成员。
为方便起见,在本例中,我们将使用静态城市列表:
List _cities = [
"Cluj-Napoca",
"Bucuresti",
"Timisoara",
"Brasov",
"Constanta"
];
接下来,我们覆盖initState(),将DropDownMenuItem 列表设置为我们的列表和当前选定的列表元素。之后我们应该打电话给super.initState()。
另外,我们需要重写build() 方法。目标是返回一个包含DropDownButton 的Container,并且DropDownButton 已分配项目列表(在类中定义)、选定元素(也在类中定义)和事件处理程序onChanged: 属性(这里还插入了其他小部件,目的是让它看起来不错)
@override
Widget build(BuildContext context) {
return new Container(
color: Colors.white,
child: new Center(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text("Please choose your city: "),
new Container(
padding: new EdgeInsets.all(16.0),
),
new DropdownButton(
value: _currentCity,
items: _dropDownMenuItems,
onChanged: changedDropDownItem,
)
],
)),
);
}
最后,我们定义从列表中选择新项目时将调用的方法(在我们的示例中为changeDropDownItem(string selectedCity))。
void changedDropDownItem(String selectedCity) {
setState(() {
_currentCity = selectedCity;
});
}
}
Link 我的答案基于下拉列表。你也可以看看getting started with sqflite plugin
【讨论】: