Error Get Value TextEditingController In Flutter - android

I want to retrieve the value from textEditingController with a loop, the problem that occurs when the listview is not scrolled will result in an error, "RangeError (index): Invalid value: Not in inclusive range 0..23: 24", I have random data of 40 records,
the application will run properly when scrolling to the end of the line. I want even though I don't scroll down the data can still be retrieved without error.
you can run my sample code, please help me thanks.
import 'dart:math';
import 'package:flutter/material.dart';
class Karyawan {
int id;
String nama;
int jamKerja;
Karyawan({this.id, this.nama,});
Karyawan.fromJson(Map<String, dynamic> json) {
id = json['id'];
nama = json['nama_karyawan'];
jamKerja = json['jam_kerja'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['nama_karyawan'] = this.nama;
data['jam_kerja'] = this.jamKerja;
return data;
}
}
List<Karyawan> _daftarKaryawan = List.generate(
40,
(index) => Karyawan(
id: Random().nextInt(100),
nama: 'test ${Random().nextInt(100)}',
),
);
class FormInputAbsenV3 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Entry Absen"),
),
body: FormEntry(listKaryawan:_daftarKaryawan)
);
}
}
class FormEntry extends StatefulWidget {
final List<Karyawan> listKaryawan;
const FormEntry({Key key, this.listKaryawan}) : super(key: key);
#override
_FormEntryState createState() => _FormEntryState();
}
class _FormEntryState extends State<FormEntry> {
List karyawan = [];
final _formKey = GlobalKey<FormState>();
List<TextEditingController> _brutos = new List();
List<TextEditingController> _nettos = new List();
void addlistAbsen() {
for (int i = 0; i < widget.listKaryawan.length; i++) {
karyawan.add({
"id": widget.listKaryawan[i].id,
"bruto": _brutos[i].text,
"netto": _nettos[i].text
});
}
print(karyawan);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
margin: EdgeInsets.all(5.0),
child: Form(
key: _formKey,
child: Container(
child: ListView.builder(
itemCount: widget.listKaryawan.length,
itemBuilder: (context,index) {
_brutos.add(new TextEditingController());
_nettos.add(new TextEditingController());
return Column(
children: [
FormWidget(
index: index,
nama: widget.listKaryawan[index].nama,
brucon: _brutos[index],
netcon: _nettos[index],
),
SizedBox(
height: 20.0,
),
],
);
},
),
),
),
),
floatingActionButton: FloatingActionButton.extended(
icon: Icon(Icons.save),
label: Text("Save"),
onPressed: () {
if (_formKey.currentState.validate()) {
addlistAbsen();
}
},
),
);
}
}
class FormWidget extends StatelessWidget {
final int index;
final String nama;
final brucon;
final netcon;
FormWidget({this.index, this.nama, this.brucon, this.netcon});
#override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text("${index + 1}. ${nama}"),
),
Expanded(
child: TextFormField(
decoration: new InputDecoration(
labelText: "Bruto",
fillColor: Colors.white,
border: new OutlineInputBorder(
borderRadius: new BorderRadius.circular(25.0),
borderSide: new BorderSide(),
),
),
style: new TextStyle(
fontFamily: "Poppins",
),
controller: brucon,
),
),
SizedBox(
width: 20.0,
),
Expanded(
child: TextFormField(
decoration: new InputDecoration(
labelText: "Netto",
fillColor: Colors.white,
border: new OutlineInputBorder(
borderRadius: new BorderRadius.circular(25.0),
borderSide: new BorderSide(),
),
),
style: new TextStyle(
fontFamily: "Poppins",
),
controller: netcon,
))
],
);
}
}

Please initialize your TextEditingControllers during initState.
#override
void initState() {
super.initState();
for (int i = 0; i < widget.listKaryawan.length; i++) {
_brutos.add(new TextEditingController());
_nettos.add(new TextEditingController());
}
}
Then, remove these lines inside the itemBuilder...
_brutos.add(new TextEditingController());
_nettos.add(new TextEditingController());
NOTE: itemBuilder will be called when a list item is to be redisplayed/newly displayed. Therefore, your list of TextEditingControllers > list items. (try scrolling to the bottom most, then scroll back up)

You CANNOT use ListView.builder for this and you will have to use ListView. You cannot use ListView.builder constructor because the builder is called only for those children that are actually visible. Please see the documentation for ListView.builder
ListView.builder constructor
Creates a scrollable, linear array of widgets that are created on
demand.
This constructor is appropriate for list views with a large (or
infinite) number of children because the builder is called only for
those children that are actually visible.
Please see the following code :
import 'package:flutter/material.dart';
import 'dart:math';
final Color darkBlue = const Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
//theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: FormInputAbsenV3(),
),
),
);
}
}
class Karyawan {
int id;
String nama;
int jamKerja;
Karyawan({
this.id,
this.nama,
});
Karyawan.fromJson(Map<String, dynamic> json) {
id = json['id'];
nama = json['nama_karyawan'];
jamKerja = json['jam_kerja'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = Map<String, dynamic>();
data['id'] = this.id;
data['nama_karyawan'] = this.nama;
data['jam_kerja'] = this.jamKerja;
return data;
}
}
List<Karyawan> _daftarKaryawan = List.generate(
40,
(index) => Karyawan(
id: Random().nextInt(100),
nama: 'test ${Random().nextInt(100)}',
),
);
class FormInputAbsenV3 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Entry Absen"),
),
body: FormEntry(listKaryawan: _daftarKaryawan));
}
}
class FormEntry extends StatefulWidget {
final List<Karyawan> listKaryawan;
const FormEntry({Key key, this.listKaryawan}) : super(key: key);
#override
_FormEntryState createState() => _FormEntryState();
}
class _FormEntryState extends State<FormEntry> {
List karyawan = [];
final _formKey = GlobalKey<FormState>();
List<TextEditingController> _brutos = [];
List<TextEditingController> _nettos = [];
#override
void initState() {
super.initState();
for (int i = 0; i < widget.listKaryawan.length; i++) {
_brutos.add(TextEditingController());
_nettos.add(TextEditingController());
}
}
void addlistAbsen() {
for (int i = 0; i < widget.listKaryawan.length; i++) {
karyawan.add({
"id": widget.listKaryawan[i].id,
"bruto": _brutos[i].text,
"netto": _nettos[i].text
});
}
print(karyawan);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
margin: EdgeInsets.all(5.0),
child: Form(
key: _formKey,
child: Container(
// child: ListView.builder(
// itemCount: widget.listKaryawan.length,
// itemBuilder: (context, index) {
// _brutos.add(new TextEditingController());
// _nettos.add(new TextEditingController());
// return Column(
// children: [
// FormWidget(
// index: index,
// nama: widget.listKaryawan[index].nama,
// brucon: _brutos[index],
// netcon: _nettos[index],
// ),
// SizedBox(
// height: 20.0,
// ),
// ],
// );
// },
// ),
child: ListView(
children: [
for (int index = 0; index < widget.listKaryawan.length; index++)
Column(
children: [
FormWidget(
index: index,
nama: widget.listKaryawan[index].nama,
brucon: _brutos[index],
netcon: _nettos[index],
),
SizedBox(
height: 20.0,
),
],
),
],
),
),
),
),
floatingActionButton: FloatingActionButton.extended(
icon: Icon(Icons.save),
label: Text("Save"),
onPressed: () {
if (_formKey.currentState.validate()) {
addlistAbsen();
}
},
),
);
}
}
class FormWidget extends StatelessWidget {
final int index;
final String nama;
final TextEditingController brucon;
final TextEditingController netcon;
const FormWidget({this.index, this.nama, this.brucon, this.netcon});
#override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text("${index + 1}. ${nama}"),
),
Expanded(
child: TextFormField(
decoration: InputDecoration(
labelText: "Bruto",
fillColor: Colors.white,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(),
),
),
style: TextStyle(
fontFamily: "Poppins",
),
controller: brucon,
),
),
SizedBox(
width: 20.0,
),
Expanded(
child: TextFormField(
decoration: InputDecoration(
labelText: "Netto",
fillColor: Colors.white,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: BorderSide(),
),
),
style: TextStyle(
fontFamily: "Poppins",
),
controller: netcon,
))
],
);
}
}

Related

Add and remove columns childs inside Gridview

I write the code to add and remove columns inside Gridview at first load screen everything looks fine but when I remove any column on click the cross button inside the column it breaks the layout and does not remove any column whenever i click to remove column it shows error
Error: SliverGeometry is not valid: The "maxPaintExtent" is less than the "paintExtent".
Error Image: Error of layout during click/remove item
Here is my code :-
import 'package:flutter/material.dart';
import 'package:mindmatch/utils/widget_functions.dart';
import 'package:mindmatch/custom/BorderIcon.dart';
import 'package:mindmatch/screens/Relation.dart';
import 'package:flutter_svg/flutter_svg.dart';
void main() {
runApp(new MaterialApp(
home: new Photos(),
));
}
class Photos extends StatefulWidget {
var usrid;
Photos({Key? key, #required this.usrid}) : super(key: key);
#override
_Photos createState() => _Photos();
}
class _Photos extends State<Photos>{
int counter = 0;
//List<Widget> _list = new List<Widget>();
List<Widget> _list = <Widget> [];
#override
void initState() {
for(int i =0; i < 4; i++){
Widget child = _newItem(i);
_list.add(child);
}
}
void on_Clicked() {
Widget child = _newItem(counter);
setState(() => _list.add(child));
}
Widget _newItem(int i) {
Key key = new Key('item_${i}');
Column child = Column(
key: key,
children: [
Stack(
children: [
Card(
elevation: 0,
shape: RoundedRectangleBorder(
side: BorderSide(
color: Color(0xffa1a1a1),
),
borderRadius: BorderRadius.all(Radius.circular(12)),
),
child: SizedBox(
//width: 300,
height: 100,
child: Center(child:
Icon(
Icons.image,
color: Color(0xffcccccc),
size: 60,
),
),
),
),
Positioned(
top: 9,
right: 9,
child: InkWell(
onTap: () => _removeItem(key),
child: SvgPicture.asset(
width: 20,
'assets/images/close.svg',
height: 20,
),
),
)
]
),
]
);
counter++;
return child;
}
void _removeItem(Key key){
for(int i = 0; i < _list.length; i++){
Widget child = _list.elementAt(i);
if(child.key == key){
setState(() => _list.removeAt(i));
print('Removing ${key.toString()}');
}
}
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Photos'),
backgroundColor: Colors.deepPurpleAccent,
),
floatingActionButton: new FloatingActionButton(onPressed: on_Clicked, child: new
Icon(Icons.add),),
body: new Container(
padding: new EdgeInsets.all(32.0),
child: Column(
children: [
Expanded(
child: GridView(
//padding: const EdgeInsets.all(8.0),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 10.0,
mainAxisSpacing: 15,
//childAspectRatio: 2/1,
),
children: _list,
)
)
],
),
),
);
}
}
And here is my output:- Output image of code where clearly see add and remove functionality
Please help out how I did this task and how I add and remove columns inside Gridview
anyone, please help me.
And this is what I need to do:- this is actual layout i want to create
So please help me
You should not operate the widget directly but data instead. What you should store in the list is the data (image URL or some string, which can be a very complex data structure) you want to present in the view and make the view respond to the changes happening on the object list with flutter's setState function.
try this:
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(
home: new Photos(),
));
}
class Photos extends StatefulWidget {
var usrid;
Photos({Key? key, #required this.usrid}) : super(key: key);
#override
_Photos createState() => _Photos();
}
class _Photos extends State<Photos> {
int counter = 0;
//List<Widget> _list = new List<Widget>();
List<String> _list = <String>[];
#override
void initState() {
for (int i = 0; i < 4; i++) {
_list.add("your data -obj");
}
}
void on_Clicked() {
setState(() => _list.add("your data -obj"));
}
Widget _newItem(int i) {
Key key = new Key('item_${i}');
Column child = Column(key: key, children: [
Stack(children: [
Card(
elevation: 0,
shape: RoundedRectangleBorder(
side: BorderSide(
color: Color(0xffa1a1a1),
),
borderRadius: BorderRadius.all(Radius.circular(12)),
),
child: SizedBox(
//width: 300,
height: 80,
child: Center(
child: Icon(
Icons.image,
color: Color(0xffcccccc),
size: 60,
),
),
),
),
Positioned(
top: 9,
right: 9,
child: InkWell(onTap: () => _removeItem(i), child: Text('close')),
)
]),
]);
counter++;
return child;
}
void _removeItem(int i) {
print("====remove $i");
print('===Removing $i');
setState(() => _list.removeAt(i));
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Photos'),
backgroundColor: Colors.deepPurpleAccent,
),
floatingActionButton: new FloatingActionButton(
onPressed: on_Clicked,
child: new Icon(Icons.add),
),
body: new Container(
padding: new EdgeInsets.all(32.0),
child: Column(
children: [
Expanded(
child: GridView(
//padding: const EdgeInsets.all(8.0),
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 10.0,
mainAxisSpacing: 15,
//childAspectRatio: 2/1,
),
children: List.generate(_list.length, (index) {
//generating tiles with people from list
return _newItem(index);
})))
],
),
),
);
}
}

Change API JSON call Link whenever i click the next tab for flutter river pods

I am using flutter river pods for this project. I want to change the API call when pressing on the second and third tab. I.e make the JSON API link dynamic. How can I do that?
Each widget is in its different file
Here is my code
main.dart
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: true,
home: HomeView(),
);
}
}
Home_views.dart
class HomeView extends ConsumerWidget {
const HomeView({Key? key}) : super(key: key);
#override
Widget build(BuildContext context, WidgetRef ref) {
TabController controller;
final ModelView = ref.watch(getFutureData);
return Consumer(
builder: (context, WidgetRef ref, _) {
return TabBarWidget;
}
);
}
}
Data_model.dart
class DataModel {
const DataModel({
required this.id,
required this.joke,
required this.categories,
});
final int id;
final String joke;
final String categories;
}
data_controllers.dart
final getFutureData = ChangeNotifierProvider<GetApiDATA>((ref) => GetApiDATA());
class GetApiDATA extends ChangeNotifier{
List<DataModel> ListOfDataModels = [];
GetApiDATA(){
getDataApi();
}
Future getDataApi() async {
ListOfDataModels = [];
try{
http.Response ApiResponse = await http.get(Uri.parse("https://v2.jokeapi.dev/joke/Programming?type=single&contains=joke&amount=10"));
if (ApiResponse.statusCode == 200) {
final body = jsonDecode(ApiResponse.body) as Map<String, dynamic>;
if (body['error'] == false) {
final jokes = body['jokes'];
for (final joke in jokes) {
final jokeMap = joke as Map<String, dynamic>;
print("jokeText is ${jokeMap['joke']}");
final id = jokeMap['id'] as int;
final jokeText = jokeMap['joke'] as String;
final categories = jokeMap['category'] as String;
ListOfDataModels.add(DataModel(id: id, joke: jokeText, categories: categories));
}
print("Length is ${ListOfDataModels.length}");
notifyListeners();
}
}
}
catch(e)
{
print(e.toString());
}
}
}
TabBarWidget.dart
import 'package:assignment_moe/Controllers/data_controllers.dart';
import 'package:assignment_moe/Widgets/TabViewWidget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
Widget TabBarWidget = Consumer(
builder: (context, WidgetRef ref, _) {
final ModelView = ref.watch(getFutureData);
return MaterialApp(
home: DefaultTabController(
length: 3,
child: Scaffold(
backgroundColor: Color(0XffF7F7F7),
appBar: AppBar(
backgroundColor: Color(0xff1B9C8F),
title: Text('Jokes API'),
),
body: Column(
children: [
Container(
margin: const EdgeInsets.only(top: 30, left: 10,right: 10),
height: 35,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color: Colors.white,
),
child: TabBar(
indicator: BoxDecoration(
color: Color(0xff1B9C8F),
borderRadius: BorderRadius.all(Radius.circular(10)),
),
labelColor: Colors.white,
unselectedLabelColor: Color(0xff1B9C8F),
tabs: [
Tab(
text: 'Programming',
),
Tab(
text: 'Dark',
),
Tab(
text: 'Spooky',
),
],
),
),
Expanded(
child: TabBarView(
children: [
TabViewWidget,
TabViewWidget,
TabViewWidget,
],
),
),
],
),
),
),
);
}
);
TabViewWidget.dart
import 'package:assignment_moe/Controllers/data_controllers.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
Widget TabViewWidget = Consumer (
builder: (context, WidgetRef ref, _) {
final ModelView = ref.watch(getFutureData);
return ModelView.ListOfDataModels.isEmpty ?
Center(child: CircularProgressIndicator(),) :
ListView.builder(
itemCount: ModelView.ListOfDataModels.length,
itemBuilder: (context, index) =>
Container(
margin: EdgeInsets.only(top: 20,left: 20,right: 20),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color: Colors.white,
),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: ListTile(
title: Text(ModelView.ListOfDataModels[index].categories
),
subtitle: Padding(
padding: const EdgeInsets.only(top: 10),
child: Text(ModelView.ListOfDataModels[index].joke),
),
leading: Container(
alignment: Alignment.center,
width: 35,
height: 35,
decoration: BoxDecoration(
color: Color(0xff1B9C8F),
borderRadius: BorderRadius.circular(20)),
child: Text(
ModelView.ListOfDataModels[index].id.toString(),
style: TextStyle(color: Colors.white),
),
),
),
),
),
);
}
);
Below is the screen shot
ANy help would be appreciated

Problem navigating to a route with Dialogflow and Flutter

I am working on an application with Flutter and Dialogflow and I want to make that when I say something specific to the bot, it will take me to a screen. That is, when writing 'depresion', I want it to take me to the context of the id to which 'depresion' corresponds. I have already created an Entitie in Dialogflow 'cual' with the id of the context I want to go to, but now I am not even shown the messages from the bot and it throws me this error.
UPDATE
This is the conversation that I usually have with the bot and it appears before placing the code that appears commented to use the parameters. The idea is that when that "3" appears, it takes me to the context screen that corresponds to that id "3" that I indicate in Navigator.pusnNamed
Flutter error
Dialogflow Entitie
class dialog_flow.dart
class FlutterFactsDialogFlow extends StatefulWidget {
FlutterFactsDialogFlow({Key key, this.title}) : super(key: key);
final String title;
#override
_FlutterFactsDialogFlowState createState() => new _FlutterFactsDialogFlowState();
}
class _FlutterFactsDialogFlowState extends State<FlutterFactsDialogFlow> {
final List<FactsMessage> _messages = <FactsMessage>[];
final TextEditingController _textController = new TextEditingController();
TtsProvider ttsProvider = TtsProvider();
Widget _queryInputWidget(BuildContext context) {
return Container(
child: Container(
margin: EdgeInsets.symmetric(horizontal: 8.0, vertical: 8.0),
child: Row(
children: <Widget>[
Flexible(
child: TextField(
controller: _textController,
onSubmitted: _submitQuery,
decoration: InputDecoration.collapsed(hintText: "Envia un mensaje"),
),
),
Container(
margin: EdgeInsets.symmetric(horizontal: 4.0),
child: IconButton(
icon: Icon(Icons.send),
onPressed: () => _submitQuery(_textController.text)),
),
],
),
),
);
}
void _dialogFlowResponse(context, query) async {
_textController.clear();
AuthGoogle authGoogle =
await AuthGoogle(fileJson: "assets/key.json").build();
Dialogflow dialogFlow =
Dialogflow(authGoogle: authGoogle, language: Language.spanish);
AIResponse response = await dialogFlow.detectIntent(query);
print(response.queryResult.parameters['cual']);
int id = int.parse(response.queryResult.parameters['cual']);
Navigator.pushNamed(context, 'home', arguments: id);
FactsMessage message = FactsMessage(
text: response.getMessage() ??
CardDialogflow(response.getListMessage()[0]).title,
name: "PsyBot",
type: false,
);
ttsProvider.hablar(response.getMessage());
setState(() {
_messages.insert(0, message);
});
}
void _submitQuery(String text) {
_textController.clear();
FactsMessage message = new FactsMessage(
text: text,
name: "TĂș",
type: true,
);
setState(() {
_messages.insert(0, message);
});
_dialogFlowResponse(context, text);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text("PsyBot"),
),
body: Column(children: <Widget>[
Flexible(
child: ListView.builder(
padding: EdgeInsets.all(8.0),
reverse: true, //Para mantener los Ășltimos mensajes al final
itemBuilder: (_, int index) => _messages[index],
itemCount: _messages.length,
)),
Divider(height: 1.0),
Container(
decoration: new BoxDecoration(color: Theme.of(context).cardColor),
child: _queryInputWidget(context),
),
]),
);
}
}
class fact_message.dart
class FactsMessage extends StatelessWidget {
FactsMessage({this.text, this.name, this.type});
final String text;
final String name;
final bool type;
List<Widget> botMessage(context) {
return <Widget>[
Container(
margin: const EdgeInsets.only(right: 16.0),
child: CircleAvatar(child: Text('Bot')),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(this.name,
style: TextStyle(fontWeight: FontWeight.bold)),
Container(
margin: const EdgeInsets.only(top: 5.0),
child: Text(text),
),
],
),
),
];
}
List<Widget> userMessage(context) {
return <Widget>[
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Text(this.name, style: Theme.of(context).textTheme.subtitle1),
Container(
margin: const EdgeInsets.only(top: 5.0),
child: Text(text),
),
],
),
),
Container(
margin: const EdgeInsets.only(left: 16.0),
child: CircleAvatar(child: new Text(this.name[0])),
),
];
}
#override
Widget build(BuildContext context) {
return new Container(
margin: const EdgeInsets.symmetric(vertical: 10.0),
child: new Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: this.type ? userMessage(context) : botMessage(context),
),
);
}
}
class home_page.dart
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
PageController pageController = PageController(initialPage: 0);
int pageChanged = 0;
TtsProvider ttsProvider = TtsProvider();
#override
Widget build(BuildContext context) {
final preguntaP = Provider.of<PreguntaProvider>(context);
final int idTest = ModalRoute.of(context).settings.arguments;
return Scaffold(
appBar: AppBar(
title: Text('Home Page'),
actions: [
IconButton(icon: Icon(Icons.arrow_forward_ios), onPressed: (){
pageController.nextPage(duration: Duration(milliseconds: 150), curve: Curves.bounceInOut );
})
],
),
body: FutureBuilder<List<Pregunta>>(
future: preguntaP.fetchPreguntas(idTest),
builder: (context, AsyncSnapshot<List<Pregunta>> snapshot) {
if (snapshot.hasData){
// ttsprovider
//ttsProvider.hablar("Prueba");
List<Pregunta> preg = snapshot.data;
return PageView(
physics: new NeverScrollableScrollPhysics(),
pageSnapping: true,
reverse: false,
controller: pageController,
onPageChanged: (index){
setState(() {
pageChanged = index;
});
},
children: armarPreguntas(preg),
);
} else{
return Center(child: CircularProgressIndicator());
//return Container();
}
}
),
);
}
List<Widget> armarPreguntas(List<Pregunta> listaPreguntas){
final List<Widget> listadoWidget = [];
for (Pregunta item in listaPreguntas) {
listadoWidget.add(Pagina(item, pageController));
}
return listadoWidget;
}
}

Stuck on being able to view detailed information from a list in flutter app

I have a louded information in RealTime database in format for example:
record
0
Club: "Club1"
Name: "Ronaldo"
Place: "London"
date: "25.07.2020"
email: "flutter#gmail.com"
phone: "12345678"
I have created a list that consists of names and clubs and I want to go to the full information according to the form by clicking on the Name, but I can't write the code. Please help to the new programmer
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:.../anketa/tile.dart';
class Anketa extends StatefulWidget {
Anketa({Key key, this.title}) : super(key: key);
final String title;
#override
_AnketaState createState() => _AnketaState();
}
class _AnketaState extends State<Anketa> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Registration form",
style: TextStyle(
fontWeight: FontWeight.w200,
fontSize: 30,
fontFamily: 'Roboto',
fontStyle: FontStyle.italic)),
RegisterStudent(),
]),
)),
);
}
}
class RegisterStudent extends StatefulWidget {
RegisterStudent({Key key}) : super(key: key);
#override
_RegisterStudentState createState() => _RegisterStudentState();
}
class _RegisterStudentState extends State<RegisterStudent> {
final _formKey = GlobalKey<FormState>();
final listOfClubs = ["Club1", "Club2", "Club3", "Club4"];
String dropdownValue = "Club1";
final clubController = TextEditingController();
final nameController = TextEditingController();
final placeController = TextEditingController();
final dateController = TextEditingController();
final emailController = TextEditingController();
final phoneController = TextEditingController();
final rawController = TextEditingController();
final dbRef = FirebaseDatabase.instance.reference().child("record");
#override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(children: <Widget>[
Padding(
padding: EdgeInsets.all(20.0),
child: TextFormField(
controller: nameController,
decoration: InputDecoration(
labelText: "EnterName",
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return "Enter name";
}
return null;
},
),
),
Padding(
padding: EdgeInsets.all(20.0),
child: DropdownButtonFormField(
value: dropdownValue,
icon: Icon(Icons.arrow_downward),
decoration: InputDecoration(
labelText: "Club",
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
items: listOfClubs.map((String value) {
return new DropdownMenuItem<String>(
value: value,
child: new Text(value),
);
}).toList(),
onChanged: (String newValue) {
setState(() {
this.dropdownValue = newValue;
});
},
validator: (value) {
if (value.isEmpty) {
return 'Club';
}
return null;
},
),
),
Padding(
padding: EdgeInsets.all(20.0),
child: TextFormField(
keyboardType: TextInputType.number,
controller: dateController,
decoration: InputDecoration(
labelText: "Date",
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Date';
}
return null;
},
),
),
Padding(
padding: EdgeInsets.all(20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
RaisedButton(
color: Colors.lightBlue,
onPressed: () {
if (_formKey.currentState.validate()) {
dbRef.push().set({
"Name": nameController.text,
"date": dateController.text,
"Club": dropdownValue
}).then((_) {
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Add')));
dateController.clear();
nameController.clear();
}).catchError((onError) {
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text(onError)));
});
}
},
child: Text('Enter'),
),
RaisedButton(
color: Colors.amber,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ListOfNames()),
);
},
child: Text('Go to'),
),
],
)),
])));
}
#override
void dispose() {
super.dispose();
dateController.dispose();
nameController.dispose();
}
}
and this is the second page with a list, from where I want to go to full information
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
class ListOfNames extends StatelessWidget {
final dbRef = FirebaseDatabase.instance.reference().child("record");
List<Map<dynamic,dynamic>> lists = List();
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey.shade300,
appBar: AppBar(
backgroundColor: Colors.deepPurple,
title: Text("List of students"),
),
body: StreamBuilder(
stream: dbRef.onValue,
builder: (context, AsyncSnapshot<Event> snapshot) {
if (snapshot.hasData) {
lists.clear();
DataSnapshot dataValues = snapshot.data.snapshot;
Map<dynamic, dynamic> values = dataValues.value;
values.forEach((key, values) {
lists.add(values);
});
return new ListView.builder(
shrinkWrap: true,
itemCount: lists.length,
itemBuilder: (BuildContext context, int index) {
itemBuilder: (BuildContext context, int index) {
return ListTile(
title:Text(lists[index]["Name"], style: TextStyle(height: 2.5, fontSize:20.0),),
subtitle:Text(lists[index]['Club'], style: TextStyle(fontSize:16.0),),
onTap: (){
// in this line i have a problem...
Navigator.push(context, MaterialPageRoute(builder: (context) => DetailPage(snapshot.data[index]['Name']),
)
);
},
);
});
}
return CircularProgressIndicator();
})
);
}
}
I want to create such a page:
class DetailPage extends StatelessWidget {
List<Map<dynamic,dynamic>> data ;
DetailPage ({this.data});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(data.name),
// here I want to show the all information from the form about one person from the list
),
);
}
}
In the body of the scaffold of 'DetailsPage' use 'Card' widget with 'Text' widgets to show the info. Like Card(child:Text('${data.clubLoc}').

How to create loading screen when i click on login button and page should be redirect to Dashboard?

Everyone I am new in flutter. How can create loading screen on login page. when i click on login button then it should be redirect on Dashboard with loading screen. I am trying to create loading screen in flutter. When I click on login button then loading screen show be show and after loading screen it should be redirect on Dashboard.....
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutternew/dashboard.dart';
import 'package:flutternew/forget_password.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'bezierContainer.dart';
class Home extends StatefulWidget {
Home({Key key, this.title}) : super(key: key);
final String title;
#override
_HomeState createState() => _HomeState();
}
class ShowLoading extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text('Loading View'),
),
body: Center(
child: _circularProgressIndicator(),
));
}
Widget _circularProgressIndicator() {
return CircularProgressIndicator();
}
}
class _HomeState extends State<Home> {
bool _isLoading = false;
GlobalKey<FormState> _formKey = GlobalKey<FormState>(debugLabel: '_homekey');
final _scaffoldKey = GlobalKey<ScaffoldState>();
String _email;
String _password;
final TextEditingController emailController = new TextEditingController();
final TextEditingController passwordController = new TextEditingController();
var modal = Container();
showAlertDialog(BuildContext context, String message) {
Widget okButton = FlatButton(
child: Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
);
AlertDialog alert = AlertDialog(
title: Text("Error"),
content: Text(message),
actions: [
okButton,
],
);
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
Widget _formSetupWidget(BuildContext context) {
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(
controller: emailController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Username",
hintStyle: TextStyle(color: Colors.grey, fontSize: 25),
fillColor: Color(0xFFFAFAfA),
filled: true),
keyboardType: TextInputType.emailAddress,
validator: (val) {
if (val.length == 0)
return "Please enter email";
else if (!val.contains("#"))
return "Please enter valid email";
else
return null;
},
onSaved: (val) => _email = val,
),
SizedBox(
height: 15,
),
TextFormField(
controller: passwordController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Password",
hintStyle: TextStyle(color: Colors.grey, fontSize: 25),
fillColor: Color(0xFFFAFAfA),
filled: true),
obscureText: true,
validator: (val) {
if (val.length == 0)
return "Please enter password";
else if (val.length <= 5)
return "Your password should be more then 6 char long";
else
return null;
},
onSaved: (val) => _password = val,
),
Padding(
padding: const EdgeInsets.only(top: 20.0),
),
ButtonTheme(
minWidth: 500.0,
height: 60.0,
child: RaisedButton(
child: new Text("Login",
style: TextStyle(color: Colors.white, fontSize: 23.0)),
color: Colors.blueAccent,
highlightColor: Colors.blueAccent,
onPressed: () {
if (emailController.text != " " ||
passwordController.text != " ") {
signIn(emailController.text, passwordController.text);
}
},
),
),
],
),
);
}
signIn(String email, pass) async {
int visible = 0;
final sharedPreferences = await SharedPreferences.getInstance();
Map data = {'email': email, 'password': pass};
var jsonResponse = null;
var response = await http
.post("https://abcdef.com/iot/api/login", body: data);
if (response.statusCode == 200) {
jsonResponse = json.decode(response.body);
if (jsonResponse != null) {
if (jsonResponse['success'] == 1) {
sharedPreferences.setString("token", jsonResponse['data']['token']);
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (BuildContext context) => Dashboard()),
(Route<dynamic> route) => false);
} else {
String message = jsonResponse['message'];
showAlertDialog(context, message);
}
}
} else {
setState(() {
_isLoading = false;
});
print(response.body);
}
}
#override
Widget build(BuildContext context) {
Center(
child: SpinKitWave(color: Colors.white, type: SpinKitWaveType.start),
);
var assetsImage = new AssetImage('assets/logo.png');
var image = new Image(image: assetsImage, width: 150.0, height: 150.0);
final height = MediaQuery.of(context).size.height;
return Scaffold(
body: Container(
height: height,
color: Colors.white,
child: Stack(
children: <Widget>[
Positioned(
top: -height * .15,
right: -MediaQuery.of(context).size.width * .4,
child: BezierContainer()),
Container(
padding: EdgeInsets.symmetric(horizontal: 20),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(height: 70),
new Center(
child: image,
),
SizedBox(height: 20),
_formSetupWidget(context),
Container(
padding: EdgeInsets.symmetric(vertical: 10),
alignment: Alignment.centerRight,
child: FlatButton(
child: Text("Forgot Password?"),
onPressed: () {
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (BuildContext context) =>
Forget_password()),
(Route<dynamic> route) => false);
},
),
),
SizedBox(height: height * .055),
],
),
),
),
],
),
));
}
}
Create class
class LoaderDialog {
static Future<void> showLoadingDialog(BuildContext context, GlobalKey key) async {
var wid = MediaQuery.of(context).size.width / 2;
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return Padding(
padding: EdgeInsets.only(left: 130 , right: 130),
child: Dialog(
key: key,
backgroundColor: Colors.white,
child: Container(
width: 60.0,
height: 60.0,
child: Image.asset(
'images/loaderOld.gif',
height: 60,
width: 60,
),
)
),
);
},
);
}
}
How to Call:
In your Class(Where you want to show the loader).
final GlobalKey<State> _LoaderDialog = new GlobalKey<State>();
// Show
LoaderDialog.showLoadingDialog(context, _LoaderDialog);
// Hide
Navigator.of(_LoaderDialog.currentContext,rootNavigator: true).pop();

Categories

Resources