How do I access separate children from Firebase database in Flutter? - database

Hi I am currently trying to access a child of my database in Flutter so that I can link it to another child. I am able to pull the data from one child, but unable to link this data with my other child. I want to be able to access a field of the 'Record' child and link to the 'Volunteer' child using the "volunteer" field but am unable to get them to link together. Any help would be appreciated!
The database structure is as follows:
This is the code for My Volunteer class:
class Volunteer {
String volunteerID;
String name;
String role;
Volunteer(this.volunteerID, this.name, this.role);
Volunteer.fromSnapshot(DataSnapshot snapshot)
: volunteerID = snapshot.key,
name = snapshot.value["name"],
role = snapshot.value["role"];
toJson() {
return {
"key": volunteerID,
"name": name,
"role": role
};
}
}
And this is the code for my UI:
class SignInPageState extends State<SignInPage> {
List<Volunteer> volunteers;
Volunteer volunteer;
DatabaseReference dbRef;
DatabaseReference volunteerRef;
DatabaseReference recordRef;
#override
void initState() {
super.initState();
volunteers = new List();
volunteer = Volunteer("","", "");
final FirebaseDatabase database = FirebaseDatabase.instance;
dbRef = database.reference();
volunteerRef = database.reference().child('volunteer');
recordRef = database.reference().child('record');
dbRef.onChildAdded.listen(_onEntryAdded);
dbRef.onChildChanged.listen(_onEntryChanged);
volunteerRef.once().then((DataSnapshot snapshot) {
Map<dynamic, dynamic> getMap = snapshot.value;
getMap.forEach((key, values) {
String volunteerRecord = recordRef.child('volunteer').toString();
if (volunteerRecord == volunteer.volunteerID){
volunteer.role = volunteerRecord;
}
volunteers.add(volunteer);
});
});
}
_onEntryAdded(Event event) {
setState(() {
volunteers.add(Volunteer.fromSnapshot(event.snapshot));
});
}
_onEntryChanged(Event event) {
var old = volunteers.singleWhere((entry) {
return entry.volunteerID == event.snapshot.key;
});
setState(() {
volunteers[volunteers.indexOf(old)] = Volunteer.fromSnapshot(event.snapshot);
});
}
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Container(
padding: EdgeInsets.all(10.0),
color: Colors.white,
child: Column(
children: <Widget>[
Expanded(
flex: 8,
child: Container(
child: FirebaseAnimatedList(
query: volunteerRef,
itemBuilder: (BuildContext context, DataSnapshot snapshot,
Animation<double> animation, int index) {
return new ListTile(
title: Text(
(volunteers[index].name + " " + volunteers[index].role),
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontWeight: FontWeight.bold ,color: Color.fromRGBO(139, 195, 68, 1)),
),
onTap: () {
SuccessSignInPage(volunteers[index].name);
},
);
},
),
)
),
],
)),
),
);
}
void Back() async {
await Navigator.of(context).pop();
}
void SuccessSignInPage(String name) async {
var route = new MaterialPageRoute(
builder: (BuildContext context) => new SignInSuccessPage(value: name));
await Navigator.of(context).push(route);
}
}

Related

How would I show my posts from my firestore?

Okay so my profile posts are working as intended right here, I am showing the users posts that only they have made to their very own profile
Now here is the code doing that
static Future<List<Post>> getUserPosts(String currentUserId) async {
QuerySnapshot userPostsSnap = await postsRef
.doc(currentUserId)
.collection('userPosts')
.orderBy('timestamp', descending: true)
.get();
List<Post> userPosts =
userPostsSnap.docs.map((doc) => Post.fromDoc(doc)).toList();
return userPosts;
}
and also to show them to the profile page as you see in the image:
showProfilePosts(UserModel author) {
return Expanded(
child: ListView.builder(
shrinkWrap: true,
physics: AlwaysScrollableScrollPhysics(),
itemCount: _allPosts.length,
itemBuilder: (context, index) {
return PostContainer(
post: _allPosts[index],
author: author,
currentUserId: widget.currentUserId,
);
}),
);
}
getAllPosts() async {
List<Post> userPosts =
await DatabaseMethods.getUserPosts(widget.visitedUserId);
if (mounted) {
setState(() {
_allPosts = userPosts;
});
}
}
#override
void initState() {
super.initState();
getAllPosts();
}
now my goal is to show every single post made by every user (I'm creating one big forum) so how can I show every single post made by everyone in the database to my home screen? My database also looks like this for some visuals, would I have to loop through?
here is my Home screen's code, where I wish to display every users posts
class HomeScreen extends StatefulWidget {
final String currentUserId;
const HomeScreen({Key? key, required this.currentUserId}) : super(key: key);
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
List _homeScreenPosts = [];
bool _loading = false;
buildHomeScreenPosts(Post post, UserModel author) {
return PostContainer(
post: post,
author: author,
currentUserId: widget.currentUserId,
);
}
showHomeScreenPosts(String currentUserId) {
List<Widget> homePostsList = [];
for (Post post in _homeScreenPosts) {
homePostsList.add(
FutureBuilder(
future: usersRef.doc(post.authorId).get(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
UserModel author = UserModel.fromSnap(snapshot.data);
return buildHomeScreenPosts(post, author);
} else {
return SizedBox.shrink();
}
},
),
);
}
return homePostsList;
}
setupHomeScreenPosts() async {
setState(() {
_loading = true;
});
List homeScreenPosts =
await DatabaseMethods.getHomeScreenPosts(widget.currentUserId);
if (mounted) {
setState(() {
_homeScreenPosts = homeScreenPosts;
_loading = false;
});
}
}
#override
void initState() {
super.initState();
setupHomeScreenPosts();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: [
IconButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SearchScreen(
currentUserId: widget.currentUserId,
),
),
);
},
icon: Icon(Icons.search),
),
],
automaticallyImplyLeading: false,
title: Text('Home'),
centerTitle: true,
),
body: RefreshIndicator(
onRefresh: () => setupHomeScreenPosts(),
child: ListView(
physics: BouncingScrollPhysics(
parent: AlwaysScrollableScrollPhysics(),
),
children: [
_loading ? LinearProgressIndicator() : SizedBox.shrink(),
SizedBox(height: 5),
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(height: 5),
Column(
children: _homeScreenPosts.isEmpty && _loading == false
? [
SizedBox(height: 5),
Padding(
padding: EdgeInsets.symmetric(horizontal: 25),
child: Text(
'There is No New posts',
style: TextStyle(
fontSize: 20,
),
),
),
]
: showHomeScreenPosts(widget.currentUserId),
),
],
)
],
),
),
);
}
}
Firebase does not have the a concept of "tables" the way relational/sql databases do. I.e. there is not a built-in method to access all documents labelled as a "post".
Because of this, you'll need to access each post through each of the user documents.
Assuming you have a List of all of your user Id's called allUserIds, then you can do something like the following:
List<Post> allPostsForAllUsers = [];
allUserIds.forEach((id) {
allPostsForAllUsers.addAll(await getUserPosts(id));
}
Okay so I figured it out myself, all I had to do was call the collectionGroup 'userPosts' like so
static Future<List<Post>> getHomeScreenPosts(String currentUserId) async {
QuerySnapshot homePostsSnap = await FirebaseFirestore.instance
.collectionGroup('userPosts')
.orderBy('timestamp', descending: true)
.get();
List<Post> homeScreenPosts =
homePostsSnap.docs.map((doc) => Post.fromDoc(doc)).toList();
return homeScreenPosts;
}

The argument type 'Object?' can't be assigned to the parameter type 'List<Destination>'

class Destination {
final double lat;
final double lng;
final String name;
final double distance;
const Destination({
required this.lat,
required this.lng,
required this.name,
required this.distance,
});
factory Destination.fromJson(Map<String, dynamic> json) {
return Destination(
lat: json['lat'] as double,
lng: json['lng'] as double,
name: json['name'] as String,
distance: json['distance'] as double,
);
}
}
here is the error
return listViewWidget(List<Destination>.from(snapshot.data));
this my code :
import 'package:flutter/material.dart';
import 'package:flutter_sorting_location/model.dart';
import 'package:geolocator/geolocator.dart';
import 'package:flutter_sorting_location/Utils.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
double? distance;
List<Destination> destinations = [];
Position? _currentPosition;
List<Destination> destinationlist = [];
Future<List<Destination>> getData() async {
var url = 'http://xxxxxxxxxxxxxx/flutter/getlocation.php';
var res =
await http.get(Uri.parse(url), headers: {"Accept": "application/json"});
print(res.body);
if (res.statusCode == 200) {
var data = json.decode(res.body);
var rest = data["articles"] as List;
print(rest);
destinations =
rest.map<Destination>((json) => Destination.fromJson(json)).toList();
}
print("List Size: ${destinations.length}");
return destinations;
}
#override
void initState() {
_getCurrentLocation();
super.initState();
}
Widget listViewWidget(List<Destination> article) {
return Container(
child: ListView.builder(
itemCount: 20,
padding: const EdgeInsets.all(2.0),
itemBuilder: (context, position) {
return Card(
child: ListTile(
title: Text(
'${article[position].name}',
style: TextStyle(
fontSize: 18.0,
color: Colors.black,
fontWeight: FontWeight.bold),
),
leading: Padding(
padding: const EdgeInsets.all(8.0),
child: SizedBox(
child: article[position].name == null
? Image(
image: AssetImage('images/no_image_available.png'),
)
: Image.network('${article[position].name}'),
height: 100.0,
width: 100.0,
),
),
),
);
}),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Location sorting from current location"),
),
body: FutureBuilder(
future: getData(),
builder: (context, snapshot) {
if (snapshot.data != null) {
return listViewWidget(List<Destination>.from(snapshot.data));
} else {
return Center(child: CircularProgressIndicator());
}
}),
);
}
// get Current Location
_getCurrentLocation() {
Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best,
forceAndroidLocationManager: true)
.then((Position position) {
distanceCalculation(position);
setState(() {
_currentPosition = position;
});
}).catchError((e) {
print(e);
});
}
distanceCalculation(Position position) {
for (var d in destinations) {
var km = getDistanceFromLatLonInKm(
position.latitude, position.longitude, d.lat, d.lng);
// var m = Geolocator.distanceBetween(position.latitude,position.longitude, d.lat,d.lng);
// d.distance = m/1000;
//d.distance = km;
destinationlist.add(d);
// print(getDistanceFromLatLonInKm(position.latitude,position.longitude, d.lat,d.lng));
}
setState(() {
destinationlist.sort((a, b) {
// print("a : ${a.distance} b : ${b.distance}");
return a.distance.compareTo(b.distance);
});
});
}
}
this what i found:
getData() is async function. Future<List<Destination>> which is return list of Object not Map or json anymore
so when you call that function here :
body: FutureBuilder(
future: getData(),
builder: (context, snapshot) {
snapshot is List<Destination> , then no need to convert to list anymore.
just like below
return listViewWidget(snapshot);
then on your listViewWidget method , changes this :
title: Text('${article.position.name}',) // no need brackets

I am creating note app in flutter and stuck in sqflite, how can I pass my title and body to insert method

I am building a simple note app, but I am stuck at saving the data (title and body) using SQLite.
DataBaseHelper class
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'model_notes.dart';
class DatabaseHelper {
static final _databaseName = "myNote.db";
static final _databaseVersion = 1;
static final table = 'notes_table';
static final columnId = 'id';
static final columnTitle = 'title';
static final columnBody = 'body';
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
static Database _database;
Future<Database> get database async {
if (_database != null) return _database;
_database = await _initDatabase();
return _database;
}
_initDatabase() async {
String path = join(await getDatabasesPath(), _databaseName);
return await openDatabase(path,
version: _databaseVersion,
onCreate: _onCreate);
}
Future _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE $table (
$columnId INTEGER PRIMARY KEY AUTOINCREMENT,
$columnTitle TEXT NOT NULL,
$columnBody TEXT NOT NULL
)
''');
}
Future<int> insert(Note note) async {
Database db = await instance.database;
return await db.insert(table, {'title': note.title, 'body': note.body});
}
This is the Model Class for Notes
import 'db_operations.dart';
class Note {
int id;
String title;
String body;
Note(this.id, this.title, this.body);
Note.fromMap(Map<String, dynamic> map) {
id = map['id'];
title = map['title'];
body = map['body'];
}
Map<String, dynamic> toMap(){
return {
DatabaseHelper.columnId : id,
DatabaseHelper.columnTitle : title,
DatabaseHelper.columnBody : body
};
}
}
and this is where I'm calling insert method (class name = adding_notes.dart)
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:note_taking_app/constants/buttons_and_icons_misc(classes).dart';
import 'package:note_taking_app/db/db_operations.dart';
import 'package:note_taking_app/db/model_notes.dart';
import 'package:sqflite/sqflite.dart';
import 'main_screen.dart';
final bodyController = TextEditingController();
final headerController = TextEditingController();
final dbHelper = DatabaseHelper.instance;
class AddingNotes extends StatefulWidget {
#override
_AddingNotesState createState() => _AddingNotesState();
}
class _AddingNotesState extends State<AddingNotes> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
backwardsCompatibility: true,
leading: LeadingIcon(
callBack: () {
Navigator.pop(context);
},
),
backgroundColor: Colors.white.withOpacity(0.4),
actions: <Widget>[
ActionsIconButton(
icon: Icon(undo, color: black),
callBack: () {
debugPrint('undo tapped');
},
),
ActionsIconButton(
icon: Icon(redo, color: black),
callBack: () {
debugPrint('redo tapped');
},
),
ActionsIconButton(
icon: Icon(save, color: black),
callBack: () async {
debugPrint(bodyController.text);
debugPrint(headerController.text);
getHeaderDataToMainScreen(context);
String title = headerController.text;
String body = bodyController.text;
/*This is where I am calling insert method*/
dbHelper.insert(title, body);
},
)
],
),
body: Container(
color: Colors.white.withOpacity(0.4),
child: Padding(
padding: const EdgeInsets.all(13.0),
child: Column(
children: [
HeaderBody(
textEditingController: headerController,
),
SizedBox(
height: 32.0,
),
Expanded(
child: NotesBody(
textEditingController: bodyController,
),
),
],
),
),
),
);
}
}
getHeaderDataToMainScreen(BuildContext context){
Navigator.push(context,
MaterialPageRoute(
builder: (context) => MainScreen(
heading : headerController.text,
)
)
);
}
It is showing too many positional arguments expected 1 found 2. I know I need to send 1 argument, but how can I send both title and body as 1 argument. Maybe through List I can send it but I don't know how to do that. Any help here guys, I'm stuck at this for the past 5 days.
Check the example below that i have created based on the code you provided.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'db_operations.dart';
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: AddingNotes(),
));
}
final bodyController = TextEditingController();
final headerController = TextEditingController();
final dbHelper = DatabaseHelper.instance;
class AddingNotes extends StatefulWidget {
#override
_AddingNotesState createState() => _AddingNotesState();
}
class _AddingNotesState extends State<AddingNotes> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
leading: GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Icon(
Icons.add,
color: Colors.black,
),
),
),
backgroundColor: Colors.white.withOpacity(0.4),
actions: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () {
debugPrint('undo tapped');
},
child: Icon(
Icons.undo,
color: Colors.black,
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () {
debugPrint('redo tapped');
},
child: Icon(
Icons.redo,
color: Colors.black,
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () async {
debugPrint(bodyController.text);
debugPrint(headerController.text);
//getHeaderDataToMainScreen(context);
String title = headerController.text;
String body = bodyController.text;
Note note = Note(20, title, body);
var value = await dbHelper.insert(note);
print("if 1 is return then insert success and 0 then not inserted : $value");
},
child: Icon(
Icons.save,
color: Colors.black,
),
),
)
],
),
body: Container(
color: Colors.white.withOpacity(0.4),
child: Padding(
padding: const EdgeInsets.all(13.0),
child: Column(
children: [
TextField(
controller: headerController,
),
SizedBox(
height: 32.0,
),
Expanded(
child: TextField(
controller: bodyController,
),
),
],
),
),
),
);
}
}
// getHeaderDataToMainScreen(BuildContext context) {
// Navigator.push(context,
// MaterialPageRoute(
// builder: (context) =>
// MainScreen(
// heading: headerController.text,
// )
// )
// );
// }
class Note {
int id;
String title;
String body;
Note(this.id, this.title, this.body);
Note.fromMap(Map<String, dynamic> map) {
id = map['id'];
title = map['title'];
body = map['body'];
}
Map<String, dynamic> toMap() {
return {
DatabaseHelper.columnId: id,
DatabaseHelper.columnTitle: title,
DatabaseHelper.columnBody: body
};
}
}
This is just a sample demo example added every thing in one file and made many changes. change it as per your needs.
You don't need a auto increment id as you have given it in the database. Run the app and let me know if it works.

How to hide a floatingActionButton after insert data flutter?

I use sqflite for flutter database management. In particular, I would like the user to enter the data only once and therefore I would need to hide and disable the button only once the data has been entered. How can I do?
Home Page, where is the button
class Casa extends StatefulWidget {
static const routeName = '/';
#override
_CasaState createState() => _CasaState();
}
class _CasaState extends State<Casa> {
DataRepository _repository;
#override
void initState() {
super.initState();
_repository = SqlRepository();
}
#override
void dispose() async {
await _repository.closeDB();
super.dispose();
}
void getNewItem(BuildContext context) async {
Attivita newItem =
await Navigator.pushNamed<Attivita>(context, AddItemScreen.routeName);
if (newItem != null) {
await _repository.add(newItem);
setState(() {});
}
}
void switchAndUpdate(Attivita item) async {
await _repository.put(item.id, item);
setState(() {});
}
void delete(Attivita item) async {
await _repository.delete(item.id);
setState(() {});
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: Colors.lightBlue[900],
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add, color: Colors.lightBlue[900],),
backgroundColor: Colors.white,
onPressed: () {
getNewItem(context);
},
),
body:
FutureBuilder<List<Attivita>>(
future: _repository.getAll(),
builder:
(BuildContext context, AsyncSnapshot<List<Attivita>> snapshot) {
return ListView.builder(
padding: EdgeInsets.all(8),
itemCount: snapshot.data == null ? 0 : snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return Dismissible(
key: UniqueKey(),
background: DecoratedBox(
decoration: BoxDecoration(color: Colors.red),
child: Align(
alignment: Alignment(-0.9, 00),
child: Icon(
Icons.delete,
color: Colors.white,
),
),
),
direction: DismissDirection.startToEnd,
onDismissed: (direction) {
Attivita item = snapshot.data[index];
snapshot.data.removeAt(index);
delete(item);
},
child: Card(
child: ListTile(
title: Text(snapshot.data[index].nome, style: TextStyle(color: Colors.lightBlue[900]),),
onTap: () {
Navigator.pushNamed(context, DettaglioScreen.routeName, arguments: snapshot.data[index]);
},
onLongPress: () {
switchAndUpdate(snapshot.data[index]);
},
),
),
);
},
);
},
)
),
);
}
}
so i have to add some details, because it is written that "it looks like your post is mostly code; please add some more details"
To check if user put so data you can use:
Use sharedPreferences and store bool value if user entered data.
On initState check if database contains data if yes it means user put some data and you can hide button.
I don't use Sqlite in flutter but I think you can use
List<Map<String, dynamic>> result;
result = await db.query(tableName);
isNotData = result.isEmpty;
Or something similar :) You can do it
Choose one way and store bool value eg. in bool isNotData
When you will have bool value about data you can write:
In _CasaState above initState: bool isNotData;
and in Scaffold in floatingActionButton property:
Scaffold(
appBar: AppBar(
title: Text('Material App Bar'),
),
floatingActionButton: isNotData
? FloatingActionButton(
onPressed: () {},
)
: null,
body: Center(
),
),
),

Flutter - Dynamic list with data coming from the database

I needed to create the DialogItem widgets using the data that comes from the database. I tried to use for(){} but it did not work.
Could you help me solve this problem?
I put the used code as well as the evidence that works, just does not work the dynamic list of DialogItem with the data of the database.
To work the code below, you need to insert the sqflite and path_provider dependencies into pubspec.yaml, thus:
dependencies:
sqflite: any
path_provider: any
flutter:
sdk: flutter
The DatabaseClient class will create the database with 3 records.
In the gif only foo1 appears the correct one would be to appear all the values of the list that came from the database:
[{name: foo1, color: 0}, {name: foo2, color: 1}, {name: foo3, color: 2}]
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
DatabaseClient _db = new DatabaseClient();
int number;
List listCategory;
List colors = [
const Color(0xFFFFA500),
const Color(0xFF279605),
const Color(0xFF005959)
];
createdb() async {
await _db.create().then(
(data){
_db.countCategory().then((list){
this.number = list[0][0]['COUNT(*)']; //3
this.listCategory = list[1];
//[{name: foo1, color: 0}, {name: foo2, color: 1}, {name: foo3, color: 2}]
});
}
);
}
#override
void initState() {
super.initState();
createdb();
}
void showCategoryDialog<T>({ BuildContext context, Widget child }) {
showDialog<T>(
context: context,
child: child,
)
.then<Null>((T value) {
if (value != null) {
setState(() { print(value); });
}
});
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(),
body: new Center(
child: new RaisedButton(
onPressed: (){
showCategoryDialog<String>(
context: context,
child: new SimpleDialog(
title: const Text('Categories'),
children: <Widget>[
//for(var i = 0; i < this.number; i++) {
new DialogItem(
icon: Icons.brightness_1,
color: this.colors[
this.listCategory[0]['color']
//the zero should be dynamic going from 0 to 2 with the for(){}
//but o for(){} dont work
],
text: this.listCategory[0]['name'],
onPressed: () {
Navigator.pop(context, this.listCategory[0]['name']);
}
),
//}
]
)
);
},
child: new Text("ListButton"),
)
),
);
}
}
//Creating Database with some data and two queries
class DatabaseClient {
Database db;
Future create() async {
Directory path = await getApplicationDocumentsDirectory();
String dbPath = join(path.path, "database.db");
db = await openDatabase(dbPath, version: 1, onCreate: this._create);
}
Future _create(Database db, int version) async {
await db.execute("""
CREATE TABLE category (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
color INTEGER NOT NULL
)""");
await db.rawInsert("INSERT INTO category (name, color) VALUES ('foo1', 0)");
await db.rawInsert("INSERT INTO category (name, color) VALUES ('foo2', 1)");
await db.rawInsert("INSERT INTO category (name, color) VALUES ('foo3', 2)");
}
Future countCategory() async {
Directory path = await getApplicationDocumentsDirectory();
String dbPath = join(path.path, "database.db");
Database db = await openDatabase(dbPath);
var count = await db.rawQuery("SELECT COUNT(*) FROM category");
List list = await db.rawQuery('SELECT name, color FROM category');
await db.close();
return [count, list];
}
}
//Class of Dialog Item
class DialogItem extends StatelessWidget {
DialogItem({
Key key,
this.icon,
this.size,
this.color,
this.text,
this.onPressed }) : super(key: key);
final IconData icon;
double size = 36.0;
final Color color;
final String text;
final VoidCallback onPressed;
#override
Widget build(BuildContext context) {
return new SimpleDialogOption(
onPressed: onPressed,
child: new Container(
child: new Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Container(
child: new Container(
margin: size == 16.0 ? new EdgeInsets.only(left: 7.0) : null,
child: new Icon(icon, size: size, color: color),
)
),
new Padding(
padding: size == 16.0 ?
const EdgeInsets.only(left: 17.0) :
const EdgeInsets.only(left: 16.0),
child: new Text(text),
),
],
),
)
);
}
}
There might be other issues, but as a start, I think this code
for(var i = 0; i < this.number; i++) {
...
}
should be changed to
children: this.number == null ? null :
new List(this.number).map((i) =>
new DialogItem(
icon: Icons.brightness_1,
color: this.colors[
this.listCategory[0]['color']
//the zero should be dynamic going from 0 to 2 with the for(){}
//but o for(){} dont work
],
text: this.listCategory[0]['name'],
onPressed: () {
Navigator.pop(context, this.listCategory[0]['name']);
}
).toList(),
to not throw an exception when this.number is null (response not yet received from the database).
and wrap the code that updates the state with setState(() {...})
createdb() async {
await _db.create().then(
(data){
_db.countCategory().then((list){
setState(() {
this.number = list[0][0]['COUNT(*)']; //3
this.listCategory = list[1];
//[{name: foo1, color: 0}, {name: foo2, color: 1}, {name: foo3, color: 2}]
});
});
}
);
}
I found the solution, according to the Flutter - Build Widgets dynamically and Flutter - Combine dynamically generated elements with hard-coded ones and in this question
As SimpleDialog only accepts a List of type Widget - <Widget>[] I declare a variable tiles of type List<Widget> - List<Widget> tiles; and created a function of type List<Widget> - List<Widget> buildTile(int counter) {... - to be able to return a List<Widget>
Because of Navigator.pop (context, ... I needed to create the buildTile() function inside the Widget build(BuildContext context) {...
In the buildTile() function I added a for() to insert into the Widget type list as many DialogItem Widgets were needed, according to the result that comes from the database
and wrap the code that updates the state with setState(() {...}) as explained by Günter Zöchbauer
setState(() {
this.number = list[0][0]['COUNT(*)']; //3
this.listCategory = list[1];
//[{name: foo1, color: 0}, {name: foo2, color: 1}, {name: foo3, color: 2}]
})
The complete code working as well as the demo are below:
To work the code below, you need to insert the sqflite and path_provider dependencies into pubspec.yaml, thus:
dependencies:
sqflite: any
path_provider: any
flutter:
sdk: flutter
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
DatabaseClient _db = new DatabaseClient();
int number;
List listCategory;
List<Widget> tiles;
List colors = [
const Color(0xFFFFA500),
const Color(0xFF279605),
const Color(0xFF005959)
];
createdb() async {
await _db.create().then(
(data){
_db.countCategory().then((list){
setState(() {
this.number = list[0][0]['COUNT(*)']; //3
this.listCategory = list[1];
//[{name: foo1, color: 0}, {name: foo2, color: 1}, {name: foo3, color: 2}]
});
});
}
);
}
#override
void initState() {
super.initState();
createdb();
}
void showCategoryDialog<T>({ BuildContext context, Widget child }) {
showDialog<T>(
context: context,
child: child,
)
.then<Null>((T value) {
if (value != null) {
setState(() { print(value); });
}
});
}
#override
Widget build(BuildContext context) {
List<Widget> buildTile(int counter) {
this.tiles = [];
for(var i = 0; i < counter; i++) {
this.tiles.add(
new DialogItem(
icon: Icons.brightness_1,
color: this.colors[
this.listCategory[i]['color']
],
text: this.listCategory[i]['name'],
onPressed: () {
Navigator.pop(context, this.listCategory[i]['name']);
}
)
);
}
return this.tiles;
}
return new Scaffold(
appBar: new AppBar(),
body: new Center(
child: new RaisedButton(
onPressed: (){
showCategoryDialog<String>(
context: context,
child: new SimpleDialog(
title: const Text('Categories'),
children: buildTile(this.number)
)
);
},
child: new Text("ListButton"),
)
),
);
}
}
//Creating Database with some data and two queries
class DatabaseClient {
Database db;
Future create() async {
Directory path = await getApplicationDocumentsDirectory();
String dbPath = join(path.path, "database.db");
db = await openDatabase(dbPath, version: 1, onCreate: this._create);
}
Future _create(Database db, int version) async {
await db.execute("""
CREATE TABLE category (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
color INTEGER NOT NULL
)""");
await db.rawInsert("INSERT INTO category (name, color) VALUES ('foo1', 0)");
await db.rawInsert("INSERT INTO category (name, color) VALUES ('foo2', 1)");
await db.rawInsert("INSERT INTO category (name, color) VALUES ('foo3', 2)");
}
Future countCategory() async {
Directory path = await getApplicationDocumentsDirectory();
String dbPath = join(path.path, "database.db");
Database db = await openDatabase(dbPath);
var count = await db.rawQuery("SELECT COUNT(*) FROM category");
List list = await db.rawQuery('SELECT name, color FROM category');
await db.close();
return [count, list];
}
}
//Class of Dialog Item
class DialogItem extends StatelessWidget {
DialogItem({
Key key,
this.icon,
this.size,
this.color,
this.text,
this.onPressed }) : super(key: key);
final IconData icon;
double size = 36.0;
final Color color;
final String text;
final VoidCallback onPressed;
#override
Widget build(BuildContext context) {
return new SimpleDialogOption(
onPressed: onPressed,
child: new Container(
child: new Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Container(
child: new Container(
margin: size == 16.0 ? new EdgeInsets.only(left: 7.0) : null,
child: new Icon(icon, size: size, color: color),
)
),
new Padding(
padding: size == 16.0 ?
const EdgeInsets.only(left: 17.0) :
const EdgeInsets.only(left: 16.0),
child: new Text(text),
),
],
),
)
);
}
}

Resources