Related
I was trying to update data (add, edit, delete) from my list using API, when I clicked something to update the list e.g deleting an item it showed a successfully updated. but in the Debug Console, there's an error that says
The following assertion was thrown while finalizing the widget tree:
Duplicate GlobalKey detected in the widget tree. The following GlobalKey
was specified multiple times in the widget tree. This will lead to
parts of the widget tree being truncated unexpectedly, because the
second time a key is seen, the previous instance is moved to the new
location. The key was:
[LabeledGlobalKey #47c37] This was determined by noticing that after the widget with the above global key was moved out
of its previous parent, that previous parent never updated during this
frame, meaning that it either did not update at all or updated before
the widget was moved, in either case implying that it still thinks
that it should have a child with that global key.
And when I tried going back to the Previous screen it just showed Blank Screen
Here's the code
Model
import 'dart:convert';
class Nasabah {
int id;
String nama_debitur;
String alamat;
String no_telp;
String no_ktp;
String no_selular;
Nasabah({
this.id = 0,
this.nama_debitur,
this.alamat,
this.no_telp,
this.no_ktp,
this.no_selular,
});
factory Nasabah.fromJson(Map<String, dynamic> json) => Nasabah(
id: json["id"],
nama_debitur: json["nama_debitur"],
alamat: json["alamat"],
no_telp: json["no_telp"],
no_ktp: json["no_ktp"],
no_selular: json["no_selular"],
);
factory Nasabah.fromMap(Map<String, dynamic> map) => Nasabah(
id: map["id"],
nama_debitur: map["nama_debitur"],
alamat: map["alamat"],
no_telp: map["no_telp"],
no_ktp: map["no_ktp"],
no_selular: map["no_selular"],
);
Map<String, dynamic> toJson() => {
"id": id,
"nama_debitur": nama_debitur,
"alamat": alamat,
"no_telp": no_telp,
"no_ktp": no_ktp,
"no_selular": no_selular,
};
#override
String toString() {
return 'Nasabah{id: $id, nama_debitur: $nama_debitur, alamat: $alamat, no_telp: $no_telp, no_ktp: $no_ktp, no_selular: $no_selular}';
}
}
class NasabahResult {
String status;
List<Nasabah> data = new List<Nasabah>();
NasabahResult({
this.status,
this.data,
});
factory NasabahResult.fromJson(Map<String, dynamic> data) => NasabahResult(
status: data["status"],
data: List<Nasabah>.from(
data["data"].map((item) => Nasabah.fromJson(item))),
);
}
NasabahResult nasabahResultFromJson(String jsonData) {
final data = json.decode(jsonData);
return NasabahResult.fromJson(data);
}
String nasabahToJson(Nasabah nasabah) {
final jsonData = nasabah.toJson();
return json.encode(jsonData);
}
Service
import 'package:flutter_auth/Models/nasabah.dart';
import 'dart:convert';
import 'package:http/http.dart' show Client;
class ApiService {
final String baseUrl = '192.168.100.242:8080';
Client client = Client();
Future<List<Nasabah>> getNasabah() async {
final response = await client.get('http://$baseUrl/api/mstdebitur');
print(response.body);
if (response.statusCode == 200) {
final nasabah = (json.decode(response.body) as List)
.map((e) => Nasabah.fromMap(e))
.toList();
return nasabah;
} else {
throw Exception('Failed to load post');
}
}
Future<bool> createNasabah(Nasabah data) async {
String url = new Uri.http("$baseUrl", "/api/mstdebitur/").toString();
final response = await client.post(url,
headers: {"Content-Type": "application/json"},
body: nasabahToJson(data));
if (response.statusCode == 201) {
return true;
} else {
return false;
}
}
Future<bool> updateNasabah(Nasabah data) async {
String url =
new Uri.http("$baseUrl", "/api/mstdebitur/${data.id}").toString();
final response = await client.put(url,
headers: {"Content-Type": "application/json"},
body: nasabahToJson(data));
if (response.statusCode == 200) {
return true;
} else {
return false;
}
}
Future<bool> deleteNasabah(int id) async {
String url = new Uri.http("$baseUrl", "/api/mstdebitur/$id").toString();
final response = await client.delete(url);
if (response.statusCode == 200) {
return true;
} else {
return false;
}
}
}
Home
import 'package:flutter/material.dart';
import 'package:flutter_auth/Models/nasabah.dart';
import 'package:flutter_auth/network/nasabah_service.dart';
import 'FormAddNasabah.dart';
import 'ListNasabah.dart';
GlobalKey<ScaffoldState> _scaffoldState = GlobalKey<ScaffoldState>();
// ignore: must_be_immutable
class DataNasabah extends StatefulWidget {
DataNasabah({Key key}) : super(key: key);
String title;
#override
_DataNasabahState createState() => _DataNasabahState();
}
class _DataNasabahState extends State<DataNasabah> {
ApiService apiService;
ListNasabah _listNasabah;
List<Nasabah> data;
#override
void initState() {
super.initState();
apiService = ApiService();
_listNasabah = new ListNasabah(apiService: apiService);
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldState,
appBar: AppBar(
title: Text(
'Data Nasabah',
style: TextStyle(color: Colors.white),
),
actions: <Widget>[
GestureDetector(
onTap: () async {
var result = await Navigator.push(
_scaffoldState.currentContext,
MaterialPageRoute(builder: (BuildContext context) {
return FormAddNasabah(nasabah: null);
}),
);
if (result != null) {
setState(() {});
}
},
child: Padding(
padding: const EdgeInsets.only(right: 16.0),
child: Icon(
Icons.add,
color: Colors.white,
),
),
)
],
),
body: _listNasabah.createViewList(),
);
}
}
List
import 'package:flutter/material.dart';
import 'package:flutter_auth/Models/nasabah.dart';
import 'package:flutter_auth/network/nasabah_service.dart';
import 'package:flutter_auth/screens/Menu/DataNasabah/FormAddNasabah.dart';
import 'package:flutter_auth/screens/Menu/DataNasabah/NasabahHome.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
class ListNasabah {
ApiService apiService;
ListNasabah({this.apiService});
Widget createViewList() {
return SafeArea(
child: FutureBuilder(
future: apiService.getNasabah(),
builder: (BuildContext context, AsyncSnapshot<List<Nasabah>> snapshot) {
if (snapshot.hasError) {
return Center(
child: Text(
'Something wrong with message: ${snapshot.error.toString()}',
textAlign: TextAlign.center,
),
);
} else if (snapshot.connectionState == ConnectionState.done) {
List<Nasabah> nasabah = snapshot.data;
return nasabahListView(nasabah);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
Widget nasabahListView(List<Nasabah> listnasabah) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
child: ListView.builder(
shrinkWrap: true,
itemBuilder: (context, index) {
Nasabah nasabah = listnasabah[index];
return Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Card(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
nasabah.nama_debitur,
style: Theme.of(context).textTheme.bodyText1,
),
Text(nasabah.alamat),
Text(nasabah.no_ktp),
Text(nasabah.no_telp),
Text(nasabah.no_selular),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
FlatButton(
onPressed: () {
apiService.deleteNasabah(nasabah.id).then((value) =>
Navigator.of(context).pushNamed('start'));
},
child: Text(
"Hapus",
style: TextStyle(color: Colors.red),
),
),
FlatButton(
onPressed: () async {
var result = await Navigator.push(context,
MaterialPageRoute(builder: (context) {
return FormAddNasabah(
nasabah: nasabah,
);
}));
},
child: Text(
'Edit',
style: TextStyle(color: Colors.blue),
),
),
],
)
],
),
),
),
);
},
itemCount: listnasabah.length,
),
);
}
}
Form
import 'package:flutter/material.dart';
import 'package:flutter_auth/Models/nasabah.dart';
import 'package:flutter_auth/network/nasabah_service.dart';
import 'package:flutter_auth/screens/Menu/DataNasabah/NasabahHome.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
class FormAddNasabah extends StatefulWidget {
Nasabah nasabah;
FormAddNasabah({this.nasabah});
#override
_FormAddNasabahState createState() => _FormAddNasabahState();
}
class _FormAddNasabahState extends State<FormAddNasabah> {
ApiService apiService;
TextEditingController _contNama = TextEditingController();
TextEditingController _contAlamat = TextEditingController();
TextEditingController _contNoTelp = TextEditingController();
TextEditingController _contNoKtp = TextEditingController();
TextEditingController _contNoSelular = TextEditingController();
#override
void initState() {
super.initState();
apiService = ApiService();
if (widget.nasabah != null) {
_contNama.text = widget.nasabah.nama_debitur;
_contAlamat.text = widget.nasabah.alamat;
_contNoTelp.text = widget.nasabah.no_telp;
_contNoKtp.text = widget.nasabah.no_ktp;
_contNoSelular.text = widget.nasabah.no_selular;
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
iconTheme: IconThemeData(color: Colors.white),
title: Text(
widget.nasabah == null ? "Tambah Nasabah" : "Edit Nasabah",
style: TextStyle(color: Colors.white),
),
),
body: Stack(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
_buildTextField(_contNama, "Nama Nasabah"),
_buildTextField(_contAlamat, "Alamat"),
_buildTextField(_contNoTelp, "No Telp"),
_buildTextField(_contNoKtp, "No KTP"),
_buildTextField(_contNoSelular, "No Selular"),
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: RaisedButton(
child: Text(widget.nasabah == null ? "Tambah" : "Edit"),
color: Colors.blue,
onPressed: () {
int id = 0;
if (widget.nasabah != null) {
id = widget.nasabah.id;
}
Nasabah nasabah = Nasabah(
id: id,
nama_debitur: _contNama.text,
alamat: _contAlamat.text,
no_telp: _contNoTelp.text,
no_ktp: _contNoKtp.text,
no_selular: _contNoSelular.text);
if (widget.nasabah == null) {
apiService.createNasabah(nasabah);
} else {
apiService.updateNasabah(nasabah);
}
Navigator.of(context)
.pushNamed('start')
.whenComplete(() => Navigator.pop(context));
},
),
)
],
),
)
],
),
);
}
Widget _buildTextField(TextEditingController _cont, String label) {
return TextField(
controller: _cont,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: label,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
);
}
}
Thank you for your attention!
bloc.dart
part 'news_article_loader_event.dart';
part 'news_article_loader_state.dart';
part 'news_article_loader_bloc.freezed.dart';
#injectable
class NewsArticleLoaderBloc
extends Bloc<NewsArticleLoaderEvent, NewsArticleLoaderState> {
NewsArticleLoaderBloc(this.iBlogPost)
: super(NewsArticleLoaderState.initial());
final INewsArticle iBlogPost;
#override
Stream<NewsArticleLoaderState> mapEventToState(
NewsArticleLoaderEvent event) async* {
yield NewsArticleLoaderState.loadInProgress();
final failureOrSuccess = await iBlogPost.getDataNews();
yield failureOrSuccess.fold((l) => NewsArticleLoaderState.loadFailure(l),
(r) => NewsArticleLoaderState.loadSuccess(r));
}
}
repository.dart
import 'dart:convert';
import 'package:dartz/dartz.dart';
import 'package:dio/dio.dart';
import 'package:injectable/injectable.dart';
import 'package:mone/app_constant.dart';
import 'package:mone/model/news/blog_post.dart';
import 'package:mone/repositories/i_news_repository.dart';
import 'package:shared_preferences/shared_preferences.dart';
#Injectable(as: INewsArticle)
class BLogPostRepository implements INewsArticle {
final Dio dio;
// int page = 1;
final SharedPreferences prefs;
BLogPostRepository(this.dio, this.prefs);
#override
Future<Either<String, List<NewsBlogModel>>> getDataNews() async {
try {
final token = prefs.get(kAccesTokenKey);
String url = '/api/v1/cms?size=30';
var response = await dio.get(url,
options: Options(
headers: {
'Accept': 'aplication/json',
'Authorization': 'bearer $token',
},
));
if (response.statusCode == 200) {
final listNews = (response.data['items'] as List)
.map((e) => NewsBlogModel.fromJson(e as Map<String, dynamic>))
.toList();
return right(listNews);
}
return left('error: ${response.statusCode}');
} catch (e) {
return left('error get data $e');
}
}
#override
Future<Either<String, List<NewsBlogModel>>> getDataNewsbyId() async {
// TODO: implement getDataNewsbyId
try {
final token = prefs.get(kAccesTokenKey);
String urlbyid = '/api/v1/cms/id';
var response = await dio.get(urlbyid,
options: Options(headers: {
'Accept': 'aplication/json',
'Authorization': 'bearer $token',
}));
if (response.statusCode == 200) {
final dataNewsbyId = (response.data['items'] as List)
.map((e) => NewsBlogModel.fromJson(e as Map<String, dynamic>))
.toList();
return right(dataNewsbyId);
}
return left("error:${response.statusCode}");
} catch (e) {
return left("error get data $e");
}
}
}
I have the code below where I have provided the BLoC code for the code and also for the repository code. but I'm still confused about how to connect it to the UI that I made. explanation please.
below also my code has succeeded to call all data list from API. but when I want to try to find the data list in the get, but can't.
UI.dart
part of '../screens.dart';
class NewsScreen extends StatefulWidget {
#override
_NewsScreenState createState() => _NewsScreenState();
}
class _NewsScreenState extends State<NewsScreen> {
Widget customTitleBar = const Text('Berita');
Icon customIcon = new Icon(Icons.search, color: primaryColor);
TextEditingController filterController = TextEditingController();
// String filter = '';
// void initState(){
// }
#override
Widget build(BuildContext context) {
// bloc provider berguna untuk menambahkan data dari bloc ke ui,
return BlocProvider(
create: (context) =>
getIt<NewsArticleLoaderBloc>()..add(NewsArticleLoaderEvent.started()),
child: Scaffold(
appBar: AppBar(
title: customTitleBar,
actions: <Widget>[
IconButton(
onPressed: () {
setState(() {
if (this.customIcon.icon == Icons.search) {
this.customIcon =
new Icon(Icons.close, color: primaryColor, size: 30);
this.customTitleBar = new TextField(
style: new TextStyle(
color: Colors.white,
),
decoration: new InputDecoration(
prefixIcon: new Icon(Icons.search,
color: primaryColor, size: 30),
hintText: "Search...",
hintStyle: new TextStyle(color: Colors.white)),
cursorColor: primaryColor,
onChanged: (value) async {
if (value.isEmpty) {
setState(() {});
return;
}
},
controller:filterController,
);
} else {
this.customIcon =
new Icon(Icons.search, color: primaryColor, size: 30);
this.customTitleBar = new Text("Berita");
}
});
},
icon: customIcon,
),
],
),
body: BlocBuilder<NewsArticleLoaderBloc, NewsArticleLoaderState>(
builder: (context, state) {
return state.map(
initial: (_) => Container(),
loadInProgress: (_) => Center(
child: SpinKitCircle(
color: primaryColor,
),
),
loadFailure: (state) => Center(
child: Text(state.failure),
),
loadSuccess: (state) {
if (state.datenews.isEmpty) {
return Center(
child: Text("data tidak di temukan"),
);
} else {
return ListView.separated(
padding: EdgeInsets.all(8.0),
itemCount: state.datenews.length,
separatorBuilder: (BuildContext context, int index) {
return SizedBox(
height: 4,
);
},
itemBuilder: (BuildContext context, int index) {
final newsBlog = state.datenews[index];
return ContentNews(
newsBlog: newsBlog,
);
},
);
}
},
);
},
),
),
);
}
}
Flutter: The value passed in parameter is null on the second page the first time. if I do a hot reload, this value is not null.
maybe it's because of the TabBar but how do you get the real value for the first time while using TabBar?
Please help me find a solution to my problem
First page. And idBou is not null here
class BoutiquePage extends StatefulWidget {
int idboutique;
BoutiquePage({this.idboutique});
#override
_BoutiquePageState createState() => _BoutiquePageState();
}
class _BoutiquePageState extends State<BoutiquePage> {
SharedPreferences sharedPreferences;
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
String idBou ;
String nomAbon ;
String prenomAbon ;
String telAbon ;
String addAbon;
String nomBou;
String ville;
String pays;
String lien_photo_bout;
bool _isLoading = false;
String _errorText;
get article_afficher333 => article_afficher333;
#override
void initState() {
setState((){
getShaerInstance();
});
super.initState();
}
getShaerInstance() async {
sharedPreferences = await SharedPreferences.getInstance();
}
Future<Map<String, dynamic>> getAllStoreInfoData2(int idboutique) async {
final response = await http.get(http://xxxxxx.com+"boutique/home?id_bout="+idboutique.toString());
if (response.statusCode == 200) {
final jsonResponse = json.decode(response.body);
BoutiqueData myData = new BoutiqueData.fromJson(jsonResponse);
Map<String, dynamic> boutiqueinfodata = Map();
boutiqueinfodata["boutiqueType"] = myData.v_boutique.typeBoutique;
return boutiqueinfodata;
} else {
throw Exception("Failed to load Data");
}
}
//SharedPreferences
#override
Widget build(BuildContext context) {
Widget myboutiqueinfodata = FutureBuilder(
future: getAllStoreInfoData2(widget.idboutique),
builder: (context, snapshot) {
if (snapshot.hasData) {
Map<String, dynamic> alldata = snapshot.data;
typeBoutique = alldata["boutiqueType"];
List<ListeInfoBoutique> boutiqueInfoData = alldata["boutiqueInfoData"];
for (var i = 0; i < boutiqueInfoData.length; i++) {
idBou = boutiqueInfoData[i].idBou;
nomAbon = boutiqueInfoData[i].nomAbon;
prenomAbon = boutiqueInfoData[i].prenomAbon;
telAbon = boutiqueInfoData[i].telAbon;
addAbon = boutiqueInfoData[i].addAbon;
}
return Scaffold(
body: ListView(
children: <Widget>[
],
),
);
}else if (snapshot.hasError) {
return Container(
child: Center(
child: Text(AppLocalizations.of(context)
.translate('_MSG_ER_CONNEXION_CHARGE_DATA'),
style: TextStyle(
fontSize: 18,
fontFamily: 'Questrial'
),),
),
);
}
return new Center(
child: CircularProgressIndicator(),
);
});
return DefaultTabController(
length: 5,
child: Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text(AppLocalizations.of(context)
.translate('_MY_STORE'), style: TextStyle(color: Colors.white, fontFamily: "Questrial"),),
iconTheme: new IconThemeData(color: Color(0xFFFFFFFF)),
actions: <Widget>[
//
],
bottom: TabBar(
isScrollable: true,
indicatorColor: Colors.white,
indicatorWeight: 5.0,
//onTap: (){},
tabs: <Widget>[
Tab(
child: Container(
child: Text(AppLocalizations.of(context)
.translate('_STORE_INFO'), style: TextStyle(color: Colors.white, fontSize: 18.0, fontFamily: 'Questrial'),),
),
),
Tab(
child: Container(
child: Text(AppLocalizations.of(context)
.translate('_MY_ARTICLES'), style: TextStyle(color: Colors.white, fontSize: 18.0, fontFamily: 'Questrial'),),
),
),
],
),
),
body: TabBarView(
children: <Widget>[
myboutiqueinfodata,
MesArticles(idboutique: idBou),
],
),
),
);
}
}
Secode page who print null a first time and after hot reload become not null
class MesArticles extends StatefulWidget {
final String idboutique;
const MesArticles({Key key, this.idboutique}) : super(key: key);
#override
_MesArticleState createState() => _MesArticleState();
}
class _MesArticleState extends State<MesArticles> {
#override
Widget build(BuildContext context) {
print(widget.idboutique.toString()); // it print null for fist time. After hot reload it become not null
return Scaffold(
body: Text(widget.idboutique.toString()), //<== it print null for fist time.
);
}
}
Try this code. I think Future builder is the reason it throws null.
class BoutiquePage extends StatefulWidget {
int idboutique;
BoutiquePage({this.idboutique});
#override
_BoutiquePageState createState() => _BoutiquePageState();
}
class _BoutiquePageState extends State<BoutiquePage> {
SharedPreferences sharedPreferences;
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
String idBou ;
String nomAbon ;
String prenomAbon ;
String telAbon ;
String addAbon;
String nomBou;
String ville;
String pays;
String lien_photo_bout;
bool _isLoading = false;
bool _isLoaded = false;
bool _isError = false;
String _errorText;
get article_afficher333 => article_afficher333;
#override
void initState() {
setState((){
getShaerInstance();
});
super.initState();
}
getShaerInstance() async {
sharedPreferences = await SharedPreferences.getInstance();
}
Future<Map<String, dynamic>> getAllStoreInfoData2(int idboutique) async {
final response = await http.get("http://xxxxxx.com/" + "boutique/home?id_bout="+idboutique.toString());
if (response.statusCode == 200) {
final jsonResponse = json.decode(response.body);
BoutiqueData myData = new BoutiqueData.fromJson(jsonResponse);
Map<String, dynamic> boutiqueinfodata = Map();
boutiqueinfodata["boutiqueType"] = myData.v_boutique.typeBoutique;
return boutiqueinfodata;
} else {
throw Exception("Failed to load Data");
}
}
//SharedPreferences
initDataFromServer(idboutique) async {
try {
var alldata = await getAllStoreInfoData2(idboutique);
var typeBoutique = alldata["boutiqueType"];
List<ListeInfoBoutique> boutiqueInfoData = alldata["boutiqueInfoData"];
for (var i = 0; i < boutiqueInfoData.length; i++) {
idBou = boutiqueInfoData[i].idBou;
nomAbon = boutiqueInfoData[i].nomAbon;
prenomAbon = boutiqueInfoData[i].prenomAbon;
telAbon = boutiqueInfoData[i].telAbon;
addAbon = boutiqueInfoData[i].addAbon;
}
setState(() {
_isLoaded = true;
_isLoading = false;
_isError = false;
});
} catch (e) {
print(e);
setState(() {
_isLoaded = true;
_isLoading = true;
_isError = true;
});
}
}
#override
Widget build(BuildContext context) {
if (_isLoaded == false && _isLoading == false) {
_isLoading = true;
initDataFromServer(widget.idboutique);
}
return DefaultTabController(
length: 5,
child: Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text(AppLocalizations.of(context)
.translate('_MY_STORE'), style: TextStyle(color: Colors.white, fontFamily: "Questrial"),),
iconTheme: new IconThemeData(color: Color(0xFFFFFFFF)),
actions: <Widget>[
//
],
bottom: TabBar(
isScrollable: true,
indicatorColor: Colors.white,
indicatorWeight: 5.0,
//onTap: (){},
tabs: <Widget>[
Tab(
child: Container(
child: Text(AppLocalizations.of(context)
.translate('_STORE_INFO'), style: TextStyle(color: Colors.white, fontSize: 18.0, fontFamily: 'Questrial'),),
),
),
Tab(
child: Container(
child: Text(AppLocalizations.of(context)
.translate('_MY_ARTICLES'), style: TextStyle(color: Colors.white, fontSize: 18.0, fontFamily: 'Questrial'),),
),
),
],
),
),
body: TabBarView(
children: <Widget>[
_isLoaded == false ? Center(
child: CircularProgressIndicator(),
): (_isError == false ? Text("Your data Loaded") : Text("Error")),
_isLoaded == false ? Center(
child: CircularProgressIndicator(),
): (_isError == false ? MesArticles(idboutique: idboutique) : Text("Error")),
],
),
),
);
}
}
class MesArticles extends StatefulWidget {
final String idboutique;
const MesArticles({Key key, this.idboutique}) : super(key: key);
#override
_MesArticleState createState() => _MesArticleState(idboutique: idboutique);
}
class _MesArticleState extends State<MesArticles> {
final String idboutique;
_MesArticleState({this.idboutique});
#override
Widget build(BuildContext context) {
print(widget.idboutique.toString()); // it print null for fist time. After hot reload it become not null
return Scaffold(
body: Text(widget.idboutique.toString()),
);
}
}
I need to shape myUrl inside Future related to username which I got from myfirstpage, I can get the name and use it in my homepage title but I couldn't figured out how can I use it in myUrl(instead of "$_name"),
Probably I made a mistake with point to data with "pushNamed(MyHomePage.routeName);" actually I don't need that value in MyHomePage, I just need it for shape myUrl line, also I tried to make "_name" value as a global value etc just not couldn't succeed..
import 'package:flutter/cupertino.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
new GlobalKey<RefreshIndicatorState>();
Future<bool> saveNamedPreference(String name) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("name", name);
return prefs.commit();
}
Future<String> getNamePreferences() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String name = prefs.getString("name");
return name;
}
Payload payloadFromJson(String str) {
return Payload.fromJson(json.decode(str));
}
String payloadToJson(Payload data) {
return json.encode(data.toJson());
}
Future<Payload> getData() async{
String myUrl = 'http://lunedor.pythonanywhere.com/query?username=$_name';
http.Response response = await http.get(myUrl);
print(myUrl);
return response == null ? getData() : payloadFromJson(response.body);
}
class Payload {
String moviecast;
String moviedirectors;
String moviegenre;
String movieposterurl;
String movierating;
String movieruntime;
String moviesummary;
String movietitle;
String moviewriters;
String movieyear;
Payload({
this.moviecast,
this.moviedirectors,
this.moviegenre,
this.movieposterurl,
this.movierating,
this.movieruntime,
this.moviesummary,
this.movietitle,
this.moviewriters,
this.movieyear,
});
factory Payload.fromJson(Map<String, dynamic> json) => Payload(
moviecast: json["Actors"],
moviedirectors: json["Director"],
moviegenre: json["Genre"],
movieposterurl: json["Poster"],
movierating: json["imdbRating"],
movieruntime: json["Runtime"],
moviesummary: json["Plot"],
movietitle: json["Title"],
moviewriters: json["Writer"],
movieyear: json["Year"],
);
Map<String, dynamic> toJson() => {
"moviecast": moviecast,
"moviedirectors": moviedirectors,
"moviegenre": moviegenre,
"movieposterurl": movieposterurl.replaceAll('300.jpg', '900.jpg'),
"movierating": movierating,
"movieruntime": movieruntime,
"moviesummary": moviesummary,
"movietitle": movietitle,
"moviewriters": moviewriters,
"movieyear": movieyear,
};
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Random Movie',
theme: new ThemeData(
primarySwatch: Colors.grey,
),
home: new MyFirstPage(),
routes: <String, WidgetBuilder>{
MyHomePage.routeName: (context) => new MyHomePage(),
},
);
}
}
class MyFirstPage extends StatefulWidget {
#override
_MyFirstPageState createState() => new _MyFirstPageState();
}
class _MyFirstPageState extends State<MyFirstPage>{
var _controller = new TextEditingController();
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
backgroundColor: Colors.blueGrey,
centerTitle: true,
title: new Text("Please enter your Trakt username",
style: new TextStyle(
fontSize: 18.0,
color: Colors.white,
),
),
),
body: new ListView(
children: <Widget>[
new ListTile(
title: new TextField(
controller: _controller,
),
),
new ListTile(
title: new RaisedButton(
child: new Text("Submit"),
onPressed:(){setState(() {
saveName();
});
}),
)
],
),
);
}
void saveName() {
String name = _controller.text;
saveNamedPreference(name).then((bool committed) {
Navigator.of(context).pushNamed(MyHomePage.routeName);
});
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
static String routeName = "/myHomePage";
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
Payload payload;
class _MyHomePageState extends State<MyHomePage> {
Modal modal = Modal();
bool isLoading = true;
String _name = "";
#override
void initState() {
// TODO: implement initState
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {loadData();
WidgetsBinding.instance.addPostFrameCallback((_) => _refreshIndicatorKey.currentState.show());
getNamePreferences().then(updateName);
});
}
void loadData() async {
payload = await getData();
isLoading = false;
setState(() {});
print('${payload.movieposterurl.replaceAll('300.jpg', '900.jpg')}');
}
void updateName(String name) {
setState(() {
this._name = name;
ValueKey(_name);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
appBar:
AppBar(
backgroundColor: Colors.blueGrey,
title:
isLoading ? Center(child: CircularProgressIndicator()):Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Center(
child: Text('${payload.movietitle}', maxLines: 2, textAlign: TextAlign.center,
style: new TextStyle(
fontSize: 18.0,
color: Colors.white,
),
),
),
Text('${payload.movieyear}' + " - " + _name + " - " + '${payload.movierating}',
style: new TextStyle(
fontSize: 14.0,
color: Colors.black,
fontStyle: FontStyle.italic,),
),
]
),
),
),
body:
isLoading ? Center(child: CircularProgressIndicator()):
RefreshIndicator(
key: _refreshIndicatorKey,
onRefresh: () async{payload = await getData();
isLoading = false;
setState(() {});
},
child: Center(
child:ListView(
shrinkWrap: true,
children: [
FittedBox(
alignment: Alignment.center,
child:
Image.network('${payload.movieposterurl.replaceAll('300.jpg', '900.jpg')}'),
),
]
)
)
),
bottomNavigationBar: isLoading ? Center(child: CircularProgressIndicator()):
BottomAppBar(
child: Container(
color: Colors.grey,
child: SizedBox(
width: double.infinity,
child:
FlatButton(
color: Colors.grey,
textColor: Colors.black,
onPressed: () {
modal.mainBottomSheet(context);
},
child: Text("Details",
style: TextStyle(fontSize: 16.0),),
),
),
),
),
);
}
}
class Modal {
mainBottomSheet(BuildContext context) {
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
_createTile(
context, "Genre: " + payload.moviegenre + "\n" + "Runtime: " + payload.movieruntime, Icons.local_movies,
_action),
_createTile(
context, "Director: " + payload.moviedirectors,
Icons.movie_creation,
_action),
_createTile(
context, "Writer: " + payload.moviewriters,
Icons.movie,
_action),
_createTile(
context, "Cast: " + payload.moviecast, Icons.chrome_reader_mode,
_action),
_createTile(
context, "Summary: " + payload.moviesummary, Icons.recent_actors, _action),
],
),
);
}
);
}
ListTile _createTile(BuildContext context, String name, IconData icon,
Function action) {
return ListTile(
leading: Icon(icon),
title: Text(name),
onTap: () {
Navigator.pop(context);
action();
},
);
}
_action() {
print('action');
}
}
Not completely sure I got your question, but it should be enough to modify your getData() method to accept a String in parameters, at the moment getData() is a top-level function that doesn't know the _name value because is a private instance variable of _MyHomePageState
Future<Payload> getData(String name) async{
String myUrl = 'http://lunedor.pythonanywhere.com/query?username=$name';
http.Response response = await http.get(myUrl);
print(myUrl);
return response == null ? getData() : payloadFromJson(response.body);
}
And then in your loadData() method pass the correct value
void loadData() async {
payload = await getData(_name);
isLoading = false;
setState(() {});
print('${payload.movieposterurl.replaceAll('300.jpg', '900.jpg')}');
}
One last thing, you should add the "reload" logic when you change the name
void updateName(String name) {
setState(() {
isLoading = true;
this._name = name;
ValueKey(_name);
loadData();
});
}
Personally I think that the Payload variable should stay inside your _MyHomePageState class
I was trying to fetch data from my backend which is developed using Laravel framework. I need to use POST request for each request to pass the API middleware.
When I use GET request without headers, future builder works just fine and got updated immediately after the data on the backend has changed but I can't get Laravel to grab the current authenticated user because no token provided.
But when I use POST request or GET request with headers, it stops updating and I need to switch to another page and go back in order to get the changes.
Please take a look at my script below:
Future<List<Document>> fetchDocuments(http.Client http, String token) async {
final headers = {'Authorization': 'Bearer $token'};
final response = await http.post(
'http://192.168.1.2:8000/api/documents/all',
headers: headers,
);
// Use the compute function to run parseDocuments in a separate isolate.
return compute(parseDocuments, response.body);
}
// A function that converts a response body into a List<DOcument>
List<Document> parseDocuments(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Document>((json) => Document.fromJSON(json)).toList();
}
class Document {
final int id;
final String name;
Document({this.id, this.name});
factory Document.fromJSON(Map<String, dynamic> json) {
return Document(
id: json['id'] as int,
name: json['name'] as String,
);
}
}
class StudentDocumentScreen extends StatefulWidget {
StudentDocumentScreen({Key key}) : super(key: key);
_StudentDocumentScreenState createState() => _StudentDocumentScreenState();
}
class _StudentDocumentScreenState extends State<StudentDocumentScreen> {
final storage = FlutterSecureStorage();
final _uploadURL = 'http://192.168.1.2:8000/api/documents';
final _scaffoldKey = GlobalKey<ScaffoldState>();
final SnackBar uploadingSnackbar = SnackBar(
content: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Uploading file, this may take a while...',
style: TextStyle(color: Colors.white),
),
),
);
final SnackBar successSnackbar = SnackBar(
content: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'File uploaded!',
style: TextStyle(color: Colors.white),
),
),
backgroundColor: Colors.green,
);
final SnackBar errorSnackbar = SnackBar(
content: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Oops... Something went wrong!',
style: TextStyle(color: Colors.white),
),
),
backgroundColor: Colors.red,
);
String _token;
String _path;
#override
void initState() {
super.initState();
_getToken();
}
void _getToken() async {
String token = await storage.read(key: 'accessToken');
setState(() => _token = token);
}
void _openFileExplorer() async {
try {
_path = null;
_path = await FilePicker.getFilePath();
} on PlatformException catch (e) {
print('Unsupported operation');
print(e);
}
if (!mounted) return;
if (_path != null || _path.isNotEmpty) {
_uploadDocument(_path);
}
}
void _uploadDocument(String path) async {
_scaffoldKey.currentState.showSnackBar(uploadingSnackbar);
try {
var multipartFile = await http.MultipartFile.fromPath('document', path);
var request = http.MultipartRequest('POST', Uri.parse(_uploadURL));
request.headers.addAll({'Authorization': 'Bearer $_token'});
request.files.add(multipartFile);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
_scaffoldKey.currentState.showSnackBar(successSnackbar);
} else {
_scaffoldKey.currentState.showSnackBar(errorSnackbar);
}
} catch (e) {
print('Error when uploading files');
print(e);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text('Koleksi Dokumen'),
),
body: _buildBody(),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: _openFileExplorer,
),
);
}
Widget _buildBody() {
return FutureBuilder<List<Document>>(
future: fetchDocuments(http.Client(), _token),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? DocumentList(documents: snapshot.data)
: Center(child: CircularProgressIndicator());
},
);
}
}
class DocumentList extends StatelessWidget {
final List<Document> documents;
const DocumentList({Key key, this.documents}) : super(key: key);
#override
Widget build(BuildContext context) {
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: documents.length,
itemBuilder: (context, index) {
return Card(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(bottom: 20.0),
child: Icon(
Icons.insert_drive_file,
color: Colors.black12,
size: 50.0,
),
),
Text(
documents[index].name,
textAlign: TextAlign.center,
),
],
),
),
);
},
);
}
}
And below is the laravel script:
# in the `api.php`
Route::post('documents/all', 'DocumentController#index');
# in the `DocumentController`
public function index()
{
$userId = auth()->user()->id;
return Document::whereUserId($userId)
->get()
->load('user');
}
Any idea? Thanks in advance.
I just found a temporary solution, putting setState(() {}); after uploading progress do the job.
Please feel free to answer if you guys has a better one.
Solution:
void _uploadDocument(String path) async {
_scaffoldKey.currentState.showSnackBar(uploadingSnackbar);
try {
var multipartFile = await http.MultipartFile.fromPath('document', path);
var request = http.MultipartRequest('POST', Uri.parse(_uploadURL));
request.headers.addAll({'Authorization': 'Bearer $_token'});
request.files.add(multipartFile);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
_scaffoldKey.currentState.showSnackBar(successSnackbar);
setState(() {}); // reload state
} else {
_scaffoldKey.currentState.showSnackBar(errorSnackbar);
}
} catch (e) {
print('Error when uploading files');
print(e);
}
}