How to call and show the data from an api, in IconButton - flutter

I want to call and show the data '800000.00' which is coming from an api, just below of the IconButton text 'ক্যাশ'
I have created a widget to click and show data from an api which uses get request. I want to show the api data just below of the Text('ক্যাশ') of this button:
Widget _buildCashDetailsBtn() {
return Column(
children: <Widget>[
IconButton(
iconSize: 50,
icon: const Icon(
Icons.directions_bike,
color: Color.fromARGB(255, 4, 219, 93),
),
onPressed: () {
setState(
() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => CashDetailsAPI()),
);
},
);
},
),
Text('ক্যাশ'),
],
);
}
The Future I have created for loading the data from the api is below:
Future<List<Welcome>> getData() async {
final response = await http.get(
Uri.parse('http://202.191.120.42:5000/api/ReportData/GetCashAmount'));
var data = jsonDecode(response.body.toString());
if (response.statusCode == 200) {
for (Map<String, dynamic> index in data) {
welcome.add(Welcome.fromJson(index));
}
return welcome;
} else {
return welcome;
}
}

Related

Riverpood does not update the status until I enter the screen

I have a general configuration screen, with a button that syncs the data
(...)
appBar: AppBar(
actions: [
Row(
children: [
const Text(ConfigurationsStringsUI.updateGeneral),
IconButton(
icon: const Icon(Icons.sync),
onPressed: () {
ref.read(listProductController.notifier).syncProducts();
ref.read(listEmployedController.notifier).syncEmployees();
},
),
],
)
],
),
(...)
In the case of products, it has a specific screen that is responsible for managing them, basically a CRUD. When I press the sync button, the idea is to connect to supabase and update the data. While this is happening display a loadign. The problem is that the loading does not appear.
products_page.dart
GetIt sl = GetIt.instance;
class CRUDProduct extends ConsumerWidget {
#override
Widget build(BuildContext context, WidgetRef ref) {
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {
Navigator.of(context).pop();
},
),
actions: [
IconButton(
onPressed: () {
ref.read(listProductController.notifier).syncProducts();
},
icon: const Icon(Icons.update),
)
],
),
floatingActionButton: ref.watch(isVisibleFabProducts)
? FloatingActionButton(
onPressed: () {
showDialog(
context: scaffoldKey.currentContext!,
builder: (context) => AddProductDialog(),
);
},
child: const Icon(Icons.fastfood),
)
: null,
body: ref.watch(listProductController).when(
data: (products) {
if (products.isEmpty) {
return const Center(
child: Text(ProductStringsUI.emptyList),
);
} else {
return NotificationListener<UserScrollNotification>(
onNotification: (notification) {
if (notification.direction == ScrollDirection.forward) {
ref.read(isVisibleFabProducts.notifier).state = true;
}
if (notification.direction == ScrollDirection.reverse) {
ref.read(isVisibleFabProducts.notifier).state = false;
}
return true;
},
child: ListView.separated(
shrinkWrap: true,
itemBuilder: (context, index) {
return ItemProductList(product: products[index]);
},
separatorBuilder: (_, __) => const Divider(
color: Colors.grey,
),
itemCount: products.length),
);
}
},
error: (error, stackTrace) {
return const Center(
child: Text(ProductStringsUI.errorList),
);
},
loading: () {
return const Center(child: CircularProgressIndicator());
},
));
}
}
Product provider:
final listProductController =
StateNotifierProvider<ProductController, AsyncValue<List<LocalProduct>>>(
(ref) => ProductController(ref));
product_controller.dart
class ProductController extends StateNotifier<AsyncValue<List<LocalProduct>>> {
ProductController(this._ref) : super(const AsyncValue.loading()) {
getProducts();
}
final Ref _ref;
Future<void> getProducts() async {
try {
final employees = await sl.get<ListProductUseCase>().getProducts();
if (mounted) {
state = AsyncValue.data(employees);
}
} catch (e) {
state = AsyncValue.error(e, StackTrace.current);
}
}
Future<void> syncProducts() async {
try {
_ref.read(listCategoryController.notifier).state =
const AsyncValue.loading();
_ref.read(listEmployedController.notifier).state =
const AsyncValue.loading();
state = const AsyncValue.loading();
await _ref.read(listCategoryController.notifier).syncCategory();
final employees = await sl.get<SyncProductUseCase>().syncProducts();
state.whenData((value) {
if (mounted) {
state = AsyncValue.data([...value, ...employees]);
}
});
_ref.invalidate(listProductController);
} catch (e) {
state = AsyncValue.error(e, StackTrace.current);
}
}
}
In the case of products, it has a specific screen that is responsible for managing them, basically a CRUD. When I press the sync button, the idea is to connect to supabase and update the data. While this is happening display a loadign. The problem is that the loading does not appear. There are two scenarios:
1-I open the app, I press the sync button on the configuration screen, I enter the screen in charge of managing the products, I see the loaded products, and at the moment it updates me with the new data, when I should see the loading and then the new ones data.
In this scenario is where my biggest doubt about the strange behavior is.
2-I open the app, I enter the screen in charge of managing the products, I go to the configuration screen, I press sync, and in that case if I go to enter if the loading appears
The same goes for employees.
When you have an async provider in Riverpod, you should tell it to load:
Future<void> addTopic(String name) async {
state = const AsyncValue.loading(); // Here
state = await AsyncValue.guard(() async { // And then you guard the value
// Inside the brackets do all the logic of the function
final currentId = ref.watch(currentSubjectProvider);
final topicRepo = ref.watch(topicRepoProvider);
await topicRepo.addTopic(currentId!, name);
return _getTopics();
});
}
This example of mine, is a real project I am working on, and this is loading as expected, but I should mention that I am using the Riverpod generator, so if the generator did something, I am unaware of it.
If you set the state to loading and guard the value, all listerners of that provider should be loading correctly.

When API hits successfully I wants to navigate to another page in flutter

My api response is: when api hits its give status code 200 but i got error unexpected end of json format and do not navigate to another page in flutter.
My controller
static Future<UserLogin> ForgetPassword(String email) async {
final response = await http.post(
Uri.parse(
'http://192.168.0.134:8080/AtdochubJ-3/send-otp?email=${email}'),
);
print(email);
print('response++ $response');
if (response.statusCode == 200) {
return UserLogin.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load UserLogin');
}
}
forget password button code:
Center(
child: ElevatedButton(
onPressed: () async {
final String email = emailController.text;
UserLogin res =
await LoginController.ForgetPassword(email);
print(res);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ResetPassword()));
},
child: const Text("Send OTP"),
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(
Color.fromARGB(255, 3, 89, 168))),
)),

Read data from Firestore reference

i have data stucture like:
/Admin/Dashboard/MRmZh9mixve1CV3M0EI8wfyDnb82/20220607/Anonymous/Entry
i want to read all that data that is under
/Admin/Dashboard/MRmZh9mixve1CV3M0EI8wfyDnb82
i tried this buts it returns empty
String collection = "/Admin/Dashboard/MRmZh9mixve1CV3M0EI8wfyDnb82";
await FirebaseFirestore.instance.collection(collection).get().then(
(res) => print("Successfully completed ${res}"),
onError: (e) => print("Error completing: $e"),
);
so basically i want lo read all the collections in it that has further documents in each collection
I could use this way to extract data from specific documents and collections.
final _firestore = FirebaseFirestore.instance;
void getMessages() async{
final docRef = await _firestore.collection('1234#123.com').doc('123123').collection('record').get();
for (var Ref in docRef.docs) {
print(Ref.data());
}
}
void getMessages44() async{
final docRef = await _firestore.collection('Admin').doc('Dashboard').collection('MRmZh9mixve1CV3M0EI8wfyDnb82').get();
for (var Ref in docRef.docs) {
print(Ref.data());
}
}
void test() async {
print("test");
// List<dynamic> userList = [];
QuerySnapshot querySnapshot = await _firestore.collection('1234#123.com').doc('123123').collection('record').where('Item', isEqualTo:"sdfsf").get();
// userList = querySnapshot.docs.map((e) => dynamic.User.fromMap(e.data())).toList();
final allData = querySnapshot.docs.map((doc) => doc.data()).toList();
// final allData = querySnapshot.docs.map((doc) => doc.get('fieldName')).toList();
print(allData);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Record'),
leading: null,
actions: <Widget>[
IconButton(
icon: const Icon(Icons.add),
onPressed: (){
Navigator.pushNamed(context, creationCategory.id);
},
),
IconButton(
icon: const Icon(Icons.settings),
onPressed: () async {
// await getData();
// getMessages();
// getMessages();
getMessages44();
test();
// getMessages33();
// Navigator.push(
// context,
// MaterialPageRoute(builder: (context) => const ItemDetailsScrrent()),
// );
},
),
],
),
body: SafeArea(
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Trahs Collection',
style: const TextStyle(
color: Colors.black38, fontWeight: FontWeight.bold, fontSize: 40),
),
ItemStream(),
],
),
),
),
);
}

Flutter response after scan

I need help regrading the scan using qr_code_scanner, the scanner successful but don't know how to call response either success or not. here example.
void _onQRViewCreated(QRViewController controller) {
this.controller = controller;
controller.scannedDataStream.listen((scanData) async {
controller.pauseCamera();
var response = await ScanApi.scan(scanData.code);
print(response);
result = scanData;
setState(() {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("check"),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text('Data: ${scanData.code}'),
],
),
),
actions: <Widget>[
TextButton(
child: Text('Ok'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
).then((value) => controller.resumeCamera());
and my example api post to get reponse.
static Future<dynamic> scan() async {
final url = Uri.parse(url);
final response = await http.post(url);
if (response.statusCode == 200) {
final String msg = json.decode(response.body)["status"];
print(msg);
return msg;
} else {
throw Exception();
}}
code like this and calling this class into widget.
class ScanResponse {
String status;
ScanResponse({this.status});
factory ScanResponse.fromJson(Map<String, dynamic> jsonData) {
return ScanResponse(
status: jsonData['status'],
);
}
}

share link on social media via several buttons in android and ios with flutter

These are three social media buttons.
I just want to share a link on social media via these buttons in Android as well as ios.
I used flutter_share_me plugin. but there are two problems with this plugin.
1.)This plugin is defined for only Android devices, not for ios.
2.)it isn't defined for Instagram.
CODE:
For Facebook:
IconButton(
icon: Image.asset("assets/icons/facebook_logo.png",fit:BoxFit.fill,color: Colors.white,),
onPressed: (){
FlutterShareMe().shareToFacebbok(url: appUrl, msg: "Babilok");
}
),
For Twitter:
IconButton(
icon: Image.asset("assets/icons/twitter_logo1.png",fit:BoxFit.fill,color: Colors.white,),
onPressed: (){
FlutterShareMe().shareToTwitter(url: appUrl, msg: "Babilok");
}
),
For Instagram:
IconButton(
icon: Image.asset("assets/icons/instagram_logo.png",fit:BoxFit.fill,color: Colors.white,),
onPressed: (){
?????????.....
}
),
You can use this plugin flutter_social_content_share
This plugin works fine both on iOS & Android as well.
/// SHARE ON FACEBOOK CALL
shareOnFacebook() async {
String result = await FlutterSocialContentShare.share(
type: ShareType.facebookWithoutImage,
url: "https://www.apple.com",
quote: "captions");
print(result);
}
/// SHARE ON INSTAGRAM CALL
shareOnInstagram() async {
String result = await FlutterSocialContentShare.share(
type: ShareType.instagramWithImageUrl,
imageUrl:
"https://post.healthline.com/wp-content/uploads/2020/09/healthy-eating-ingredients-732x549-thumbnail-732x549.jpg");
print(result);
}
/// SHARE ON WHATSAPP CALL
shareWatsapp() async {
String result = await FlutterSocialContentShare.shareOnWhatsapp(
number: "xxxxxx", text: "Text appears here");
print(result);
}
/// SHARE ON EMAIL CALL
shareEmail() async {
String result = await FlutterSocialContentShare.shareOnEmail(
recipients: ["xxxx.xxx#gmail.com"],
subject: "Subject appears here",
body: "Body appears here",
isHTML: true); //default isHTML: False
print(result);
}
/// SHARE ON SMS CALL
shareSMS() async {
String result = await FlutterSocialContentShare.shareOnSMS(
recipients: ["xxxxxx"], text: "Text appears here");
print(result);
}
///Build Context
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Column(
children: <Widget>[
Text('Running on: $_platformVersion\n'),
RaisedButton(
child: Text("Share to facebook button"),
color: Colors.red,
onPressed: () {
shareOnFacebook();
},
),
RaisedButton(
child: Text("Share to instagram button"),
color: Colors.red,
onPressed: () {
shareOnInstagram();
},
),
RaisedButton(
child: Text("Share to whatsapp button"),
color: Colors.red,
onPressed: () {
shareWatsapp();
},
),
RaisedButton(
child: Text("Share to email button"),
color: Colors.red,
onPressed: () {
shareEmail();
},
),
RaisedButton(
child: Text("Share to sms button"),
color: Colors.red,
onPressed: () {
shareSMS();
},
),
],
),
),
);
}
You can use package https://pub.dev/packages/social_share_plugin
package description forget to mention include twitter now
full example code
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:social_share_plugin/social_share_plugin.dart';
import 'package:image_picker/image_picker.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
#override
void initState() {
super.initState();
initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
platformVersion = await SocialSharePlugin.platformVersion;
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Column(
children: <Widget>[
Center(
child: Text('Running on: $_platformVersion\n'),
),
RaisedButton(
child: Text('Share to Instagram'),
onPressed: () async {
File file = await ImagePicker.pickImage(source: ImageSource.gallery);
await SocialSharePlugin.shareToFeedInstagram("image/*", file.path);
},
),
RaisedButton(
child: Text('Share to Facebook'),
onPressed: () async {
File file = await ImagePicker.pickImage(source: ImageSource.gallery);
await SocialSharePlugin.shareToFeedFacebook('test', file.path);
},
),
RaisedButton(
child: Text('Share to Facebook Link'),
onPressed: () async {
String url = 'https://flutter.dev/';
final quote =
'Flutter is Google’s portable UI toolkit for building beautiful, natively-compiled applications for mobile, web, and desktop from a single codebase.';
final result = await SocialSharePlugin.shareToFeedFacebookLink(
quote: quote,
url: url,
onSuccess: (postId) {
print('FACEBOOK SUCCESS $postId');
return;
},
onCancel: () {
print('FACEBOOK CANCELLED');
return;
},
onError: (error) {
print('FACEBOOK ERROR $error');
return;
},
);
print(result);
},
),
RaisedButton(
child: Text('Share to Twitter'),
onPressed: () async {
String url = 'https://flutter.dev/';
final text =
'Flutter is Google’s portable UI toolkit for building beautiful, natively-compiled applications for mobile, web, and desktop from a single codebase.';
final result = await SocialSharePlugin.shareToTwitter(
text: text,
url: url,
onSuccess: (_) {
print('TWITTER SUCCESS');
return;
},
onCancel: () {
print('TWITTER CANCELLED');
return;
});
print(result);
},
),
],
),
),
);
}
}
You can use pack Share social media plugin
final twitterLogin = new ShareSocialMediaPlugin(
consumerKey: "consumerKey",
consumerSecret: 'consumerSecret');
RaisedButton(
child: Text(titleTwitterButton, style: TextStyle(fontSize: 20)),
onPressed: () async {
//Platform in Android
if (Platform.isAndroid) {
var result = await twitterLogin.shareTwitter("conectado desde plugin");
print(result);
if(result != null){
if (result == "success"){
print("success!");
}else{
print("fail");
}
}
}
//Platform in iOS
else if (Platform.isIOS) {
var sessionTwitter = await twitterLogin.currentSessionIOS();
var tweet = await twitterLogin.shareTwitteriOS(
sessionTwitter["outhToken"],
sessionTwitter["oauthTokenSecret"],
"test cpmplete future",
twitterLogin.consumerKey,
twitterLogin.consumerSecret);
final response = json.decode(tweet.body);
if (response['text'] != null) {
print("success");
}else{
print("fail");
}
}
},
),
That plugin have support for instagram, twitter, line