click on raised button failed without any error - flutter

I have a very Strange error in my app. When i try to click on the button "PARIER" it does absolutely Nothing and i Don't see why. I called Prono_Match() but it doesn't work at all, i have no syntax errors and it does Nothing. I have tried called an other page but it is same. Why it ignores totally the call of Prono_Match ??? It is very very Strange :(
My code :
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'menu_member.dart';
import 'globals.dart' as globals;
import 'appbar_draw.dart';
import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:intl/intl.dart';
import 'prono_match.dart';
// Create a Form widget.
class Affiche_Matchs extends StatefulWidget {
#override
_Affiche_Matchs_State createState() {
return _Affiche_Matchs_State();
}
}
// Create a corresponding State class.
// This class holds data related to the form.
class _Affiche_Matchs_State extends State<Affiche_Matchs> {
#override
bool load=false;
bool visible=false;
String idmatch="";
String prono="";
List<String> radioValues = [];
Future<List<Match>> grid;
Future <List<Match>> Liste_Match_Display() async {
// SERVER LOGIN API URL
var url = 'https://www.easytrafic.fr/game_app/display_matchs.php';
var data = {
'id_membre': globals.id_membre,
};
var data_encode = jsonEncode(data);
// Starting Web API Call.
var response = await http.post(url,body: data_encode,headers: {'content-type': 'application/json','accept': 'application/json','authorization': globals.token});
// Getting Server response into variable.
var jsondata = json.decode(response.body);
List<Match> Matchs = [];
var i=0;
for (var u in jsondata) {
i=i+1;
Match match = Match(u["id"],u["equipe1"],u["equipe2"],u["dated"],u["heured"]);
Matchs.add(match);
radioValues.add("");
}
return Matchs;
}
void initState() {
super.initState();
grid = Liste_Match_Display();
}
#override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: <Color>[
Colors.blue[300],Colors.blue[400]
],
),
),
),
Scaffold(
appBar: drawappbar(true),
backgroundColor: Colors.transparent,
drawer: new DrawerOnly(className: Affiche_Matchs()),
body:
Center(
child : Column(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height*0.8,
width: MediaQuery.of(context).size.width,
child:
FutureBuilder(
future: grid,
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting: return new Center(child: new CircularProgressIndicator(),);
default:
if(snapshot.hasError) {
return new Center(child: new Text('Error: ${snapshot.error}'),);
}
else {
List<Match> values = snapshot.data;
if (values.isEmpty) {
return Container(
child: Center(
child: Text("Aucun match disponible !!!",style: TextStyle(color: Colors.white))
)
);
}
else {
Match lastitem;
lastitem=values[0];
int i=0;
return ListView.builder(itemCount: values.length,itemBuilder: (_,index) {
bool header = lastitem.date_debut !=
values[index].date_debut;
lastitem = values[index];
var parsedDate = DateTime.parse(values[index].date_debut);
final formatter = new DateFormat('dd/MM/yyyy');
var dat = formatter.format(parsedDate);
return Column(
children: [
(header || index == 0)
?
Container(
height: 30,
margin: EdgeInsets.only(top:10),
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
border: Border.all(
color: Colors.blue[700],
width: 2,
),
color: Colors.blue[700]
),
child : new Text(dat,textAlign: TextAlign.center,style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.w500,color: Colors.white),),
)// here// display header
:
Container(),
Container(
margin: EdgeInsets.only(top:20,bottom:20),
child: Center(
child: Text(values[index].heure_debut,style: TextStyle(color: Colors.white)),
),
),
Container(
margin: const EdgeInsets.only(bottom:10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
child: Text(values[index].equipe1+" - "+values[index].equipe2,style: TextStyle(fontSize:10,color: Colors.white)),
),
]
),
),
Container(
margin: const EdgeInsets.only(left:5),
child: RaisedButton(
color: Colors.green,
textColor: Colors.white,
padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
child: Text('PARIER'),
onPressed: () {
idmatch=values[index].id;
print(idmatch);
setState(() {
visible=true;
});
Prono_Match(idmatch: idmatch);
},
),
),
]
);
}
);
}
};
};
}
),
),
]
)
)
)
]
);
}
}
class Match {
final String id;
final String equipe1;
final String equipe2;
final String date_debut;
final String heure_debut;
const Match(this.id,this.equipe1, this.equipe2,this.date_debut,this.heure_debut);
}

I'm guessing you're trying to show Prono_Match page when pressing on the button, although that's not how you call a page in flutter, instead do this :
onPressed: () {
idmatch=values[index].id;
print(idmatch);
setState(() {
visible=true;
});
Navigator.push(context,MaterialPageRoute(builder: (context)=>Prono_Match(idmatch: idmatch),),
);
},

Related

How do I add a search box in Flutter?

I have this class name index which pushes some data from some web to a list. I just want to filter out the results by name for example. I am a newbie in flutter and it would be appreciated some help
you can see below how we fetch data from fetchUser>getBody>getCard
Inside getCard there is my "item['name']" that I would like to look up
import 'package:flutter/cupertino.dart';
//import 'package:flutter/foundation.dart' as nose;
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_app/pages/theme/color.dart';
class IndexPage extends StatefulWidget {
#override
_IndexPageState createState() => _IndexPageState();
}
class _IndexPageState extends State<IndexPage> {
List users = [];
bool isLoading = false;
#override
void initState() {
super.initState();
this.fetchUser();
}
fetchUser() async {
setState(() {
isLoading = true;
});
var url = "https://randomuser.me/api/?results=1000";
var response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
var items = json.decode(response.body)['results'];
setState(() {
users = items;
isLoading = false;
});
} else {
setState(() {
users = [];
isLoading = false;
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Usuarios'),
centerTitle: true,
),
body: getBody());
}
Widget getBody() {
if (users.contains(null) || users.length < 0 || isLoading) {
return Center(
child: CircularProgressIndicator(
valueColor: new AlwaysStoppedAnimation<Color>(Colors.red)));
}
return ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
return getCard(users[index]);
});
}
String searchString = "";
Widget getCard(item) {
var fullName = item['name']['title'] +
" " +
item['name']['first'] +
" " +
item['name']['last'];
var email = item['email'];
var profileUrl = item['picture']['large'];
return Padding(
padding: const EdgeInsets.all(10.0),
child: Card(
child: ListTile(
title: Row(
children: <Widget>[
Container(
width: 60,
height: 60,
decoration: BoxDecoration(
color: primary,
borderRadius: BorderRadius.circular(60 / 2),
image: DecorationImage(
fit: BoxFit.cover,
image: NetworkImage((profileUrl.toString())))),
),
SizedBox(
width: 20,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(fullName.toString(),
style: TextStyle(fontFamily: 'Calibri')),
SizedBox(
height: 11,
),
Text(email, style: TextStyle(fontSize: 10))
])
],
),
),
),
);
}
}

List View in Flutter

I've been having trouble understanding how to correctly list of all the items from the API call, I have now made it to display the first from the list of the API, by adding the index [0] after the API response. I realize I can do that with the itemCount which I currently had it set at 1 since I can't seem to comprehend how to use the .length option that lists all of the item from the API. Here is the code:
API CALL:
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:practice/models/jobs.dart';
Future<JobData> fetchJobs() async {
final response = await http.get('https://jsonplaceholder.typicode.com/posts');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return JobData.fromJson(jsonDecode(response.body)[0]);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load jobs');
}
}
THE JOB MODEL:
import 'package:flutter/foundation.dart';
class JobData extends ChangeNotifier {
final int userId;
final int id;
final String title;
final String body;
JobData({this.userId, this.id, this.title, this.body});
factory JobData.fromJson(Map<String, dynamic> json) {
return JobData(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
AND THE WIDGET WHERE IT IS RENDERED:
import 'package:flutter/material.dart';
import 'package:practice/models/jobs.dart';
import 'package:provider/provider.dart';
import 'package:practice/services/api_calls.dart';
class JobList extends StatefulWidget {
#override
_JobListState createState() => _JobListState();
}
class _JobListState extends State<JobList> {
Future<JobData> futureJobs;
#override
void initState() {
super.initState();
futureJobs = fetchJobs();
}
#override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(
'Today',
),
SizedBox(
height: 12.0,
),
Container(
decoration: BoxDecoration(
color: Colors.grey[300],
borderRadius: BorderRadius.only(
topLeft: Radius.circular(12.0),
topRight: Radius.circular(12.0),
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(left: 15.0),
child: Text(
'Jobs #1',
style: TextStyle(fontWeight: FontWeight.w700),
),
),
FlatButton(
textColor: Colors.blue[700],
minWidth: 0,
child: Text('View'),
onPressed: () {
},
),
],
),
),
Container(
padding: EdgeInsets.all(18.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(12.0),
bottomRight: Radius.circular(12.0),
),
),
child: Consumer<JobData>(
builder: (context, jobData, child) {
return SizedBox(
height: 200,
child: FutureBuilder<JobData>(
future: futureJobs,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: 1,
itemBuilder: (context, index) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('${snapshot.data.userId}',
style: TextStyle(color: Colors.black),
Text(
'${snapshot.data.id}',
style: TextStyle(color: Colors.black),
),
Text(
'${snapshot.data.title}',
style: TextStyle(color: Colors.black),
),
Text(
'${snapshot.data.body}',
style: TextStyle(color: Colors.black),
),
],
);
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
),
);
},
),
),
SizedBox(
height: 16.0,
),
],
);
}
}
Do you I need to make a list out of the returned API response first and then display it's length?
Thanks in advance!
Try changing this..
Future<List<JobData>> fetchJobs() async {
List<JobData> jobs = new List();
final response = await http.get('https://jsonplaceholder.typicode.com/posts');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
var jobsJson = jsonDecode(response.body);
for(int i = 0; i < jobsJson.length; i++) {
jobs.add(JobData.fromJson(jobsJson[i]));
}
return jobs;
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load jobs');
}
}
then..
Future<List<JobData>> futureJobs;
inside ListView
itemCount: futureJobs.length,
then take each job from futureJobs list using index and show in ListView()

Flutter Streambuilder + Firestore returning null snapshot after using background location plugin

After the addition of this plugin (https://pub.dev/packages/carp_background_location), all my Streambuilders with Firestore stopped working. It returns null for all snapshot.data of my app.
Situation:
StreamBuilder works for all collections from Firestore on the app
Use carp_background_location like on the example/lib/main.dart on a specific screen
All streams return null on snapshot.data on the app
Normal behaviour just comes back when I close the app and run main.dart again (and don't run background location).
This was the only plugin that worked for the case I needed with location (background), so changing the plugin would not be ideal. Actually I suspect that forcing the background work is causing this (maybe other plugins inside this plugin), but I am not able to find the answer. No error or warn is shown, what is making it more difficult.
Could someone help me on this please? Is there any function to get the "normal" behaviour after using the background plugin?
On this screen I am listening to Firestore with Streambuilder:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:provider/provider.dart';
import 'begin_activity.dart';
class MainApp extends StatefulWidget {
#override
_MainAppState createState() => _MainAppState();
}
class _MainAppState extends State<MainApp> {
final _firestore = FirebaseFirestore.instance;
#override
Widget build(BuildContext context) {
void moveToPage() async {
await Navigator.push(
context,
MaterialPageRoute(builder: (context) => LocationStreamWidget()),
);
}
return Scaffold(
backgroundColor: Colors.grey,
floatingActionButton: FloatingActionButton(
mini: true,
onPressed: () {
moveToPage();
},
child: Icon(
Icons.add,
color: Colors.white,
size: 30,
),
backgroundColor: Colors.blue,
),
body: Stack(
children: [
Padding(
padding: EdgeInsets.fromLTRB(10, 0, 10, 10),
child: StreamBuilder(
stream: _firestore
.collection('users')
.doc('user_id')
.collection('corridas')
.orderBy('date', descending: true)
.snapshots(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.data == null) {
return Center(
child: SpinKitCubeGrid(
size: 51.0, color: Colors.blue,));
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else if (snapshot.data.docs.isEmpty) {
return Container(
height: MediaQuery.of(context).size.height * 0.55,
child: Padding(
padding: const EdgeInsets.fromLTRB(8.0, 50.0, 8.0, 0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Icon(
Icons.directions_run,
size: 50,
),
Text(
Strings.noTracks,
style: TextParameters.noActivities,
textAlign: TextAlign.center,
),
],
),
));
} else if (snapshot.hasData) {
return Column(
children: <Widget>[
Expanded(
child: ListView.builder(
itemCount: snapshot.data.docs.length,
itemBuilder: (context, index) {
final docAux = snapshot.data.docs;
return Container(
child: Column(
children: [
Text(_printDate(docAux[index]['date'])
.toString()),
Text(
docAux[index]['distance'].toStringAsFixed(2),
),
],
));
},
),
),
],
);
} else {
return Center(
child: SpinKitCubeGrid(
size: 51.0, color: Colors.blue,));
}
},
),
),
],
),
);
}
}
String _printTime(int timeInMilliseconds) {
String twoDigits(int n) {
if (n >= 10) return "$n";
return "0$n";
}
Duration duration = Duration(milliseconds: timeInMilliseconds);
String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
if (duration.inHours > 0)
return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
else
return "$twoDigitMinutes:$twoDigitSeconds";
}
String _printDate(Timestamp timestamp) {
var formattedAux = timestamp.toDate();
var day = formattedAux.day.toString().padLeft(2, '0');
var month = formattedAux.month.toString().padLeft(2, '0');
var year = formattedAux.year;
return '$year' + '-' + '$month' + '-' + '$day';
}
This screen is the one I am using background location and when I go back to MainApp, Streambuilder doesn't update and returns snapshot.data null:
import 'dart:async';
import 'package:carp_background_location/carp_background_location.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:provider/provider.dart';
import 'package:timer_builder/timer_builder.dart';
class LocationStreamWidget extends StatefulWidget {
#override
State<LocationStreamWidget> createState() => LocationStreamState();
}
enum LocationStatus { UNKNOWN, RUNNING, STOPPED }
class LocationStreamState extends State<LocationStreamWidget> {
final globalKey = GlobalKey<ScaffoldState>();
LocationManager locationManager = LocationManager.instance;
Stream<LocationDto> dtoStream;
StreamSubscription<LocationDto> dtoSubscription;
LocationStatus _status = LocationStatus.UNKNOWN;
// Definitions
List<LocationDto> _allPositions;
List<LocationDto> _positions = <LocationDto>[];
double totalDistance;
double intermediaryDist;
double distAux;
double distLatLong;
int totalTime;
int intermediaryTime;
int timeAux;
List<LocationDto> _allPositionsInter;
List<LocationDto> _positionsInter = <LocationDto>[];
final _firestore = FirebaseFirestore.instance;
#override
void initState() {
super.initState();
locationManager.interval = 1;
locationManager.distanceFilter = 0;
dtoStream = locationManager.dtoStream;
totalDistance = 0.0;
intermediaryDist = 0.0;
totalTime = 0;
intermediaryTime = 0;
_positions.clear();
}
void onData(LocationDto dto) {
setState(() {
if (_status == LocationStatus.UNKNOWN) {
_status = LocationStatus.RUNNING;
}
_positions.add(dto);
_allPositions = _positions;
print(_positions.length);
_positionsInter.add(dto);
_allPositionsInter = _positionsInter;
final firstTime = DateTime.fromMillisecondsSinceEpoch(
_allPositionsInter.first.time ~/ 1)
.toLocal();
final lastTime =
DateTime.fromMillisecondsSinceEpoch(_allPositionsInter.last.time ~/ 1)
.toLocal();
totalTime =
intermediaryTime + lastTime.difference(firstTime).inMilliseconds;
print(totalTime);
});
}
void start() async {
if (dtoSubscription != null) {
dtoSubscription.resume();
}
dtoSubscription = dtoStream.listen(onData);
await locationManager.start();
setState(() {
_status = LocationStatus.RUNNING;
});
}
void pause() async {
setState(() {
intermediaryDist = totalDistance;
intermediaryTime = totalTime;
_positionsInter.clear();
_allPositionsInter.clear();
_status = LocationStatus.STOPPED;
});
dtoSubscription.cancel();
await locationManager.stop();
}
String _printTime(int timeInMilliseconds) {
String twoDigits(int n) {
if (n >= 10) return "$n";
return "0$n";
}
Duration duration = Duration(milliseconds: timeInMilliseconds);
String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
if (duration.inHours > 0)
return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
else
return "$twoDigitMinutes:$twoDigitSeconds";
}
#override
void dispose() {
if (dtoSubscription != null) {
dtoSubscription.cancel();
dtoSubscription = null;
_allPositions.clear();
_allPositionsInter.clear();
totalDistance = 0;
intermediaryDist = 0.0;
distAux = 0.0;
_status = LocationStatus.STOPPED;
totalTime = 0;
intermediaryTime = 0;
locationManager.start();
if (_positions != null) {
_positions.clear();
_positionsInter.clear();
_allPositionsInter.clear();
locationManager.start();
}
}
super.dispose();
}
#override
Widget build(BuildContext context) {
return TimerBuilder.periodic(Duration(milliseconds: 500),
builder: (context) {
return Scaffold(
key: globalKey,
body: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Expanded(
child: Container(
child: FutureBuilder(
future: locationManager.checkIfPermissionGranted(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.data == false) {
return Text('No gps');
}
return Container(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
'${totalTime != null ? _printTime(totalTime) : '0'}',
),
_getButtons(user),
],
),
),
);
}),
),
),
],
),
);
});
}
Widget _getButtons(UserClasse user) {
final _currentDate = _positions?.isNotEmpty ?? false
? (DateTime.fromMillisecondsSinceEpoch(_positions[0].time ~/ 1)
.toLocal())
: 0;
if (dtoSubscription == null)
return Padding(
padding: EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
Expanded(
child: RaisedButton(
child: Text('Begin'),
color: Colors.blue,
onPressed: start),
),
],
),
);
else if (_status == LocationStatus.RUNNING)
return Padding(
padding: EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
Expanded(
child: RaisedButton(
child: Text('Pause'),
color: Colors.blue,
onPressed: pause),
),
],
),
);
else if (_status == LocationStatus.STOPPED) {
return Padding(
padding: EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
Expanded(
child: RaisedButton(
child: Text('Back'),
color: Colors.blue,
onPressed: start),
),
SizedBox(
width: 15,
),
Expanded(
child: RaisedButton(
child: Text('Stop'),
color: Colors.blue,
onPressed: () {},
onLongPress: () async {
_firestore
.collection('users')
.doc('user_id')
.collection('corridas')
.add({
'date': _currentDate,
'distance': 41.7,
'pace': 1244,
'average_speed': 12,
'runtime': 14134,
'max_speed': 41,
'max_altitude': 13,
'delta_altitude': 13,
'lat_first': -23.213,
'long_first': -23.213,
'polylines': 'feaf',
'markers': [1, 2, 3],
});
Navigator.of(context).pop();
},
),
),
],
),
);
} else
return Padding(
padding: EdgeInsets.all(8.0),
child: Row(
children: <Widget>[
Expanded(
child: RaisedButton(
child: Text('Start'),
color: Colors.blue,
onPressed: () {}),
),
],
),
);
}
}

How display a list of data order by date?

Here is the result now :
It is much better but i Don't know why BELSHINA BOBRUISK is not centered vertically. As you can see the others team are centered vertically. FC SMOELVITCHI is centered. Strange. Too i would like display the "2020-06-01" in mobile format so if it is french mobile it will be "01-06-2020".
And another question i Don't know why my mobile app use the theme with fontfamily but not all. I have some pages with a part of data in good family font and the other part in default font, its is really strange
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:flutter_app/menu_member.dart';
import 'package:flutter_app/globals.dart' as globals;
import 'package:flutter_app/appbar_draw.dart';
// Create a Form widget.
class Affiche_Matchs extends StatefulWidget {
#override
_Affiche_Matchs_State createState() {
return _Affiche_Matchs_State();
}
}
// Create a corresponding State class.
// This class holds data related to the form.
class _Affiche_Matchs_State extends State<Affiche_Matchs> {
#override
final _formKey = GlobalKey<FormState>();
List<String> radioValues = [];
Future<List<Match>> grid;
Future <List<Match>> Liste_Match_Display() async {
// SERVER LOGIN API URL
var url = 'https://www.easytrafic.fr/game_app/display_matchs.php';
// Starting Web API Call.
var response = await http.get(url,headers: {'content-type': 'application/json','accept': 'application/json','authorization': globals.token});
// Getting Server response into variable.
var jsondata = json.decode(response.body);
List<Match> Matchs = [];
var i=0;
for (var u in jsondata) {
i=i+1;
Match match = Match(u["id"],u["equipe1"],u["equipe2"],u["type_prono"],u["date_debut"],u["heure_debut"]);
Matchs.add(match);
radioValues.add("");
}
return Matchs;
}
void initState() {
grid = Liste_Match_Display();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: drawappbar(true),
drawer: new DrawerOnly(className: Affiche_Matchs()),
body:
Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child:
FutureBuilder(
future: grid,
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting: return new Center(child: new CircularProgressIndicator(),);
default:
if(snapshot.hasError) {
return new Center(child: new Text('Error: ${snapshot.error}'),);
}
else {
List<Match> values = snapshot.data;
Match lastitem;
lastitem=values[0];
if (values.isEmpty) {
return Container(
child: Center(
child: Text("Aucun match disponible !!!")
)
);
}
else {
return Form(
key: _formKey,
child: ListView.builder(itemCount: values.length,itemBuilder: (_,index) {
bool header = lastitem.date_debut !=
values[index].date_debut;
lastitem = values[index];
return Column(
children: [
(header || index == 0)
?
Container(
height: 30,
margin: EdgeInsets.only(top:10),
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
border: Border.all(
color: Colors.blue[700],
width: 2,
),
color: Colors.blue[700]
),
child : new Text(values[index].date_debut,textAlign: TextAlign.center,style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.w500,color: Colors.white),),
)// here display header
:
Container(),
Container(
margin: EdgeInsets.only(top:20,bottom:20),
child: Center(
child: Text(values[index].heure_debut),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(values[index].equipe1,style: TextStyle(fontSize:12)),
draw_grid("1", index, values[index].typeprono),
draw_grid("N", index, values[index].typeprono), //
draw_grid("2", index, values[index].typeprono), //
Text(values[index].equipe2,style: TextStyle(fontSize:12)),
]
),
]
);
}
)
);
}
};
};
}
),
),
);
}
draw_grid (String choix, int index,String type_prono) {
if (type_prono.contains(choix)) {
return new InkWell(
onTap: () {
setState(() {
if (radioValues[index] == choix) {
radioValues[index] = "";
}
else {
radioValues[index] = choix;
}
});
print(radioValues);
},
child:
Container(
height: 30.0,
width: 30.0,
margin: EdgeInsets.only(right: 2,left: 2),
child: new Center(
child: new Text(choix,
style: new TextStyle(
color:
radioValues[index] == choix ? Colors.white : Colors.red,
//fontWeight: FontWeight.bold,
fontSize: 18.0, fontWeight: FontWeight.w900)),
),
decoration: new BoxDecoration(
color: radioValues[index] == choix
? Colors.red
: Colors.white,
border: new Border.all(
width: 2.0,
color: radioValues[index] == choix
? Colors.red
: Colors.red),
borderRadius: const BorderRadius.all(const Radius.circular(5)),
),
),
);
}
else {
return Text("");
}
}
}
class Match {
final String id;
final String equipe1;
final String equipe2;
final String typeprono;
final String date_debut;
final String heure_debut;
const Match(this.id,this.equipe1, this.equipe2, this.typeprono,this.date_debut,this.heure_debut);
}
You have to sort you list base on date and then you can display by checking you have to display header or not.
Following code help you to understand more and then you can implement.
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
class DeleteWidget extends StatefulWidget {
#override
_DeleteWidgetState createState() => _DeleteWidgetState();
}
class _DeleteWidgetState extends State<DeleteWidget> {
final _formKey = GlobalKey<FormState>();
List<String> radioValues = [];
Future<List<Match>> grid;
Future<List<Match>> Liste_Match_Display() async {
// SERVER LOGIN API URL
var url = 'https://www.easytrafic.fr/game_app/display_matchs.php';
// Starting Web API Call.
var response = await http.get(url, headers: {
'content-type': 'application/json',
'accept': 'application/json',
'authorization':
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOjE1ODg5NTQ0NDgsImlhdCI6MTU4ODk1NDQ0OCwiZXhwIjoxNTg5MDE0NDQ4LCJkYXRhIjp7ImlkIjoiMSIsImVtYWlsIjoicGFzMzBAbmV0Y291cnJpZXIuY29tIn19.-jcyoxtkNVWWagune6EOjInjBgObyxf9gweXJrA2MxLL5fRTW1pkFSFrJOW8uYzhVpaZ4CF9A-c_m8akUq74NA '
});
// Getting Server response into variable.
var jsondata = json.decode(response.body);
List<Match> Matchs = [];
var i = 0;
for (var u in jsondata) {
i = i + 1;
Match match = Match(u["id"], u["equipe1"], u["equipe2"], u["type_prono"],
u["date_debut"], u["heure_debut"]);
Matchs.add(match);
radioValues.add("");
}
return Matchs;
}
void initState() {
grid = Liste_Match_Display();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
// appBar: drawappbar(true),
//drawer: new DrawerOnly(className: Affiche_Matchs()),
body: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: FutureBuilder(
future: grid,
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return new Center(
child: new CircularProgressIndicator(),
);
default:
if (snapshot.hasError) {
return new Center(
child: new Text('Error: ${snapshot.error}'),
);
} else {
List<Match> values = snapshot.data;
Match lastitem;
lastitem = values[0];
if (values.isEmpty) {
return Container(
child: Center(
child: Text("Aucun match disponible !!!")));
} else {
return Form(
key: _formKey,
child: ListView.builder(
itemCount: values.length,
itemBuilder: (_, index) {
bool header = lastitem.date_debut !=
values[index].date_debut;
lastitem = values[index];
return Column(
children: [
(header || index == 0)
? Container(
height: 30,
margin: EdgeInsets.only(top: 10),
width: MediaQuery.of(context)
.size
.width,
decoration: BoxDecoration(
border: Border.all(
color: Colors.blue[700],
width: 2,
),
color: Colors.blue[700]),
child: new Text(
values[index].date_debut,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18.0,
fontWeight: FontWeight.w500,
color: Colors.white),
),
) // here display header
: Container(),
Text(values[index].heure_debut),
Text(values[index].equipe1),
Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
draw_grid("1", index,
values[index].typeprono),
draw_grid("N", index,
values[index].typeprono), //
draw_grid("2", index,
values[index].typeprono), //
],
),
Text(values[index].equipe2),
// here display whole item
],
);
}));
}
}
;
}
;
}),
),
);
}
draw_grid(String choix, int index, String type_prono) {
if (type_prono.contains(choix)) {
return new InkWell(
onTap: () {
setState(() {
if (radioValues[index] == choix) {
radioValues[index] = "";
} else {
radioValues[index] = choix;
}
});
print(radioValues);
},
child: Container(
height: 40.0,
width: 40.0,
child: new Center(
child: new Text(choix,
style: new TextStyle(
color:
radioValues[index] == choix ? Colors.white : Colors.red,
//fontWeight: FontWeight.bold,
fontSize: 18.0,
fontWeight: FontWeight.w900)),
),
decoration: new BoxDecoration(
color: radioValues[index] == choix ? Colors.red : Colors.white,
border: new Border.all(
width: 2.0,
color: radioValues[index] == choix ? Colors.red : Colors.red),
borderRadius: const BorderRadius.all(const Radius.circular(5)),
),
),
);
} else {
return Text("");
}
}
}
class Match {
final String id;
final String equipe1;
final String equipe2;
final String typeprono;
final String date_debut;
final String heure_debut;
const Match(this.id, this.equipe1, this.equipe2, this.typeprono,
this.date_debut, this.heure_debut);
}

how can we center the loader widget flutter_spinkit?

I want use this loading widget : https://pub.dev/packages/flutter_spinkit
But i would like to know how i can center horizontally and vertically this widget whatever the content displayed (simple container it is simple but when there is futurebuilder and a lot of widget displayed in column it is more complicated).
EDIT : My code is Under :
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'menu_member.dart';
import 'globals.dart' as globals;
import 'appbar_draw.dart';
import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:firebase_admob/firebase_admob.dart';
import 'package:intl/intl.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
const testDevices = "Your_DEVICE_ID";
// Create a Form widget.
class Affiche_Liste_Tombola extends StatefulWidget {
#override
_Affiche_Liste_Tombola_State createState() {
return _Affiche_Liste_Tombola_State();
}
}
// Create a corresponding State class.
// This class holds data related to the form.
class _Affiche_Liste_Tombola_State extends State<Affiche_Liste_Tombola> {
#override
static const MobileAdTargetingInfo targetingInfo = MobileAdTargetingInfo(testDevices: testDevices!=null ? <String> ['tessDevices'] : null,keywords: <String> ['game','bet'],nonPersonalizedAds: true);
RewardedVideoAd VideoAd = RewardedVideoAd.instance;
bool load=false;
bool visible=false;
String tombola_select="";
Future<List<Tombola>> ListTombola;
Future <List<Tombola>> Tombola_display() async {
// SERVER LOGIN API URL
var url = 'https://www.easytrafic.fr/game_app/display_list_tombola.php';
var data = {
'id_membre': globals.id_membre,
};
var data_encode = jsonEncode(data);
// Starting Web API Call.
var response = await http.post(url,body: data_encode,headers: {'content-type': 'application/json','accept': 'application/json','authorization': globals.token});
// Getting Server response into variable.
var jsondata = json.decode(response.body);
List<Tombola> Tombolas = [];
for (var u in jsondata) {
Tombola tombola = Tombola(u["id"],u["libelle"],u["date_debut_validation"],u["gain"],u["nb_tickets_achat"],u["nb_tickets_total"],u["nb"]);
Tombolas.add(tombola);
}
return Tombolas;
}
void initState() {
super.initState();
//FirebaseAdMob.instance.initialize(appId: "ca-app-pub-8677431175756102~8892789953");
FirebaseAdMob.instance.initialize(appId: FirebaseAdMob.testAppId);
VideoAd.listener=(RewardedVideoAdEvent event,{String rewardType, int rewardAmount}) {
print('REWARDED VIDEO ADS $event');
if (event == RewardedVideoAdEvent.rewarded) {
setState(() {
load=false;
});
Valide_tombola(tombola_select);
}
if (event == RewardedVideoAdEvent.loaded) {
print('VIDEO LOADED !!!');
load=true;
visible=false;
VideoAd.show();
}
};
ListTombola = Tombola_display();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: drawappbar(true),
drawer: new DrawerOnly(className: Affiche_Liste_Tombola()),
body:
Center(
child:
Column(
children: <Widget>[
Visibility(
maintainSize: true,
maintainAnimation: true,
maintainState: true,
visible: visible,
child: Container(
child: SpinKitChasingDots(color: Colors.blueAccent,size:200)
)
),
Container(
height: MediaQuery.of(context).size.height*0.8,
width: MediaQuery.of(context).size.width*0.8,
child:
FutureBuilder(
future: ListTombola,
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
setState(() {
visible=true;
});
break;
default:
if (snapshot.hasError) {
return new Center(
child: new Text('Error: ${snapshot.error}'),);
}
else {
List<Tombola> values = snapshot.data;
if (values.isEmpty) {
return Container(
child: Center(
child: Text("Aucune tombola disponible !!!")
)
);
}
else {
return ListView.builder(itemCount: values.length,
itemBuilder: (_, index) {
var mt_jackpot=double.parse(values[index].gain);
var f = new NumberFormat.currency(locale: "fr-FR",symbol: "");
var mt_jackpot_f=f.format(mt_jackpot);
return Column(
children: [
Container(
height: 30,
width: MediaQuery.of(context).size.width*90/100,
margin : EdgeInsets.only(top:20),
decoration: BoxDecoration(
border: Border.all(
color: Colors.blue[700],
width: 2,
),
borderRadius: BorderRadius.only(topLeft : Radius.circular(25),topRight: Radius.circular(25)),
color: Colors.blue[700]
),
child : new Text(values[index].libelle,textAlign: TextAlign.center,style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.w500,color: Colors.white),),
),
Center(
child : Container(
height:MediaQuery.of(context).size.height/4,
width: MediaQuery.of(context).size.width*90/100,
margin: EdgeInsets.only(bottom:20),
decoration: BoxDecoration(
border: Border.all(
color: Colors.grey[500],
width: 2,
),
borderRadius: BorderRadius.only(bottomLeft : Radius.circular(25),bottomRight: Radius.circular(25)),
color:Colors.white,
),
child :
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
margin : EdgeInsets.only(bottom:10),
child : RichText(
text: TextSpan(
children: [
TextSpan(
text: mt_jackpot_f,
style: TextStyle(fontSize: 20,fontWeight: FontWeight.w800,color: Colors.black)
),
WidgetSpan(
child: Icon(FontAwesomeIcons.euroSign,color: Colors.amber[900],size:20)
),
],
),
),
),
Container(
margin : EdgeInsets.only(bottom:10),
child :
Text("Vos tickets : "+values[index].nb_tickets_membre)
),
Container(
child : RaisedButton(
color: Colors.green,
textColor: Colors.white,
padding: EdgeInsets.fromLTRB(
9, 9, 9, 9),
child: Text(
'PARTICIPEZ'),
onPressed: () {
tombola_select=values[index].id;
setState(() {
visible=true;
});
VideoAd.load(
adUnitId: RewardedVideoAd.testAdUnitId,
targetingInfo: targetingInfo);
},
),
)
]
),
),
)
]
);
}
);
}
}
}
}
)
)
]
)
)
);
}
Future Valide_tombola(String id_tombola) async{
// For CircularProgressIndicator.
bool visible = false ;
// Showing CircularProgressIndicator.
setState(() {
visible = true ;
});
// SERVER LOGIN API URL
var url = 'https://www.easytrafic.fr/game_app/valide_tombola.php';
// Store all data with Param Name.
var data = {'id_membre':globals.id_membre, 'id_tombola':id_tombola};
var tombola_encode=jsonEncode(data);
// Starting Web API Call.
var response = await http.post(url, body: tombola_encode,headers: {'content-type': 'application/json','accept': 'application/json','authorization': globals.token});
// Getting Server response into variable.
Map <String,dynamic> map2 = json.decode(response.body);
// If the Response Message is Matched.
if(map2["status"] == 1)
{
setState(() {
ListTombola=Tombola_display();
});
AwesomeDialog(context: context,
useRootNavigator: true,
dialogType: DialogType.SUCCES,
animType: AnimType.BOTTOMSLIDE,
tittle: 'VALIDATION',
desc: map2["message"],
btnOkOnPress: () {
}).show();
}else{
// Showing Alert Dialog with Response JSON Message.
AwesomeDialog(context: context,
useRootNavigator: true,
dialogType: DialogType.ERROR,
animType: AnimType.BOTTOMSLIDE,
tittle: 'ERREUR',
desc: map2["message"],
btnOkOnPress: () {
}).show();
}
}
}
class Tombola {
final String id;
final String libelle;
final String datedebut;
final String gain;
final String nb_tickets_achat;
final String nb_tickets_total;
final String nb_tickets_membre;
const Tombola(this.id, this.libelle, this.datedebut,this.gain,this.nb_tickets_achat,this.nb_tickets_total,this.nb_tickets_membre);
}
As you can see the loader is here :
Visibility(
maintainSize: true,
maintainAnimation: true,
maintainState: true,
visible: visible,
child: Container(
child: SpinKitChasingDots(color: Colors.blueAccent,size:200)
)
),
problem : it doesn't work because this code make it is overflowed by 123 pixel and because it is not centered horizontally and vertically