Flutter 使用本地sqlite文件创建列表视图

Flutter 使用本地sqlite文件创建列表视图,flutter,sqflite,Flutter,Sqflite,使用sqflite从本地sql文件(chinook.db)创建listview 初始问题已解决: I/flatter(5084)‘未来’实例 参考代码: 谢谢@aakash的帮助 main.dart body: Container( child: FutureBuilder( future: getSQL("albums"), builder: (BuildContext context, AsyncSnapshot snapshot) {

使用sqflite从本地sql文件(chinook.db)创建listview 初始问题已解决: I/flatter(5084)‘未来’实例 参考代码: 谢谢@aakash的帮助

main.dart
body: Container(
        child: FutureBuilder(
          future: getSQL("albums"),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            print(snapshot.data);
            if (snapshot.data == null) {
              return Container(child: Center(child: Text("Loading...")));
            } else {
              return ListView.builder(
                itemCount: snapshot.data.length,
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                    title: Text(snapshot.data[index].title),
                  );
                },
              );
            }
          },
        ),
      ),

getSQL.dart 
Future getSQL(String tableName) async {
  var databasesPath = await getDatabasesPath();
  var path = join(databasesPath, "chinook.db");
// Check if the database exists
  var exists = await databaseExists(path);
  if (!exists) {
    // Should happen only the first time you launch your application
    print("Creating new copy from asset");
    // Make sure the parent directory exists
    try {
      await Directory(dirname(path)).create(recursive: true);
    } catch (_) {}
    // Copy from asset
    ByteData data = await rootBundle.load(join("assets", "chinook.db"));
    List<int> bytes =
        data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
    // Write and flush the bytes written
    await File(path).writeAsBytes(bytes, flush: true);
  } else {
    print("Opening existing database");
  }
// open the database
  var db = await openDatabase(path, readOnly: true);

  List<Map> list = await db.rawQuery('SELECT * FROM $tableName');
  List theList = [];
  for (var n in list) {
    theList.add(MyCategoryFinal(n["Title"]));
  }
  return (theList);
}
class MyCategoryFinal {
  final String title;
  MyCategoryFinal(this.title);
}
main.dart
主体:容器(
孩子:未来建设者(
未来:getSQL(“相册”),
生成器:(BuildContext上下文,异步快照){
打印(快照数据);
如果(snapshot.data==null){
返回容器(子:中心(子:文本(“加载…”));
}否则{
返回ListView.builder(
itemCount:snapshot.data.length,
itemBuilder:(构建上下文,int索引){
返回列表块(
标题:文本(快照.数据[索引].标题),
);
},
);
}
},
),
),
getSQL.dart
未来的getSQL(字符串表名)异步{
var databasesPath=等待getDatabasesPath();
var path=join(databasesPath,“chinook.db”);
//检查数据库是否存在
var exists=等待数据库exists(路径);
如果(!存在){
//应该仅在第一次启动应用程序时发生
打印(“从资产创建新副本”);
//确保父目录存在
试一试{
等待目录(dirname(path)).create(递归:true);
}捕获({}
//从资产中复制
ByteData=wait rootBundle.load(连接(“资产”、“chinook.db”);
列表字节=
data.buffer.asUint8List(data.offsetingbytes,data.lengthInBytes);
//写入并刷新写入的字节
等待文件(路径).writeAsBytes(字节,刷新:true);
}否则{
打印(“打开现有数据库”);
}
//打开数据库
var db=await openDatabase(路径,只读:true);
List List=await db.rawQuery('SELECT*FROM$tableName');
列表列表=[];
for(列表中的变量n){
添加(MyCategoryFinal(n[“标题]));
}
返回(列表);
}
类MyCategoryFinal{
最后的字符串标题;
MyCategoryFinal(本标题);
}

我通过为sqflite表创建一个类来解决这个问题,在该映射列表上运行一个循环,并将这些映射项转换为对象列表

示例代码

List<ItemBean> items = new List();
    list.forEach((result) {
      ItemBean story = ItemBean.fromJson(result);
      items.add(story);
    });

从源代码在类中添加项时遇到问题,下面添加了Future….List List=wait db.rawQuery('SELECT*from$tableName')//打印(列表);列表列表=[];对于(列表中的变量n){MyCategory theList=MyCategory(n[“CategoryName”],n[“CategoryDescription”];theList.add(theList);}返回(theList);}类MyCategory{final String categoryName;final String categoryDescription;MyCategory(this.categoryName,this.categoryDescription);}我做错了吗?您的列表和MyCategory对象的名称相同。这就是为什么您在添加项目时会遇到问题。当您在for循环中创建
MyCategory列表
时,它将创建一个本地对象,以替换原始的
列表
。在for loop中为您的对象指定一个不同的名称,或者您可以简单地添加该项,而无需创建类似以下内容的对象
theList.add(MyCategory(n[“CategoryName”]、n[“CategoryDescription”)谢谢@aakash,问题解决了。编辑原文供参考
       FutureBuilder(
          future: MyService.getAllItems(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) {
              return Center(child: CircularProgressIndicator());
            }

            return ListView.builder(
              controller: listScrollController,
              itemCount: snapshot.data.length,
              reverse: true,
              itemBuilder: (context, index) {
                return Text(snapshot.data[index].itemName);
              },
            );
          },
        ),