Flutter PhpMyAdmin Fetch Data - flutter

I wanna fetch data from PhpMyAdmin. But i am facing one issue. I can see in the body my data. I am sharing my source code. Thx for helping. And I am working with flutter desktop.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class WarehousePage extends StatefulWidget {
const WarehousePage({Key key}) : super(key: key);
#override
_WarehousePageState createState() => _WarehousePageState();
}
class _WarehousePageState extends State<WarehousePage> {
List data = [];
#override
void initState() {
fetchData();
super.initState();
}
void fetchData() async {
final response =
await http.get(Uri.parse('url/getdata.php'));
data = json.decode(response.body);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: ListView.builder(
itemCount: data.length,
itemBuilder: (BuildContext context, int index) => ListTile(
title: Text(data[index]['productName']),
),
),
);
}
}
Update my code but still same. What is wrong? I have not any model class. I am see my data in the body and debug console. But i cant write it in the listview.
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class WarehousePage extends StatefulWidget {
const WarehousePage({Key key}) : super(key: key);
#override
_WarehousePageState createState() => _WarehousePageState();
}
class _WarehousePageState extends State<WarehousePage> {
List data = [];
#override
void initState() {
fetchData();
super.initState();
}
Future<List> fetchData() async {
var jsonResponse;
try {
var url = Uri.parse('https://rul/getdata.php');
var response = await http.get(url).timeout(const Duration(seconds: 20));
if (response.statusCode == 200) {
jsonResponse = json.decode(response.body);
if (jsonResponse != null) {
return (json.decode(response.body) as List)
.map((data) => (data))
.toList();
}
}
} on SocketException catch (e) {
print(e);
} catch (e) {
print(e);
}
return jsonResponse;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: ListView.builder(
itemCount: data.length,
itemBuilder: (BuildContext context, int index) => ListTile(
title: Text(data[index]['productName']),
),
),
);
}
}

static Future<List<SomeModel>> fetchQuizTest() async {
var jsonResponse;
try {
var url = Uri.parse(url');
var response = await http.get(url).timeout(const Duration(seconds: 20));
if (response.statusCode == 200) {
jsonResponse = json.decode(response.body);
if (jsonResponse != null) {
return (json.decode(response.body) as List)
.map((data) => new SomeModel.fromJson(data))
.toList();
}
}
} on SocketException catch (e) {
print(e);
} catch (e) {
print(e);
}
return jsonResponse;
}

Related

flutter does not show data from API

When I try to pull data from the jsonplaceholder API and put it on the screen, I don't have any problems, but when I try to change the data in this link (https://reqres.in/api/users?page=2 ) on the reqres.io site with the same codes, only by changing the API and model, the text no data appears on the screen. I'm getting it can you help me ?
My project with JsonPlaceHolder
main.dart
import 'package:flutter/material.dart';
import 'package:my_app/models/json_model.dart';
import 'service/api_service.dart';
void main() =\> runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: const Text('Json Deneme'),
),
body: const Home(),
),
);
}
}
class Home extends StatefulWidget {
const Home({super.key});
#override
State\<Home\> createState() =\> \_HomeState();
}
class \_HomeState extends State\<Home\> {
List\<JsonModel\>? \_postItems;
bool \_isLoading = false;
String? \_errorMessage;
#override
void initState() {
super.initState();
loadData();
}
Future\<void\> loadData() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final postItems = await Api.fetchApi();
setState(() {
_postItems = postItems;
_isLoading = false;
});
} catch (e) {
setState(() {
_isLoading = false;
_errorMessage = 'Error fetching data: $e';
});
}
}
#override
Widget build(BuildContext context) {
if (\_isLoading) {
return const Center(child: CircularProgressIndicator());
} else if (\_postItems == null || \_postItems!.isEmpty) {
return const Center(child: Text('No Data'));
} else {
return ListView.builder(
itemCount: \_postItems!.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(\_postItems!\[index\].name),
);
},
);
}
}
}`
api_service.dart
`import 'dart:io';
import 'package:my_app/models/json_model.dart';
import 'package:dio/dio.dart';
class Api {
static Future<List<JsonModel>?> fetchApi() async {
final res = await Dio().get("https://jsonplaceholder.typicode.com/users");
if (res.statusCode == HttpStatus.ok) {
final data = res.data!;
if (data is List) {
return data.map((e) =\> JsonModel.fromMap(e)).toList();
}
}
return <JsonModel>[];
}
}
`
conclusion
conclusion
My project with reqres.in
main.dart
`import 'package:flutter/material.dart';
import 'package:my_app/models/json_model.dart';
import 'service/api_service.dart';
void main() =\> runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: const Text('Json Deneme'),
),
body: const Home(),
),
);
}
}
class Home extends StatefulWidget {
const Home({super.key});
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<ReqresModel>? _postItems;
bool _isLoading = false;
String? _errorMessage;
#override
void initState() {
super.initState();
loadData();
}
Future<void> loadData() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final postItems = await Api.fetchApi();
setState(() {
_postItems = postItems;
_isLoading = false;
});
} catch (e) {
setState(() {
_isLoading = false;
_errorMessage = 'Error fetching data: $e';
});
}
}
#override
Widget build(BuildContext context) {
if (_isLoading) {
return const Center(child: CircularProgressIndicator());
} else if (_postItems == null || _postItems!.isEmpty) {
return const Center(child: Text('No Data'));
} else {
return ListView.builder(
itemCount: _postItems!.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(\_postItems!\[index\].data\[index\].firstName),
);
},
);
}
}
}`
api_servise.dart
`import 'dart:io';
import 'package:my_app/models/json_model.dart';
import 'package:dio/dio.dart';
class Api {
static Future<List<ReqresModel>?> fetchApi() async {
final res = await Dio().get("https://reqres.in/api/users?page=2");
if (res.statusCode == HttpStatus.ok) {
final data = res.data!;
if (data is List) {
return data.map((e) => ReqresModel.fromMap(e)).toList();
}
}
return <ReqresModel>[];
}
}`
conclusion
conclusion
**Thank you **
I sent the API using Postman, there was no problem, I don't think the problem was caused by the API, sorry for my bad English
Change your api_service.dart for reqres.in project with following code.
First api which returns List directly, but second api which return Json which has data as List
Edited
main.dart
import 'package:flutter/material.dart';
import 'package:my_app/models/json_model.dart';
import 'service/api_service.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: const Text('Json Deneme'),
),
body: const Home(),
),
);
}
}
class Home extends StatefulWidget {
const Home({super.key});
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<ReqresModel>? _postItems;
bool _isLoading = false;
String? _errorMessage;
#override
void initState() {
super.initState();
loadData();
}
Future<void> loadData() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final postItems = await Api.fetchApi();
setState(() {
_postItems = postItems;
_isLoading = false;
});
} catch (e) {
setState(() {
_isLoading = false;
_errorMessage = 'Error fetching data: $e';
});
}
}
#override
Widget build(BuildContext context) {
if (_isLoading) {
return const Center(child: CircularProgressIndicator());
} else if (_postItems == null || _postItems!.isEmpty) {
return const Center(child: Text('No Data'));
} else {
return ListView.builder(
itemCount: _postItems!.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_postItems![index].firstName),//Updated here
);
},
);
}
}
}
api_service.dart
import 'dart:io';
import 'package:my_app/models/json_model.dart';
import 'package:dio/dio.dart';
class Api {
static Future<List<ReqresModel>?> fetchApi() async {
final res = await Dio().get("https://reqres.in/api/users?page=2");
if (res.statusCode == HttpStatus.ok) {
final data = res.data!['data'];//Updated here
if (data is List) {
return data.map((e) => ReqresModel.fromMap(e)).toList();
}
}
return <ReqresModel>[];
}
}
ReqresModel - should be updated
//Updated here
class ReqresModel {
int? id;
String? email;
String? firstName;
String? lastName;
String? avatar;
ReqresModel(
{this.id, this.email, this.firstName, this.lastName, this.avatar});
ReqresModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
email = json['email'];
firstName = json['first_name'];
lastName = json['last_name'];
avatar = json['avatar'];
}
}

How to use MapShapeSource.network() with data from API Call (Post / Get from server)

I'm working with SfMaps syncfusion map and when I try to load geojson data from the local assets folder using the MapShapeSource.asset() property and everything works fine. But I'm having problems when I want to load geojson data as a result from api calling (GET / POST) using the http package flutter.
// Function to load data json from API
Future<void> loadGeojsonDataFromAPI() async {
setState(() => loading = true);
try {
final response = await http.post(
Uri.parse("some url"),
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: body);
if (response.statusCode >= 400) {
throw Exception('statusCode=${response.statusCode}');
}
setState(() {
loading = false;
data = jsonDecode(response.body);
});
} catch (e) {
setState(() => loading = false);
debugPrint("Error load data: $e");
return;
}
}
// Loadjson data from API in Map Shape Source.network() but not sure how to do it
dataSource = MapShapeSource.network(
'url',
shapeDataField: 'name',
);
I believe this can be solved using MapShapeSource.network(), but am still confused about how to use it.
any kind of help is very much appreciated
You can load the area shape JSON data from the web/network using the MapShapeSource.network() constructor available in the maps widget. We have shared the user guide documentation and sample below for your reference.
UG, https://help.syncfusion.com/flutter/maps/getting-started#from-network
Code snippet:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_maps/maps.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Syncfusion Flutter Maps',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Syncfusion Flutter Maps'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late MapShapeSource _dataSource;
late List<IndiaMap> _mapDetails;
Future<bool> _fetchNetworkJsonDetails() async {
if (_mapDetails.isNotEmpty) {
return true;
}
final http.Response response = await http
.get(Uri.tryParse('https://api.npoint.io/b127f79b6e9c883d0aba')!);
if (response.statusCode == 200) {
Map<String, dynamic> responseJson = json.decode(response.body);
List<dynamic> countriesCoordinates = responseJson['features'];
for (int i = 0; i < countriesCoordinates.length; i++) {
Map<String, dynamic> data = countriesCoordinates[i]['properties'];
IndiaMap mapDetail = IndiaMap.fromJsonMap(data);
_mapDetails.add(mapDetail);
}
_dataSource = MapShapeSource.network(
'https://api.npoint.io/b127f79b6e9c883d0aba',
shapeDataField: 'name',
dataCount: _mapDetails.length,
primaryValueMapper: (index) => _mapDetails[index].state,
);
return true;
} else {
throw Exception('Failed to load JSON');
}
}
#override
void initState() {
_mapDetails = [];
super.initState();
}
#override
void dispose() {
_mapDetails.clear();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: FutureBuilder(
future: _fetchNetworkJsonDetails(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
if (snapshot.hasData) {
return Padding(
padding: const EdgeInsets.all(15),
child: SfMaps(
layers: [
MapShapeLayer(
source: _dataSource,
color: const Color.fromRGBO(15, 59, 177, 0.5),
strokeColor: Colors.white,
strokeWidth: 0.5,
),
],
),
);
} else {
return const Center(child: CircularProgressIndicator());
}
}),
);
}
}
class IndiaMap {
late String state;
late String country;
IndiaMap(this.state, this.country);
IndiaMap.fromJsonMap(Map data) {
state = data['name'];
country = data['admin'];
}
}

Hive boxes are deleted when app closes or restart

The problem is that Hive is acting unexpectedly, and when the app closes or I restart it all, the data in the box is cleared.
main.dart:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle(statusBarColor: Colors.transparent));
await Firebase.initializeApp();
await Hive.initFlutter();
Hive.registerAdapter(CredentialsModelAdapter());
Hive.registerAdapter(DoctorModelAdapter());
Hive.registerAdapter(DuserModelAdapter());
Hive.registerAdapter(DoctorAppointmentsAdapter());
Hive.registerAdapter(AppointmentStatusesAdapter());
Hive.registerAdapter(AccountTypeAdapter());
Hive.registerAdapter(UserAdapter());
await Hive.openBox<CredentialsModel>("cred");
await Hive.openBox<DuserModel>("doctor");
runApp(ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
MyApp({Key? key}) : super(key: key);
final _appRouter = app_router.AppRouter();
#override
Widget build(BuildContext context) {
return MaterialApp.router(
title: "x",
debugShowCheckedModeBanner: false,
routerDelegate: _appRouter.delegate(),
routeInformationParser: _appRouter.defaultRouteParser(),
);
}
}
Here is where I fetch the data from the api and store it in box:
#override
Future<Either<ApiFailures, dynamic>> signInWithEmailAndPassword(
{required String email, required String password}) async {
late Box<CredentialsModel> credentials;
var result;
try {
final response = await http.get(Uri.parse(
"xxxxxxxx"));
if (response.statusCode == 200) {
result = await json.decode(response.body);
if (result["AZSVR"] == "FAILED") {
return const Left(ApiFailures.authFailed());
} else {
var content = CredentialsModel.fromJson(result);
credentials = Hive.box("cred");
credentials.put('cred', content);
return right(result["api_token"]);
}
}
} on SocketException catch (e) {
return const Left(ApiFailures.noConnection());
} on HttpException {
return const Left(ApiFailures.notfound());
} catch (_) {
return const Left(ApiFailures.notfound());
}
return Right(result["api_token"]);
}
Where I call the box:
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:vwelfare/application/provider/doctor.repository.provider.dart';
import 'package:vwelfare/domain/models/doctor/duser.dart';
import '../../domain/models/credentials/credentials.dart';
class MyWidget extends HookConsumerWidget {
const MyWidget({super.key});
#override
Widget build(BuildContext context, WidgetRef ref) {
final Box<CredentialsModel> credBox = Hive.box("cred");
final Box<DuserModel> doctorBox = Hive.box("doctor");
final controller = useTextEditingController();
final uid = useState(0);
final cred = useState(const CredentialsModel());
return Scaffold(
body: ValueListenableBuilder(
valueListenable: credBox.listenable(),
builder: (context, Box<CredentialsModel> box, _) {
final cred = box.get("cred");
print(cred!.api_token);
final doctor = ref.watch(getDoctor(cred.api_token!));
return doctor.when(
data: (data) => data.fold(
(l) => ValueListenableBuilder(
valueListenable: doctorBox.listenable(),
builder: (context, Box<DuserModel> box, _) {
final model = box.get("doctor");
final doctor = model!.User;
if (doctor != null) {
return Center(
child: Text("${doctor.address}"),
);
} else {
return const Center(
child: Text("CONTACT US"),
);
}
}),
(r) => Center(child: Text("${r.User!.name}"))),
loading: () => const CircularProgressIndicator(),
error: (error, stackTrace) {
print(error);
return Center(
child: Text("$error hello"),
);
});
},
),
);
}
}
I don't know if I am doing something wrong but I followed the docs as they say:
1- registered the adapter
2- opened the box
3- called it in a widget
What am I doing wrong?

convert future builder to listview builder

i want to fetch data withour using future, can someone help me to convert it ? direct using listview.builder without using future builder. and how can i post it ? i already try it for a couple days and stuck here. please explain it too
thank you
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:latihan_dio/src/features/home/domain/user.dart';
import '../../../../dio_client.dart';
class myHomepage extends StatefulWidget {
const myHomepage({Key? key}) : super(key: key);
#override
State<myHomepage> createState() => _myHomepageState();
}
class _myHomepageState extends State<myHomepage> {
// List<User> users = [];
var selectedIndex = 0;
#override
void initState() {
super.initState();
// fetchData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FutureBuilder<List<User>>(
future: fetchData(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Text('Loading....');
default:
// if (snapshot.hasError) {
// return Text('Error: ${snapshot.error}');
// } else {
List<User>? data = snapshot.data;
return ListView.builder(
itemBuilder: (context, index) {
return Column(children: [
Text(data![index].firstName!),
]);
},
itemCount: data?.length,
);
}
}
// },
),
));
}
Future<List<User>> fetchData() async {
var Response = await DioClient().apiCall(
url: 'https://reqres.in/api/users?page=2',
requestType: RequestType.GET,
// queryParameters: {},
);
if (Response.statusCode == 200) {
List<dynamic> listUser = Response.data['data'];
List<User> users = listUser.map((e) => User.fromJson(e)).toList();
return users;
} else {
return [];
}
}
}
// Future<void> fetchData() async {
// var Response = await DioClient().apiCall(
// url: 'https://reqres.in/api/users?page=2',
// requestType: RequestType.GET,
// // queryParameters: {},
// );
// // List<dynamic> listUser = Response.data;
// // OR
// List<dynamic> listUser =
// Response.data['data']; // if you want to access data inside it
// List<User> users = listUser.map((e) => User.fromJson(e)).toList();
// }
as u can see here is my homepage. i make a freeze class and using dio client here.
Try this
class _myHomepageState extends State<myHomepage> {
List<User> user = [];
bool isLoading = false;
#override
void initState() {
initFunction();
super.initState();
}
void initFunction() async {
setState((){
isLoading= true;
})
user = await fetchData();
setState((){
isLoading = false;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: isLoading
? CircularProgressIndicator()
: ListView.builder(
itemBuilder: (context, index) {
return Column(children: [
Text(user[index].firstName!),
]);
},
itemCount: user.length,
);
),
));
}
Future<List<User>> fetchData() async {
var Response = await DioClient().apiCall(
url: 'https://reqres.in/api/users?page=2',
requestType: RequestType.GET,
// queryParameters: {},
);
if (Response.statusCode == 200) {
List<dynamic> listUser = Response.data['data'];
List<User> users = listUser.map((e) => User.fromJson(e)).toList();
return users;
} else {
return [];
}
}
}

My data isnt being refreshed when i try to refresh

When i refresh the data isnt fetching new data please help me
This is my method to fetch data from news org api
Future<List<Article>> getApi() async {
Response response = await get(Uri.parse(
"https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=apikey"));
if (response.statusCode == 200) {
Map<String, dynamic> json = jsonDecode(response.body);
List<dynamic> body = json['articles'];
List<Article> article = body.map((e) => Article.fromJson(e)).toList();
return article;
} else {
throw ("cant get the articles");
}
}
this is my builder to show data
body: FutureBuilder<List<Article>>(
future: futureWords,
builder: (context, AsyncSnapshot<List<Article>> snap) {
if (snap.hasData) {
List<Article> articles = snap.data!;
return RefreshIndicator(
onRefresh: () {
setState(() {});
return _pullRefresh();
},
child: ListView.builder(
itemCount: 20,
itemBuilder: (context, index) {
return customListTile(articles[index]);
}),
);
} else {
return Center(child: CircularProgressIndicator());
}
}),
this is my pullrefresh method
Future<List<Article>> _pullRefresh() async {
List<Article> freshWords = await news.getApi();
setState(() {
futureWords = Future.value(freshWords);
});
return futureWords!;
}
May be it'll help you. If not - post your full code)
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
class Test2 extends StatefulWidget {
const Test2({Key? key}) : super(key: key);
#override
_Test2State createState() => _Test2State();
}
class Article {
String header='';
}
class _Test2State extends State<Test2> {
Future <List<Article>>? futureWords;
#override
void initState() {
super.initState();
_getNews();
}
_getNews() async {
var response = await http.get(Uri.parse(
"https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=aa20aef042a14de5b99a7f7d32952504"));
if (response.statusCode == 200) {
Map<String, dynamic> json = jsonDecode(response.body);
List<dynamic> body = json['articles'];
//List<Article> articles = body.map((e) => Article.fromJson(e)).toList();
List<Article> articles = [];
for (var el in body) {
Article article = Article();
article.header = el['title'];
articles.add(article);
}
articles.shuffle();
setState(() {
futureWords = Future.value(articles);
});
} else {
throw ("cant get the articles. statusCode ${response.statusCode}");
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<List<Article>>(
future: futureWords,
builder: (context, AsyncSnapshot<List<Article>> snap) {
if (snap.hasData) {
List<Article> articles = snap.data!;
return
RefreshIndicator(
onRefresh: () {
_getNews();
return futureWords!;
},
child: ListView.builder(
itemCount: 10,
itemBuilder: (context, index) {
return ListTile(title: Text(articles[index].header));
}),
);
} else {
return Center(child: CircularProgressIndicator());
}
}),
);
}
}