Flutter:为什么我无法从 sqflite 中查看列表?
我是颤振的初学者。我创建了一个方法,从“todos”表中选择特定列,因此我希望在列表类型“todos”中接收该查询。
但是当我调用它时,这不会出现在屏幕上。我做错了什么?
证据:
这是我的数据库助手:
import 'dart:developer';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'lista_model.dart';
class DatabaseHandler {
Future<Database> initializeDB() async {
String path = await getDatabasesPath();
return openDatabase(
join(path, 'courses.db'),
onCreate: (database, version) async {
final String sql = ''
'CREATE TABLE todos ('
' id INTEGER PRIMARY KEY AUTOINCREMENT,'
' title TEXT,'
' entidad TEXT,'
' categoria TEXT,'
' emision TEXT,'
' imgcourse TEXT,'
' urlcourse TEXT,'
' description TEXT'
')';
await database.execute(sql);
final String addCourse = ''
'INSERT INTO todos(title, entidad, categoria, emision, imgcourse, urlcourse, description) VALUES ('
'"Control" , "Slim", "TIC", "Certificable", "https://dinahosting.com", "https://aprende.org/", "+Entu formación académica y profesional."),'
'("Transparencia" , "Defensoría", "Ciencias", "Certificable", "https://www.notinetlegal.com", "https://campusvirtual", "+El accesopara tu formación académica y profesional.")'
;
await database.execute(addCourse);
},
version: 1,
);
}
//this is the method where i make the column select query and it works fine
Future<List<Map>> queryCat() async {
Database db = await initializeDB();
db.rawQuery('SELECT categorias FROM todos WHERE categoria="TIC"');
List<Map> result =
await db.rawQuery('SELECT * FROM todos WHERE categoria=?', ['TIC']);
// print the results
result.forEach((row) => print(row));
return result;
}
//method to make all query
Future<List<todo>> todos() async {
final db = await initializeDB();
final List<Map<String, dynamic>> queryResult = await db.query('todos');
return queryResult.map((e) => todo.fromMap(e)).toList();
}
//this method was antoher way to make the query to my column, i dont kwnow if it works
Future<List<todo>> cattic() async {
final db = await initializeDB();
List<String> columnCategoria = ['categoria'];
final List<Map<String, dynamic>> queryResult = await db.query('todos',
columns: columnCategoria, //selecciona columna, en este caso = categoria
where: 'categoria = ?', //donde categoria sea "TIC");
whereArgs: ['TIC']);
return queryResult.map((e) => todo.fromMap(e)).toList();
}
}
这是我的班级屏幕,我应该在其中查看列查询中的列表,但没有显示任何内容:
import 'package:cursin/model/user_model.dart';
import 'package:cursin/screens/course_detail.dart';
import 'package:cursin/screens/dbhelper.dart';
import 'package:cursin/screens/lista_model.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:share_plus/share_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
class categorias extends StatefulWidget {
categorias({required this.cat});
late String cat;
@override
_categoriasState createState() => _categoriasState();
}
class _categoriasState extends State<categorias> {
late DatabaseHandler handler;
Future<List<todo>>? _todo;
@override
void initState() {
switch (widget.cat) {
case "TIC":
{
handler = DatabaseHandler();
handler.initializeDB().whenComplete(() async {
setState(() async {
_todo = (await handler.queryCat()) as Future<List<todo>>;
});
});
}
break;
}
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[850],
appBar: AppBar(
title: Text(
"Welcome "
),
),
body: FutureBuilder<List<todo>>(
future: _todo,
builder: (BuildContext context, AsyncSnapshot<List<todo>> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: const CircularProgressIndicator(),
);
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
var items = snapshot.data ?? <todo>[];
return Container(
margin: EdgeInsets.symmetric(
horizontal: 5.0,
vertical: 5.0,
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
),
child: ListView.builder(
itemCount: items.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CourseDetail(td: items[index]),
),
);
},
child: Column(
children: [
Padding(
child: Container(
child: ListTile(
leading: SizedBox(
height: 100.0,
width: 80.0,
child: Image.network(items[index].imgcourse),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
title: Text(
items[index].title,
style: TextStyle(
fontSize: 23,
color: Colors.blueAccent,
),
),
)),
)
],
),
);
},
),
);
}
},
),
);
}
}
I am a beginner in flutter. I created a method where I do a select of a specific column from my 'todos' table, so I want to receive that query in a list type 'todos'.
But when I call it, this does not appear on the screen. What am I doing wrong?
Evidence:
this is my database helper:
import 'dart:developer';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'lista_model.dart';
class DatabaseHandler {
Future<Database> initializeDB() async {
String path = await getDatabasesPath();
return openDatabase(
join(path, 'courses.db'),
onCreate: (database, version) async {
final String sql = ''
'CREATE TABLE todos ('
' id INTEGER PRIMARY KEY AUTOINCREMENT,'
' title TEXT,'
' entidad TEXT,'
' categoria TEXT,'
' emision TEXT,'
' imgcourse TEXT,'
' urlcourse TEXT,'
' description TEXT'
')';
await database.execute(sql);
final String addCourse = ''
'INSERT INTO todos(title, entidad, categoria, emision, imgcourse, urlcourse, description) VALUES ('
'"Control" , "Slim", "TIC", "Certificable", "https://dinahosting.com", "https://aprende.org/", "+Entu formación académica y profesional."),'
'("Transparencia" , "Defensoría", "Ciencias", "Certificable", "https://www.notinetlegal.com", "https://campusvirtual", "+El accesopara tu formación académica y profesional.")'
;
await database.execute(addCourse);
},
version: 1,
);
}
//this is the method where i make the column select query and it works fine
Future<List<Map>> queryCat() async {
Database db = await initializeDB();
db.rawQuery('SELECT categorias FROM todos WHERE categoria="TIC"');
List<Map> result =
await db.rawQuery('SELECT * FROM todos WHERE categoria=?', ['TIC']);
// print the results
result.forEach((row) => print(row));
return result;
}
//method to make all query
Future<List<todo>> todos() async {
final db = await initializeDB();
final List<Map<String, dynamic>> queryResult = await db.query('todos');
return queryResult.map((e) => todo.fromMap(e)).toList();
}
//this method was antoher way to make the query to my column, i dont kwnow if it works
Future<List<todo>> cattic() async {
final db = await initializeDB();
List<String> columnCategoria = ['categoria'];
final List<Map<String, dynamic>> queryResult = await db.query('todos',
columns: columnCategoria, //selecciona columna, en este caso = categoria
where: 'categoria = ?', //donde categoria sea "TIC");
whereArgs: ['TIC']);
return queryResult.map((e) => todo.fromMap(e)).toList();
}
}
and this is my class screen where i should view the list from the column query, but nothing is showed:
import 'package:cursin/model/user_model.dart';
import 'package:cursin/screens/course_detail.dart';
import 'package:cursin/screens/dbhelper.dart';
import 'package:cursin/screens/lista_model.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:share_plus/share_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
class categorias extends StatefulWidget {
categorias({required this.cat});
late String cat;
@override
_categoriasState createState() => _categoriasState();
}
class _categoriasState extends State<categorias> {
late DatabaseHandler handler;
Future<List<todo>>? _todo;
@override
void initState() {
switch (widget.cat) {
case "TIC":
{
handler = DatabaseHandler();
handler.initializeDB().whenComplete(() async {
setState(() async {
_todo = (await handler.queryCat()) as Future<List<todo>>;
});
});
}
break;
}
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[850],
appBar: AppBar(
title: Text(
"Welcome "
),
),
body: FutureBuilder<List<todo>>(
future: _todo,
builder: (BuildContext context, AsyncSnapshot<List<todo>> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: const CircularProgressIndicator(),
);
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
var items = snapshot.data ?? <todo>[];
return Container(
margin: EdgeInsets.symmetric(
horizontal: 5.0,
vertical: 5.0,
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
),
child: ListView.builder(
itemCount: items.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CourseDetail(td: items[index]),
),
);
},
child: Column(
children: [
Padding(
child: Container(
child: ListTile(
leading: SizedBox(
height: 100.0,
width: 80.0,
child: Image.network(items[index].imgcourse),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
title: Text(
items[index].title,
style: TextStyle(
fontSize: 23,
color: Colors.blueAccent,
),
),
)),
)
],
),
);
},
),
);
}
},
),
);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论