我有一个SQLite数据库,其中有一列包含Blob。
我尝试访问并显示此BLOB,但可惜没有成功。
这是我尝试过的:
Image.memory(Uint8List.view(myList[counterInt]['ItemImageBLOB'])),
我也尝试过
Image.memory(Uint8List(myList[counterInt]['ItemImageBLOB'])),
我收到的错误是:
type '_Uint8ArrayView' is not a subtype of type 'ByteBuffer'
答案 0 :(得分:1)
如果您在下面也关注我的情况
直接使用以下
Image.memory(myList[counteInt]['ItemImageBLOB'])
在我的示例中,我进行了硬编码并将此https://upload.wikimedia.org/wikipedia/commons/7/70/Example.png保存到sqlite BLOB字段
显示picutre
Image.memory(snapshot.data[index].pict)
创建sqlite表时,您的字段类型必须为BLOB
await db.execute(
"CREATE TABLE Employee(id INTEGER PRIMARY KEY, firstname TEXT, lastname TEXT, mobileno TEXT,emailId TEXT, pict BLOB )");
在您的班级中,pict字段必须为Uint8List
班级员工{
String firstName;
String lastName;
String mobileNo;
String emailId;
Uint8List pict;
Employee(this.firstName, this.lastName,this.mobileNo,this.emailId, this.pict);
Employee.fromMap(Map map) {
firstName = map[firstName];
lastName = map[lastName];
mobileNo = map[mobileNo];
emailId = map[emailId];
pict = map[pict];
}
Map<String, dynamic> toMap() => {
"firstName": firstName,
"lastName": lastName,
"mobileNo" : mobileNo,
"emailId" : emailId,
"pict": pict,
};
}
演示执行
完整的工作代码
main.dart
import 'package:flutter/material.dart';
import 'package:so_sqlite/database/dbhelper.dart';
import 'package:so_sqlite/model/employee.dart';
import 'package:so_sqlite/employeelist.dart';
import 'package:http/http.dart' show get;
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'SQFLite DataBase Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Employee employee = new Employee("", "", "", "", null);
String firstname;
String lastname;
String emailId;
String mobileno;
final scaffoldKey = new GlobalKey<ScaffoldState>();
final formKey = new GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return new Scaffold(
key: scaffoldKey,
appBar: new AppBar(title: new Text('Saving Employee'), actions: <Widget>[
new IconButton(
icon: const Icon(Icons.view_list),
tooltip: 'Next choice',
onPressed: () {
navigateToEmployeeList();
},
),
]),
body: SingleChildScrollView(
child: new Padding(
padding: const EdgeInsets.all(16.0),
child: new Form(
key: formKey,
child: new Column(
children: [
new TextFormField(
keyboardType: TextInputType.text,
decoration: new InputDecoration(labelText: 'First Name'),
validator: (val) => val.length == 0 ? "Enter FirstName" : null,
onSaved: (val) => this.firstname = val,
),
new TextFormField(
keyboardType: TextInputType.text,
decoration: new InputDecoration(labelText: 'Last Name'),
validator: (val) => val.length == 0 ? 'Enter LastName' : null,
onSaved: (val) => this.lastname = val,
),
new TextFormField(
keyboardType: TextInputType.phone,
decoration: new InputDecoration(labelText: 'Mobile No'),
validator: (val) => val.length == 0 ? 'Enter Mobile No' : null,
onSaved: (val) => this.mobileno = val,
),
new TextFormField(
keyboardType: TextInputType.emailAddress,
decoration: new InputDecoration(labelText: 'Email Id'),
validator: (val) => val.length == 0 ? 'Enter Email Id' : null,
onSaved: (val) => this.emailId = val,
),
new Container(
margin: const EdgeInsets.only(top: 10.0),
child: new RaisedButton(
onPressed: _submit,
child: new Text('Save'),
),
)
],
),
),
),
),
);
}
void _submit() async {
if (this.formKey.currentState.validate()) {
formKey.currentState.save();
} else {
return null;
}
var response = await get(
"https://upload.wikimedia.org/wikipedia/commons/7/70/Example.png");
var bytesFromPict = response.bodyBytes;
print("bytes : ${bytesFromPict}");
var employee =
Employee(firstname, lastname, mobileno, emailId, bytesFromPict);
var dbHelper = DBHelper();
dbHelper.saveEmployee(employee);
_showSnackBar("Data saved successfully");
}
void _showSnackBar(String text) {
scaffoldKey.currentState
.showSnackBar(new SnackBar(content: new Text(text)));
}
void navigateToEmployeeList() {
Navigator.push(
context,
new MaterialPageRoute(builder: (context) => new MyEmployeeList()),
);
}
}
employeelist.dart
import 'package:flutter/material.dart';
import 'package:so_sqlite/model/employee.dart';
import 'dart:async';
import 'package:so_sqlite/database/dbhelper.dart';
Future<List<Employee>> fetchEmployeesFromDatabase() async {
var dbHelper = DBHelper();
Future<List<Employee>> employees = dbHelper.getEmployees();
return employees;
}
class MyEmployeeList extends StatefulWidget {
@override
MyEmployeeListPageState createState() => new MyEmployeeListPageState();
}
class MyEmployeeListPageState extends State<MyEmployeeList> {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Employee List'),
),
body: new Container(
padding: new EdgeInsets.all(16.0),
child: new FutureBuilder<List<Employee>>(
future: fetchEmployeesFromDatabase(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return new ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Text(snapshot.data[index].firstName,
style: new TextStyle(
fontWeight: FontWeight.bold, fontSize: 18.0)),
new Text(snapshot.data[index].lastName,
style: new TextStyle(
fontWeight: FontWeight.bold, fontSize: 14.0)),
Image.memory(snapshot.data[index].pict),
new Divider()
]);
});
} else if (snapshot.hasError) {
return new Text("${snapshot.error}");
}
return new Container(alignment: AlignmentDirectional.center,child: new CircularProgressIndicator(),);
},
),
),
);
}
}
model \ employee.dart
import 'dart:math';
import 'dart:typed_data';
class Employee{
String firstName;
String lastName;
String mobileNo;
String emailId;
Uint8List pict;
Employee(this.firstName, this.lastName,this.mobileNo,this.emailId, this.pict);
Employee.fromMap(Map map) {
firstName = map[firstName];
lastName = map[lastName];
mobileNo = map[mobileNo];
emailId = map[emailId];
pict = map[pict];
}
Map<String, dynamic> toMap() => {
"firstName": firstName,
"lastName": lastName,
"mobileNo" : mobileNo,
"emailId" : emailId,
"pict": pict,
};
}
database \ dbhelper.dart
import 'dart:async';
import 'dart:io' as io;
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:so_sqlite/model/employee.dart';
class DBHelper {
static Database _db;
Future<Database> get db async {
if (_db != null) return _db;
_db = await initDb();
return _db;
}
initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "test1.db");
var theDb = await openDatabase(path, version: 1, onCreate: _onCreate);
return theDb;
}
void _onCreate(Database db, int version) async {
// When creating the db, create the table
await db.execute(
"CREATE TABLE Employee(id INTEGER PRIMARY KEY, firstname TEXT, lastname TEXT, mobileno TEXT,emailId TEXT, pict BLOB )");
print("Created tables");
}
void saveEmployee(Employee employee) async {
var dbClient = await db;
await dbClient.insert("Employee", employee.toMap());
/*await dbClient.transaction((txn) async {
return await txn.rawInsert(
'INSERT INTO Employee(firstname, lastname, mobileno, emailid, pict ) VALUES(' +
'\'' +
employee.firstName +
'\'' +
',' +
'\'' +
employee.lastName +
'\'' +
',' +
'\'' +
employee.mobileNo +
'\'' +
',' +
'\'' +
employee.emailId +
'\'' +
employee.pict +
'\'' +
')');
});*/
}
Future<List<Employee>> getEmployees() async {
var dbClient = await db;
List<Map> list = await dbClient.rawQuery('SELECT * FROM Employee');
List<Employee> employees = new List();
for (int i = 0; i < list.length; i++) {
employees.add(new Employee(list[i]["firstname"], list[i]["lastname"], list[i]["mobileno"], list[i]["emailid"], list[i]["pict"]));
}
print(employees.length);
return employees;
}
}