i can't display my data from the database - database

so this is the create quiz interface where the teacher can insert the title of the quiz , the question and the option
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mr_quiz/DB_helper.dart';
import 'package:random_string/random_string.dart';
import 'DB_helper.dart';
import 'question.dart';
import 'qcm.dart';
import 'choix.dart';
import 'folder.dart';
class Create_Quiz extends StatefulWidget {
#override
_Create_QuizState createState() => _Create_QuizState();
}
class _Create_QuizState extends State<Create_Quiz> {
bool choix = false;
late String question;
late String option;
late String titre;
String qst_id=randomAlphaNumeric(16);
String op_id=randomAlphaNumeric(16);
String qcm_id=randomAlphaNumeric(16);
TextEditingController titre_ctrl=TextEditingController();
TextEditingController qst_ctrl=TextEditingController();
TextEditingController choix_ctrl=TextEditingController();
add_qst(Question question){
DB_helper.instance.insertquestion(question);
print('question ajoutée');
}
add_qcm(Qcm qcm){
DB_helper.instance.insertqcm(qcm);
print('qcm ajouté');
}
add_choix(Choix choix){
DB_helper.instance.insertchoix(choix);
print('choix ajouté');
}
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
fontFamily: 'HindGuntur',
),
debugShowCheckedModeBanner: false,
title: 'Mr.Quiz',
routes: {
'/folder': (BuildContext context) => Folder()},
home: Builder(builder: (context) => Scaffold(
backgroundColor: Colors.white,
resizeToAvoidBottomInset: false,
appBar: AppBar(
backgroundColor: Colors.white,
title: Text('QCM', style: TextStyle(
color: Colors.black, fontWeight: FontWeight.bold),),
centerTitle: true,
elevation: 0.0,
leading: IconButton(icon: Icon(Icons.arrow_back),
onPressed: () {},
color: Colors.deepPurple,),
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Center(child: Container(
height: 160.0,
width: 650.0,
margin: EdgeInsets.fromLTRB(30, 15, 30, 15),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30.0),
color: Colors.deepPurple.shade50,),
child: Column(
children: <Widget>[
SizedBox(height: 15.0,),
Text("Entrez le titre du QCM:",
style: TextStyle(fontWeight: FontWeight.bold,),
),
Container(
width: 300.0,
child: TextFormField(
controller: titre_ctrl,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
contentPadding: EdgeInsets.fromLTRB(20, 10, 5,
10),
hintText: 'Titre',
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.deepPurple,),
borderRadius: BorderRadius.circular(30.0),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.deepPurple.shade200,),
borderRadius: BorderRadius.circular(30.0),
),
),
),
),
],
),
),
),
SizedBox(height: 20.0,),
Container(
width: 350.0,
child: TextFormField(
controller: qst_ctrl,
decoration: InputDecoration(
contentPadding: EdgeInsets.fromLTRB(10, 10, 10, 10),
hintText: 'Question ',
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.deepPurple.shade100,),
borderRadius: BorderRadius.circular(30.0),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.deepPurple.shade200,),
borderRadius: BorderRadius.circular(30.0),
),
),
),
),
SizedBox(height: 20.0,),
Row(
children: [
Expanded(
flex: 6,
child: TextFormField(
controller: choix_ctrl,
decoration: InputDecoration(
hintText: "option ",
contentPadding: EdgeInsets.fromLTRB(20, 10, 10, 10),
),
),
),
Flexible(
child: SizedBox(
width: 5,
child: Checkbox(value: choix,
onChanged: (val) {
setState(() {
choix= val!;
});
},
activeColor: Colors.deepPurple,
checkColor: Colors.white,
),
),
)
],
),
Row(
children: <Widget>[
SizedBox(width: 120.0),
Icon(Icons.add_circle_outline, color: Colors.deepPurple,
size: 22.0,),
TextButton(
child: Text(
'ajouter un choix', textAlign: TextAlign.center,
style: TextStyle(
color: Colors.deepPurple, fontSize: 16.0),),
onPressed: () {setState(() {
option=choix_ctrl.text;
});
Choix choice =new Choix(op_id,option,choix);
add_choix(choice);
choix_ctrl.clear();},
),
],
),
SizedBox(height: 30.0,),
Column(
children: <Widget>[
ElevatedButton(style: ElevatedButton.styleFrom(
primary: Colors.deepPurple.shade200,
fixedSize: Size(300.0, 50.0),
elevation: 0.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0)),
),
child:
Text('Ajouter Question',
style: TextStyle(fontSize: 16.0),),
onPressed: () {setState(() {
question=qst_ctrl.text;
});
Question qst =new Question(qst_id,question);
add_qst(qst);
qst_ctrl.clear();},),
SizedBox(height: 20.0,),
ElevatedButton(style: ElevatedButton.styleFrom(
primary: Colors.indigo.shade400,
fixedSize: Size(250.0, 50.0),
elevation: 0.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30.0)),
),
child:
Text(
'valider mon QCM', style: TextStyle(fontSize: 16.0),),
onPressed: () {setState(() {
titre=titre_ctrl.text;
});
Qcm qcm =new Qcm(qcm_id,titre);
add_qcm(qcm);
Navigator.pushNamed(context, '/folder');
},),
],
),
SizedBox(height: 10.0,),
],),
),
),
)
);
}`
this is the folder interface where the quiz title is displayed
import 'package:flutter/material.dart';
import 'DB_helper.dart';
import'package:mr_quiz/createquiz.dart';
import 'qcm.dart';
import 'package:mr_quiz/question.dart';
import 'package:mr_quiz/choix.dart';
class Folder extends StatefulWidget {
const Folder({Key? key}) : super(key: key);
#override
_FolderState createState() => _FolderState();
}
class _FolderState extends State<Folder> {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
fontFamily: 'HindGuntur',
),
debugShowCheckedModeBanner: false,
title: 'Mes QCM',
home: Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: Colors.white,
appBar: AppBar(backgroundColor: Colors.deepPurple.shade200,
elevation: 0.0,
centerTitle: true,
title: Text(
"Mes QCM",
style:
TextStyle(
color: Colors.white,
fontWeight: FontWeight.w500,
),
),
),
body:FutureBuilder<List<Qcm>>(
future : DB_helper.instance.qcms(),
builder: (BuildContext context, AsyncSnapshot<List<Qcm>> snapshot) {
if (snapshot.hasData) {
List<Qcm>? qcms = snapshot.data;
return ListView.builder(
itemCount: qcms?.length,
itemBuilder: (context, index){
final qcm = qcms![index];
return Dismissible(key: Key(qcm.qcm_id),
onDismissed: (direction){
setState(() {
DB_helper.instance.deleteprofil(qcm.qcm_id);
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("${qcm.titre} supprimé")));
},
background: Container(color: Colors.red),
child: ProfWidget(qcm: qcm, ));
},
);
} else {
return Center(child: CircularProgressIndicator());
}
}
),
)
);
}
}
class ProfWidget extends StatelessWidget {
const ProfWidget({Key? key, required this.qcm}) : super(key: key);
final Qcm qcm;
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: (){
},
child: Card(
margin: EdgeInsets.all(8),
elevation: 8,
child: Row(
children: [
Padding(
padding: EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.only(bottom: 8),
child: Text(qcm.titre,
style:
TextStyle(fontWeight: FontWeight.bold, fontSize: 20)),
),
],
),
)
],
),
),
);
}
}
only the loading indicator is showing could anyone please help me solve this problem , and also can anyone please tell me how to display the data in the playquiz interface , we have a table for each model and they're related to each other with foreign keys but i don't know how to display data from them like i want to display the questions that belong to the same quiz and the options for each question

Related

how to show sub category data by category in flutter from sqlite db

import 'package:flutter/material.dart';
import 'package:stone_recipe_app/homepage.dart';
import 'package:stone_recipe_app/models/recipe.dart';
import 'package:share_plus/share_plus.dart';
class DetailedScreen extends StatelessWidget {
DetailedScreen({Key? key, required this.recipe, required this.index}) : super(key: key);
List<Recipe>? recipe;
int index;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: Row(
children: [
IconButton(
icon: const Icon(Icons.arrow_back_ios),
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => HomePage()));
},
),
Text(
'Back',
style: TextStyle(color: Color(0xff007AFF)),
)
],
),
iconTheme: const IconThemeData(color: Color(0xff007AFF)),
title: Center(
child: Text(
recipe![index].recipe_name,
style: TextStyle(color: Colors.black),
),
),
backgroundColor: Colors.white,
elevation: 0,
),
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
children: [
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(200),
),
child: Container(
width: 400,
height: 200,
decoration: const BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(9.0)),
image: DecorationImage(
image: AssetImage("images/cook.jpg"),
fit: BoxFit.cover,
),
boxShadow: [
BoxShadow(
blurRadius: 5,
color: Colors.black,
)
],
),
),
),
Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
const Icon(
Icons.file_download_sharp,
color: Colors.blue,
size: 40,
),
const Icon(
Icons.document_scanner,
size: 40,
),
IconButton(
onPressed: () {
Share.share(recipe![index].recipe_prep);
},
icon: const Icon(
Icons.share,
color: Colors.blue,
size: 40,
)),
const Icon(
Icons.favorite,
color: Colors.red,
size: 40,
),
]),
SizedBox(
height: 500,
child: Card(
elevation: 4,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: Text(
'Ingredients',
style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
),
),
Column(
children: [
Text(recipe![index].recipe_ingrdients),
],
),
Center(
child: Text(
'Method',
style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
),
),
Text(
recipe![index].recipe_prep,
style: TextStyle(
fontSize: 20,
),
)
],
),
),
)
],
),
),
);
// Scaffold(
// appBar: AppBar(
// title: Text(recipe![index].recipe_name),
// ),
// body: Center(
// child: SingleChildScrollView(
// child: Column(
// mainAxisSize: MainAxisSize.min,
// children: [
// SelectableText(recipe![index].recipe_cat),
// Text(recipe![index].recipe_prep),
// Text(recipe![index].recipe_id.toString()),
// Text(recipe![index].recipe_ingrdients),
// Text(recipe![index].image_name),
// OutlinedButton(
// onPressed: () {
// Share.share(recipe![index].recipe_prep);
// },
// child: Text('Share'))
// ],
// ),
// ),
// ),
// );
}
}
import 'package:flutter/material.dart';
import 'package:stone_recipe_app/detailedScreen.dart';
import 'package:stone_recipe_app/models/recipe.dart';
import 'package:stone_recipe_app/services/db_services.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final dbservice = DataBaseService();
#override
void dispose() {
dbservice.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Recipe App')),
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: FutureBuilder<List<Recipe>>(
future: dbservice.getRecipe(),
builder: (context, snapshot) {
if (!snapshot.hasData) return Center(child: CircularProgressIndicator());
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data?.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailedScreen(
recipe: snapshot.data,
index: index,
)));
},
title: Text(snapshot.data![index].recipe_name, style: TextStyle(color: Colors.black)),
// trailing: Text(
// snapshot.data![index].recipe_cat,
// style: TextStyle(color: Colors.black),
// overflow: TextOverflow.fade,
// ),
);
},
);
},
)),
);
}
}
enter image description herei am trying to show data from sqlite db in flutter when user click on country category like india china after user click user navigate to other page which are recipe name related to chine or related to india i am trying to show data from sqlite db in flutter when user click on country category like india china after user click user navigate to other page which are recipe name related to chine or related to india enter image description here
add group_list_view: ^1.1.1 package in your pubspec.yaml file.
try below the example then implement it in your project
import 'package:flutter/material.dart';
import 'package:group_list_view/group_list_view.dart';
import 'package:group_listview_example/app_colors.dart';
void main() => runApp(MyApp());
Map<String, List> _elements = {
'Team A': ['Klay Lewis', 'Ehsan Woodard', 'River Bains'],
'Team B': ['Toyah Downs', 'Tyla Kane'],
'Team C': ['Marcus Romero', 'Farrah Parkes', 'Fay Lawson', 'Asif Mckay'],
'Team D': [
'Casey Zuniga',
'Ayisha Burn',
'Josie Hayden',
'Kenan Walls',
'Mario Powers'
],
'Team Q': ['Toyah Downs', 'Tyla Kane', 'Toyah Downs'],
};
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Group List View Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Group List View Demo'),
),
body: GroupListView(
sectionsCount: _elements.keys.toList().length,
countOfItemInSection: (int section) {
return _elements.values.toList()[section].length;
},
itemBuilder: _itemBuilder,
groupHeaderBuilder: (BuildContext context, int section) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 8),
child: Text(
_elements.keys.toList()[section],
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
),
);
},
separatorBuilder: (context, index) => SizedBox(height: 10),
sectionSeparatorBuilder: (context, section) => SizedBox(height: 10),
),
),
);
}
Widget _itemBuilder(BuildContext context, IndexPath index) {
String user = _elements.values.toList()[index.section][index.index];
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Card(
elevation: 8,
child: ListTile(
contentPadding:
const EdgeInsets.symmetric(horizontal: 18, vertical: 10.0),
leading: CircleAvatar(
child: Text(
_getInitials(user),
style: TextStyle(color: Colors.white, fontSize: 18),
),
backgroundColor: _getAvatarColor(user),
),
title: Text(
_elements.values.toList()[index.section][index.index],
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w400),
),
trailing: Icon(Icons.arrow_forward_ios),
),
),
);
}
String _getInitials(String user) {
var buffer = StringBuffer();
var split = user.split(" ");
for (var s in split) buffer.write(s[0]);
return buffer.toString().substring(0, split.length);
}
Color _getAvatarColor(String user) {
return AppColors
.avatarColors[user.hashCode % AppColors.avatarColors.length];
}
}

List view using array list with name image date in flutter

How to get data from static or dynamic list and set to list view or grid view
If you want to convert your list of data into a ListView of widgets you can map the data list to your resultant widget list. Follow the code below:
class TestPage extends StatefulWidget {
#override
_TestPageState createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
List<Data> dataList = [
Data(name: "Demo name",date: DateTime.now(),description: "Dummy long description",imageURL: 'https://m.files.bbci.co.uk/modules/bbc-morph-sport-seo-meta/1.20.8/images/bbc-sport-logo.png'),
Data(name: "Demo name",date: DateTime.now(),description: "Dummy long description",imageURL: 'https://m.files.bbci.co.uk/modules/bbc-morph-sport-seo-meta/1.20.8/images/bbc-sport-logo.png'),
Data(name: "Demo name",date: DateTime.now(),description: "Dummy long description",imageURL: 'https://m.files.bbci.co.uk/modules/bbc-morph-sport-seo-meta/1.20.8/images/bbc-sport-logo.png'),
Data(name: "Demo name",date: DateTime.now(),description: "Dummy long description",imageURL: 'https://m.files.bbci.co.uk/modules/bbc-morph-sport-seo-meta/1.20.8/images/bbc-sport-logo.png'),
];
#override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return Scaffold(
body: Container(
width: width,
height: height,
child: ListView(
scrollDirection: Axis.vertical,
children: dataList.map((data){
return Container(
width: width,height: 80,
decoration: BoxDecoration(border: Border(bottom: BorderSide(width: 1.5,color: Colors.black))),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(width: 50,height: 50,decoration: BoxDecoration(image: DecorationImage(image: NetworkImage(data.imageURL))),),
Column(
mainAxisSize: MainAxisSize.max,
children: [
Text(data.name),
Expanded(child: Text(data.description)),
],
),
Text(data.date.toString());
],
),
);
}).toList(),
),
),
);
}
}
class Data {
String name;
String imageURL;
String description;
DateTime date;
Data({this.name,this.imageURL,this.date,this.description});
}
Check the above code based on your requirement.
List dataList = [
Data(
name: "Title",date: "12/03/2021",description: "Description",imageURL:'https://m.files.bbci.co.uk/modules/bbc-morph-sport-seo-meta/1.20.8/images/bbc-sport-logo.png'),
];
#override
Widget build(BuildContext context) {
double width = MediaQuery
.of(context)
.size
.width;
double height = MediaQuery
.of(context)
.size
.height;
return Scaffold(
appBar: new AppBar(
bottomOpacity: 0.0,
elevation: 0.0,
backgroundColor: Color(0xFF104C57),
title: new Text("Notification"),
leading: new IconButton(
icon: new Icon(Icons.arrow_back),
onPressed: () => Navigator.of(context).pop(),
),
),
body: SingleChildScrollView(
child: Container(
child: Card(
margin: EdgeInsets.only(left: 7.0, right: 7.0),
child: Container(
width: width,
height: height,
child: ListView(
scrollDirection: Axis.vertical,
children: dataList.map((data) {
return Container(
margin: EdgeInsets.only(left: 6.0, right: 6.0, top: 10.0),
width: width,
height: 80,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(5)),
border: Border.all(
color: Color(0xFFDCDADB),
width: 0.5,
),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
width: 10,
),
Container(
width: 65,
height: 65,
decoration: BoxDecoration(
image: DecorationImage(
image: ExactAssetImage(
'lib/images/notificationicon.png',
),
)),
),
SizedBox(
width: 10,
),
Container(
width: 145,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
children: [
SizedBox(
height: 20,
),
Text(
data.name,
style: TextStyle(
fontSize: 12.0,
//fontWeight: FontWeight.w700,
color: Color(0xFF75778A),
fontWeight: FontWeight.w500,
),
),
Expanded(
child: Text(
data.description,
style: TextStyle(
fontSize: 12.0,
//fontWeight: FontWeight.w700,
color: Color(0xFF868C9A),
),
)),
],
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: [
SizedBox(
height: 20,
),
Row(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(
"Date : ",
style: TextStyle(
fontSize: 12.0,
color: Color(0xFF868C9A),
),
),
Text(
data.date,
style: TextStyle(
fontSize: 12.0,
fontWeight: FontWeight.w500,
color: Color(0xFF6A7180),
),
),
],
),
],
),
],
),
);
}).toList(),
),
),
),
width: double.infinity,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(00)),
image: DecorationImage(
image: ExactAssetImage('lib/images/homebg.png'),
fit: BoxFit.fill,
),
),
),
),
);
}
class Data {
String name,imageURL,description,date;
Data({this.name, this.imageURL, this.date, this.description});
}

Use while loop to repeat 3 widgets. in flutter

I want to repeat the following code with index values from 1 to n. How to do it in flutter ?
return ListView(
children: <Widget>[
SizedBox(
height: 15.0,
),
new Image.asset(
"assets/$name/$index.jpg",
fit: BoxFit.cover,
),
SizedBox(
height: 10.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("$name $index",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 23,
fontFamily: 'Raleway',
color: Colors.black)),
Container(
margin: EdgeInsets.only(left: 100.0),
width: 150.0,
height: 50.0,
child: FlatButton(
onPressed: null,
child: Text('Download',
style: TextStyle(color: Colors.black, fontSize: 20)),
textColor: Colors.white,
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.teal, width: 2, style: BorderStyle.solid),
borderRadius: BorderRadius.circular(50)),
),
),
],
),
],
);
To show 3 times simple text using while loop.
Widget getWidgets() {
List<Widget> list = new List<Widget>();
int i = 0;
while (i < 3) {
list.add(new Text(strings[i]));
i++;
}
return Row(children:list);
}
You can copy paste run full code below
You can use ListView.builder with itemCount and wrap Column
code snippet
ListView.builder(
itemCount: 10,
itemBuilder: (BuildContext ctxt, int index) {
return Column(
children: <Widget>[
working demo
full code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: ListView.builder(
itemCount: 10,
itemBuilder: (BuildContext ctxt, int index) {
return Column(
children: <Widget>[
SizedBox(
height: 15.0,
),
Image.network(
"https://picsum.photos/50?image=$index",
fit: BoxFit.cover,
),
SizedBox(
height: 10.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("$index",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 23,
fontFamily: 'Raleway',
color: Colors.black)),
Container(
margin: EdgeInsets.only(left: 100.0),
width: 150.0,
height: 50.0,
child: FlatButton(
onPressed: null,
child: Text('Download',
style:
TextStyle(color: Colors.black, fontSize: 20)),
textColor: Colors.white,
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.teal,
width: 2,
style: BorderStyle.solid),
borderRadius: BorderRadius.circular(50)),
),
),
],
),
],
);
}),
);
}
}

Unable to create data tables dynamically using TextField input

I am trying out to create an invoice application, wherein the user is entering the data, and then it should come up listed as a table.
What I have achieved so far is just a single row with just a single user input detail like with errors in it as well...
I wanted the application to
HardCoded Code:
class Sixth extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return SixthState();
}
}
class SixthState extends State<Sixth> {
final pdf = pw.Document();
String path;
share() async {
Share.shareFiles([path]);
}
create() async {
print('creating');
pdf.addPage(pw.MultiPage(
pageFormat: PdfPageFormat.a4,
margin: pw.EdgeInsets.all(12),
build: (pw.Context context) {
return <pw.Widget>[
pw.Paragraph(
text: 'SOLUTION HUB\nVENDORS',
style: pw.TextStyle(fontWeight: pw.FontWeight.bold)),
pw.Paragraph(
padding: pw.EdgeInsets.only(left: 450),
text: 'Billing Address:',
style: pw.TextStyle(fontWeight: pw.FontWeight.bold)),
pw.Row(children: [
pw.Paragraph(
text: 'wrqijwqiojqwoirjq\nirjorwiuroeriuwor\noerweo8rw',
padding: pw.EdgeInsets.only(top: 10)),
pw.SizedBox(width: 370),
pw.Paragraph(
text: 'wrqijwqiojqwoirjq\nirjorwiuroeriuwor\noerweo8rw',
padding: pw.EdgeInsets.only(top: 10))
]),
pw.Paragraph(
padding: pw.EdgeInsets.only(top: 15),
text: 'PAN No. ${panvalue}',
style: pw.TextStyle(fontWeight: pw.FontWeight.bold)),
pw.Paragraph(
padding: pw.EdgeInsets.only(top: 15),
text: 'GST Registration No. ${gstvalue}',
style: pw.TextStyle(fontWeight: pw.FontWeight.bold)),
pw.Paragraph(
padding: pw.EdgeInsets.only(top: 15),
text: 'Order No. ${ordernovalue}',
style: pw.TextStyle(fontWeight: pw.FontWeight.bold)),
pw.Paragraph(
padding: pw.EdgeInsets.only(top: 15),
text: 'Order Date. ${orderdatevalue}',
style: pw.TextStyle(fontWeight: pw.FontWeight.bold)),
pw.Paragraph(
padding: pw.EdgeInsets.only(left: 450),
text: 'INVOICE NUMBER\n03950234982042980',
style: pw.TextStyle(fontWeight: pw.FontWeight.bold)),
pw.SizedBox(height: 20),
pw.Table.fromTextArray(data: <List<String>>[
<String>[
'SI\nNo.',
'Description',
'Unit\nPrice',
'Qty',
'Net Amount',
'Tax\nRate',
'Tax\nType',
'Tax\nAmt',
'Total\nAmt'
],
<String>[
'1',
'${SecondState.descriptionController.text}',
'${ThirdState.unitpriceController.text}',
'1',
'500',
'${FourthState.taxrateController.text}',
'${FourthState.taxtypeController.text}',
'${FourthState.taxamountController.text}',
'276.6'
],
])
];
},
));
}
Future save() async {
print('sacing');
Directory directory = await getApplicationDocumentsDirectory();
String documentpath = directory.path;
File file = File("$documentpath/example.pdf");
setState(() {
path = "$documentpath/example.pdf";
});
file.writeAsBytesSync(pdf.save());
}
int _value = 1;
AnimationController animationController;
Animation<Offset> offset;
static var panvalue;
static var gstvalue;
static var ordernovalue;
static var orderdatevalue;
static var descriptionvalue;
static var unitpricevalue;
static var quantityvalue;
static var taxratevalue;
static var taxtypevalue;
static var taxamtvalue;
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
drawer: Drawer(),
appBar: AppBar(
centerTitle: true,
title: Text('ORDER DETAILS'),
backgroundColor: Colors.blueGrey,
actions: <Widget>[
Padding(
padding: EdgeInsets.all(2),
child: IconButton(
onPressed: () {}, //USER PROFILE
icon: Icon(Icons.supervised_user_circle),
iconSize: 30,
),
)
],
),
body: SingleChildScrollView(
child: SafeArea(
child: Column(children: <Widget>[
Container(
padding: EdgeInsets.only(right: 220, top: 20),
child: Text(
'SOLUTION HUB \n VENDORS',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
),
),
Container(
padding: EdgeInsets.only(left: 240),
child: Text(
'Billing Adress:',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
),
),
SizedBox(
height: 15,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
padding: EdgeInsets.only(left: 30),
child:
Text('Ubga wjpw wiqjoiw\n owqkdw qwok qoqkw \nojq vpoqk'),
),
Container(
padding: EdgeInsets.only(right: 15),
child: Text('oefkwpfoke 20-32 \n 032902 0239 \n 0392230'),
)
],
),
Container(
width: 800,
padding: EdgeInsets.only(left: 35, right: 10, top: 45),
child: Text(
"Pan No. ${panvalue}",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Container(
width: 800,
padding: EdgeInsets.only(left: 35, right: 10, top: 25),
child: Text(
"GST REGISTRATION NO. ${gstvalue}",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Container(
width: 800,
padding: EdgeInsets.only(left: 35, right: 10, top: 25),
child: Text(
"Order No. ${ordernovalue} ",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
Container(
width: 400,
padding: EdgeInsets.only(left: 35, right: 20, top: 25),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Order Date: ${orderdatevalue}",
style: TextStyle(fontWeight: FontWeight.bold),
),
Text(
'INVOICE NUMBER',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
)
],
),
),
Container(
padding: EdgeInsets.only(left: 250, top: 5),
child: Text('5920384283429')),
Row(
children: <Widget>[
Expanded(
child: SingleChildScrollView(
child: DataTable(columnSpacing: 4, columns: [
DataColumn(
label: Text(
'Si\nNo.',
textAlign: TextAlign.left,
)),
DataColumn(label: Text('Description')),
DataColumn(label: Text('Unit\nPrice')),
DataColumn(label: Text('Qty')),
DataColumn(label: Text('Net\namount')),
DataColumn(label: Text('Tax\nRate')),
DataColumn(label: Text('Tax\nType')),
DataColumn(label: Text('Tax\nAmt')),
DataColumn(label: Text('Total\nAmt'))
], rows: [
DataRow(cells: [
DataCell(Wrap(
children: <Widget>[
Text(
'1',
textAlign: TextAlign.start,
)
],
)),
DataCell(Text(
'${SecondState.descriptionController.text}',
textAlign: TextAlign.center,
)),
DataCell(Wrap(
children: <Widget>[
Text(
'${ThirdState.unitpriceController.text}',
textAlign: TextAlign.center,
)
],
)),
DataCell(Text('${ThirdState.quantityController.text}')),
DataCell(Text('500')),
DataCell(Text('${FourthState.taxrateController.text}')),
DataCell(Text('${FourthState.taxtypeController.text}')),
DataCell(Text('${FourthState.taxamountController.text}')),
DataCell(Text('500')),
])
]))),
],
),
SizedBox(
height: 150,
),
ButtonTheme(
minWidth: 110,
height: 50,
child: RaisedButton(
color: Colors.blue[300],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18)),
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("COMPLETE ACTION USING"),
content: Container(
height: 150,
width: 100,
child: Column(
children: <Widget>[
FlatButton(
onPressed: () async {
create();
await save();
share();
},
child: Text('WhatsApp'),
),
FlatButton(
onPressed: () {},
child: Text('Gmail'),
),
FlatButton(
onPressed: () {},
child: Text("Download"),
)
],
),
),
);
});
},
child: Text('Share'),
),
)
]),
),
),
));
}
}
What I want to achieve is this
It should automatically add rows as user inputs enter details
Errors I have encountered:
Whenever I going to add more items the previous data are stored in the text fields.
There are more colors on the right side but am unable to view it.
Please help me solve this issue

how to update flutter UI according to firebase

I have this list of Post where user can like, comment and share.
Widget build(BuildContext context) {
return Container(
child: FutureBuilder(
future: _data,
builder: (_, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (_, index) {
return Card(
elevation: 4,
child: Padding(
padding: EdgeInsets.only(left: 10.0, top: 10),
child: InkWell(
onTap: () => navigateToDetail(
snapshot.data[index],
snapshot.data[index].data["Userid"],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new Row(
children: <Widget>[
Container(
width: 45,
height: 45,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(snapshot
.data[index].data["User Pic"]),
fit: BoxFit.cover,
),
borderRadius: BorderRadius.all(
Radius.circular(50.5)),
),
),
Padding(
padding: EdgeInsets.only(left: 15),
child: Text(
snapshot.data[index].data["Name"],
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 18),
),
),
],
),
Padding(
padding: EdgeInsets.only(left: 60, bottom: 10),
child: Text(
DateFormat.yMMMd().add_jm().format(
DateTime.parse(snapshot
.data[index].data["Creation Time"]
.toDate()
.toString())),
style: TextStyle(
color: Colors.black38, fontSize: 12),
),
),
Flexible(
child: Padding(
padding: EdgeInsets.only(left: 75, right: 15),
child: Text(
snapshot.data[index].data["Description"],
style: TextStyle(fontSize: 16),
),
),
),
Padding(
padding: EdgeInsets.only(
left: 75, top: 15, bottom: 8),
child: Text(
snapshot.data.length.toString() +
"Files uploaded",
style: TextStyle(
color: Colors.blueAccent,
fontSize: 14,
fontStyle: FontStyle.italic),
),
),
Divider(),
new Row(
children: <Widget>[
Expanded(
child: Row(
children: <Widget>[
IconButton(
onPressed: () {
Firestore.instance.runTransaction((transaction) async{
DocumentSnapshot freshData = await transaction.get(snapshot.data[index].reference);
await transaction.update(freshData.reference, {
'Likes':freshData['Likes']+1,
});
});
},
icon: Icon(Icons.favorite_border,
color: Colors.redAccent,
size: 23.0),
),
Text(snapshot.data[index].data["Likes"].toString())
],
),
),
Expanded(
child: IconButton(
onPressed: () {},
icon: Icon(
Icons.chat_bubble_outline,
color: Colors.blue,
size: 23.0,
),
),
),
Expanded(
child: IconButton(
onPressed: () {},
icon: Icon(
Icons.near_me,
color: Colors.blue,
size: 23.0,
),
),
),
],
),
],
),
),
),
);
});
}
}),
);
}
and have a Firestore like this :
storing likes in Post collection.
I need:
when the user press on like icon it will update the firestore as well as count in flutter UI.
what I have done so far:
it will only update the firestore and for updation in flutter UI I have to refresh the screen.
Thanks.
Update:
#override
void initState() {
super.initState();
_data = UserManagement().getPosts();
}
from UserManagement:
getPosts() async {
QuerySnapshot Qn = await Firestore.instance.collection("Posts").orderBy(
"Creation Time", descending: true).getDocuments();
return Qn.documents;
}
Just replace your FutureBuilder with StreamBuilder to get the stream whenever there is an update in your collection
Widget build(BuildContext context) {
return Container(
child: StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection("Posts").orderBy(
"Creation Time", descending: true).snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (_, index) {
return Card(
elevation: 4,
child: Padding(
padding: EdgeInsets.only(left: 10.0, top: 10),
child: InkWell(
onTap: () => navigateToDetail(
snapshot.data[index],
snapshot.data[index].data["Userid"],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new Row(
children: <Widget>[
Container(
width: 45,
height: 45,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(snapshot
.data[index].data["User Pic"]),
fit: BoxFit.cover,
),
borderRadius: BorderRadius.all(
Radius.circular(50.5)),
),
),
Padding(
padding: EdgeInsets.only(left: 15),
child: Text(
snapshot.data[index].data["Name"],
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 18),
),
),
],
),
Padding(
padding: EdgeInsets.only(left: 60, bottom: 10),
child: Text(
DateFormat.yMMMd().add_jm().format(
DateTime.parse(snapshot
.data[index].data["Creation Time"]
.toDate()
.toString())),
style: TextStyle(
color: Colors.black38, fontSize: 12),
),
),
Flexible(
child: Padding(
padding: EdgeInsets.only(left: 75, right: 15),
child: Text(
snapshot.data[index].data["Description"],
style: TextStyle(fontSize: 16),
),
),
),
Padding(
padding: EdgeInsets.only(
left: 75, top: 15, bottom: 8),
child: Text(
snapshot.data.length.toString() +
"Files uploaded",
style: TextStyle(
color: Colors.blueAccent,
fontSize: 14,
fontStyle: FontStyle.italic),
),
),
Divider(),
new Row(
children: <Widget>[
Expanded(
child: Row(
children: <Widget>[
IconButton(
onPressed: () {
Firestore.instance.runTransaction((transaction) async{
DocumentSnapshot freshData = await transaction.get(snapshot.data[index].reference);
await transaction.update(freshData.reference, {
'Likes':freshData['Likes']+1,
});
});
},
icon: Icon(Icons.favorite_border,
color: Colors.redAccent,
size: 23.0),
),
Text(snapshot.data[index].data["Likes"].toString())
],
),
),
Expanded(
child: IconButton(
onPressed: () {},
icon: Icon(
Icons.chat_bubble_outline,
color: Colors.blue,
size: 23.0,
),
),
),
Expanded(
child: IconButton(
onPressed: () {},
icon: Icon(
Icons.near_me,
color: Colors.blue,
size: 23.0,
),
),
),
],
),
],
),
),
),
);
});
}
}),
);
}
I assume you should use a StreamBuilder instead of a FutureBuilder.
StreamBuilders are like FutureBuilders that continuously update, depending on their stream.
You should also subscribe to the stream of the Firestore collection, instead of getting it only once.
Instead of getPosts maybe use this:
Stream<QuerySnapshot> getPostsStream() {
return Firestore.instance.collection("Posts").orderBy(
"Creation Time", descending: true).snapshots();
}
And change your FutureBuilder to a StreamBuilder:
StreamBuilder<QuerySnapshot>(
stream: getPostsStream(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
} else {
final List<DocumentSnapshot> documents = snapshot.data.documents;
// use as documents[index].
// ....
}
},
),

Resources