Flutter Data - splimter/Flutter GitHub Wiki
sqflite
SQLite plugin for Flutter. Supports both iOS and Android.
path_provider
A Flutter plugin for finding commonly used locations on the filesystem. Supports iOS and Android.
http
A composable, Future-based library for making HTTP requests.
dependencies:
sqflite: ^1.1.3
path_provider: ^0.5.0
http: ^0.12.0+1
Not Finished ;(
Not Finished ;(
Not Finished ;(
Wraps NSUserDefaults (on iOS) and SharedPreferences (on Android), providing a persistent store for simple data.
Add the dependencies: shared_preferences: ^0.5.1+2
.
Import: import 'package:shared_preferences/shared_preferences.dart';
SharedPreferences sharedPreferences;
save() async {
sharedPreferences = await SharedPreferences.getInstance();
setState(() {
sharedPreferences.set<Type>(<key>, <TextEditingController>.text);
});
}
load() async {
sharedPreferences = await SharedPreferences.getInstance();
setState(() {
<TextEditingController>.text = sharedPreferences.getString(<key>);
});
}
- Use a
TextEditingController
variable to get the input fromTextField
. - Use the
controller
atribute to assing that varibale.
Checkout this exemple.
Sarting by define our database, check the Helper file:
note: CM will be the class object that you want to add into your DB e.g: Note ...
CM class should use private properties:
class CM {
int _id;
<Type> _<prop>;
// Ctor
CM(this._<prop>);
CM.withId(this._id, this.<prop>);
//Getters
int get id => _id;
String get <prop> => _<prop>;
//Setters
set <prop>(<Type> <arg>) {
this.<prop> = <arg>;
}
// Convert a CM object into a Map object
Map<String, dynamic> toMap() {
var map = Map<String, dynamic>();
if (id != null) {
map['id'] = _id;
}
map['<prop>'] = _<prop>;
return map;
}
// Extract a CM object from a Map object
CM.fromMapObject(Map<String, dynamic> map) {
this._id = map['id'];
this._<prop> = map['<prop>'];
}
}
Not Finished ;(
Not Finished ;(
Not Finished ;(
- Goto Firebase make a project, enable
test mode
. - In Database make a Collection sample.
- In Project Overview, Add Firebase to your Android app.
In you working dir goto
android\app\src\main\AndroidManifest.xml
file, then copy the package name and use it in Andoid Package Name. - Download the config file and palce it in
android\app
. - Follow the instruction.
- In Project Overview, Add Firebase to your IOS app.
In you working dir goto
android\app\src\main\AndroidManifest.xml
file, then copy the package name and use it in Andoid Package Name. - Download the config file and palce it in
ios\runner
. - Skip all
- goto
pubspec.yaml
file and addcloud_firestore: ^0.9.13+1
under dependencies.
In order to use the firebase in your app add the import 'package:cloud_firestore/cloud_firestore.dart';
.
To be able to do the CRUD on your database, you need to make a variable that will control it.
DocumentReference documentReference = Firestore.instance.collection("<collection-name>").document('document-name');
- Create
Map<String, dynamic> <var> = {
<feild_name>: <val>,
};
documentReference.setData(<var>); //silent
documentReference.setData(<var>).whenComplete((){
<todo_when_created>;
});
- Read
documentReference.get().then((datasnapshot){
datasnapshot.data[<feild_name>]; //value of <feild_name>
});
- Update
//same as Create
- Delete
documentReference.delete(); //silent
documentReference.delete().whenComplete((){
<todo_when_deleted>;
});
Snippet that show all db documents:
StreamBuilder(
stream: Firestore.instance.collection("<collection_name>").snapshots(),
builder: (context, snapshot) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.documents.length,
itemBuilder: (context, i) {
DocumentSnapshot ds = snapshot.data.documents[i];
return Row(
children: <Widget>[
Expanded(
child: Text(ds["<feild_name>"].toString()),
),
],
);
},
);
},
),
Checkout this exemple.
Setup download function:
Future<File> _downloadFile(String url, String filename) async {
var request = await httpClient.getUrl(Uri.parse(url));
var response = await request.close();
var bytes = await consolidateHttpClientResponseBytes(response);
String dir = (await getApplicationDocumentsDirectory()).path;
File file = new File('/storage/emulated/0/Download/$filename');
await file.writeAsBytes(bytes);
return file;
}
Call the download function:
_downloadFile('<url>','<filename>');
in pubspec.yaml add the json file under the assert (in this example the file is under data/msg.json )
var messages = const [];
Future setMessages() async {
var content = await rootBundle.loadString('data/msg.json');
var collection = json.decode(content);
setState(() {
messages = collection;
});
}
void initState(){
setMessages();
super.initState();
}
in pubspec.yaml under dev_dependencies
add http: ^0.12.0+2
.
You can get the json using http request
//To Change
http.Response response =
await http.get("http://www.mocky.io/v2/5d543d652f00002b008614f0");
String content = response.body;
note: You can use mocky for testing purpose.
It provides Dart Build System builders for handling JSON, The builders generate code when they find members annotated with classes defined in package:json_annotation
.
in pubspec.yaml add:
dependencies:
json_annotation: ^2.0.0
dev_dependencies:
build_runner: ^1.0.0
json_serializable: ^2.0.0
Make a Model for json data:
import 'package:json_annotation/json_annotation.dart';
part 'message.g.dart';
@JsonSerializable()
class Message{
final String title;
final String body;
Message(this.title, this.body);
factory Message.fromJson(Map<String, dynamic> json) =>
_$MessageFromJson(json);
}
Run flutter pub run build_runner build
.
Do some modification in previous code:
//To Add
List<Message> _msg = collection.map((json)=>Message.fromJson(json)).toList();
//To Change
setState(() {
messages = _msg;
});
- set schema:
type Person {
id: String!
name: String!
lastName: String!
age: String!
}
type Query {
allPersons: [Person!]
}
- add dependancies
graphql_flutter: ^3.0.0
http: ^0.12.0+4
- Get this example.
code explanation:
- Set the Class that is compatible with the schema.
- Set the queries in QueryMutation class, you can run examples on the dashboard to make sure that you have a correct syntax.