I am migrating my ionic app to flutter i have some data which need to split and show.
The string look like this PRE-AUTHORIZATION=MANDATORY AT NON-PANEL HOSPITALS|||||HOSPITAL NETWORK=220+ FACILITIES NATIONWIDE|||||
I need to break the line when ||||| this come split the word on =
The code in typescript look something like this
const policies = this.wording.split('|').filter(w => w !== '');
this.displayData = [];
policies.forEach((policy) => {
const splited = policy.split('=');
const displayPolicy = {name: splited[0], value: splited[1]};
this.displayData.push(displayPolicy);
});
In app the string look like this
Any one please tell how can i show this data in flutter app same like in image Thanks
This is my full code i am using
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import 'dart:convert';
import 'dart:io';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class BenefitScreen extends StatefulWidget {
#override
_BenefitScreenState createState() => _BenefitScreenState();
}
class _BenefitScreenState extends State<BenefitScreen> {
#override
initState() {
super.initState();
doSomeAsyncStuff();
}
Future<String> doSomeAsyncStuff() async {
final storage = new FlutterSecureStorage();
String value = await storage.read(key: 'company_id');
print(value);
String url2 =
'gttps://api?company_id=${value}';
final response2 = await http.get(url2);
var Data = json.decode(response2.body);
print(Data);
print(Data["records"][0]["policies"][0]["policywording"]);
var DisplayData = Data["records"][0]["policies"][0]["policywording"]; // This is the data which need to split
return DisplayData;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('IGI GENERAL INSURANCE'),
),
body: FutureBuilder<String>(
future: doSomeAsyncStuff(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.hasData) {
print(snapshot.data);
return Text('Here in ned to show data');
} else if (snapshot.hasError) {
return Padding(
padding: const EdgeInsets.only(top: 16),
child: Text('Error: ${snapshot.error}'),
);
} else {
return Padding(
padding: EdgeInsets.only(top: 16),
child: Text('Awaiting result...'),
);
}
}),
);
}
}
And there is one more thing all string not contain = sign to split. i have attached the image as you can see first value dont have have = sign and its showing in blue text.
The code in typescript can be converted to following method:
List<Map<String, String>> divideString(String wording) {
final policies = wording.split('|').where((w) => w != '');
var displayData = <Map<String, String>>[];
policies.forEach((policy) {
final splitted = policy.split('=');
final displayPolicy = <String, String>{
'name': splitted[0],
'value': splitted.length > 1 ? splitted[1] : null,
};
displayData.add(displayPolicy);
});
return displayData;
}
Related
I am trying to do a compound query. If this one works, then I want to display the results in a listView.builder.
The records are not displayed properly. I do not understand why. I must display the name field of each document find using the query. I have tried different options, but the result is also an error.
Thank you.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class LoadDataFromFirestore extends StatefulWidget {
const LoadDataFromFirestore({super.key});
#override
State<LoadDataFromFirestore> createState() => _LoadDataFromFirestoreState();
}
class _LoadDataFromFirestoreState extends State<LoadDataFromFirestore> {
QuerySnapshot? querySnapshot;
#override
void initState() {
super.initState();
myQuery().then((results) {
setState(() {
querySnapshot = results;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: _showDrivers(),
);
}
Widget _showDrivers() {
if (querySnapshot != null) {
return ListView.builder(
primary: false,
itemCount: querySnapshot?.docs.length,
padding: const EdgeInsets.all(12),
itemBuilder: (context, i) {
return Column(
children: <Widget>[
Text(querySnapshot!.docs[i].data().toString()),
],
);
},
);
} else {
return const Center(
child: CircularProgressIndicator(),
);
}
}
Future myQuery () async{
final uid = FirebaseAuth.instance.currentUser!.uid;
final path = 'Users/$uid/allTasks';
final currentQuery = FirebaseFirestore.instance.collection(path);
Query statusQuery = currentQuery.where('status', isEqualTo: 'Next Action');
Query importantQuery = statusQuery.where('important', isEqualTo: 'False');
final snapshot = await importantQuery.get();
final data = snapshot.docs;
if(data.isNotEmpty){
for(var i =0; i < data.length; i++){
print(data[i].data());
return Text(data[i]['name']);
}
return data;
}
}
}
Since I can't test this, my guess is that the view is not refreshing properly since you used an function to get that widget.
Also you're returning an widget (Text) instead of the expected response that is of type QuerySnapshot.
Also you're returning data at the end which is a List and not the snapshot.
Go ahead and try this please:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class LoadDataFromFirestore extends StatefulWidget {
const LoadDataFromFirestore({super.key});
#override
State<LoadDataFromFirestore> createState() => _LoadDataFromFirestoreState();
}
class _LoadDataFromFirestoreState extends State<LoadDataFromFirestore> {
QuerySnapshot? querySnapshot;
#override
void initState() {
super.initState();
myQuery().then((results) {
setState(() {
querySnapshot = results;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: querySnapshot != null ? ListView.builder(
primary: false,
itemCount: querySnapshot?.docs.length,
padding: const EdgeInsets.all(12),
itemBuilder: (context, i) {
return ListTile(
title: Text(querySnapshot!.docs[i].data().toString()),
);
},
) : Center(
child: CircularProgressIndicator(),
)
);
}
Future myQuery () async{
final uid = FirebaseAuth.instance.currentUser!.uid;
final path = 'Users/$uid/allTasks';
final currentQuery = FirebaseFirestore.instance.collection(path);
Query statusQuery = currentQuery.where('status', isEqualTo: 'Next Action');
Query importantQuery = statusQuery.where('important', isEqualTo: 'False');
final snapshot = await importantQuery.get();
final data = snapshot.docs;
if(data.isNotEmpty){
//for(var i =0; i < data.length; i++){
// print(data[i].data());
// return Text(data[i]['name']);
//}
return snapshot;
}
}
}
I try to get a List from this Api(https://www.getpostman.com/collections/fa1296508e65891de558)
But there does no appear any Object. Console showing => "E/LB (26008): fail to open file: No such file or directory
".
I tried to print respone.statusCode but the result does'n apper in console.
I hope to solve this problem, Thank you.
What can be the problem here?
My code:
class ApiSetting{
static const String _baseUri='http://demo-api.mr-dev.tech/api/';
static const String users= '${_baseUri}users';
}
**User Model
** class User {
late int id;
late String firstName;
late String lastName;
late String email;
late String mobile;
late String bio;
late String jobTitle;
late String latitude;
late String longitude;
late String country;
late String image;
late String active;
late String emailVerifiedAt;
late String imagesCount;
User.fromJson(Map<String, dynamic> json) {
id = json['id'];
firstName = json['first_name'];
lastName = json['last_name'];
email = json['email'];
mobile = json['mobile'];
bio = json['bio'];
jobTitle = json['job_title'];
latitude = json['latitude'];
longitude = json['longitude'];
country = json['country'];
image = json['image'];
active = json['active'];
emailVerifiedAt = json['email_verified_at'];
imagesCount = json['images_count'];
}
}
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:api_secand_project/api/api_setting.dart';
import 'package:api_secand_project/models/user.dart';
class UserApiController {
Future<List<User>> getUser() async {
var uri = Uri.parse(ApiSetting.users);
var response = await http.get(uri);
if (response.statusCode == 200) {
print(response.statusCode);
var jsonResponse = jsonDecode(response.body);
var userJsonArray = jsonResponse['data'] as List;
return userJsonArray
.map((jsonObject) => User.fromJson(jsonObject))
.toList();
}
return [];
}
}
import 'package:api_secand_project/api/controllers/user_api_controller.dart';
import 'package:api_secand_project/models/user.dart';
import 'package:flutter/material.dart';
class UsersScreen extends StatefulWidget {
const UsersScreen({Key? key}) : super(key: key);
#override
State<UsersScreen> createState() => _UsersScreenState();
}
class _UsersScreenState extends State<UsersScreen> {
List<User> _users=<User>[];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Users'),
),
body: FutureBuilder<List<User>>(
future: UserApiController().getUser(),
builder: (context, snapshot) {
if(snapshot.connectionState == ConnectionState.waiting){
return const Center(
child: CircularProgressIndicator(),
);
}
else if(snapshot.hasData){
_users=snapshot.data!;
return ListView.builder(
itemCount: _users.length,
itemBuilder: (context, index) {
return ListTile(
leading: CircleAvatar(
radius: 30,
// child: NetworkImage(snapshot.data!.),
),
title: Text(_users[index].firstName),
subtitle: Text(_users[index].mobile),
);
},
);
}
else{
return Center(child: Text('No Data',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 28),),);
}
},
));
}
}
The question was not very clear, and there is no clear screenshot or message from the error console,
It seems that you are using the BLOC pattern and since part of the code is missing, you decide to create one from scratch, maybe it will help you, I thought not to publish it, but maybe something from here will help you
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class GetApi extends StatefulWidget {
const GetApi({super.key});
#override
State<GetApi> createState() => _GetApiState();
}
class _GetApiState extends State<GetApi> {
List<User> users = [];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("Get Api")),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ElevatedButton(
onPressed: () {
getApi();
},
child: const Text("Get Api"),
),
Flexible(
child: ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
User user = users[index];
return ListTile(
title: Text(user.name),
subtitle: Text(user.id),
);
}),
),
],
),
);
}
Future<void> getApi() async {
users = [];
Uri uri = Uri.parse("https://www.getpostman.com/collections/fa1296508e65891de558 ");
http.Response response = await http.get(uri);
if (response.statusCode == 200) {
//debugPrint("body: ${response.body}");
Map data = jsonDecode(response.body);
for (MapEntry item in data.entries) {
//debugPrint("key: ${item.key} value: ${item.value}");
if ("item" == item.key) {
List usersResponse = data["item"];
//debugPrint("users: ${users}");
for (dynamic json in usersResponse) {
User user = User.fromJson(json);
users.add(user);
//debugPrint("user: ${_user.name}");
}
}
}
if (!mounted) return;
setState(() {});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("succes -> status: ${response.statusCode}"),
backgroundColor: Colors.green,
),
);
} else {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("fail -> status: ${response.statusCode}"),
backgroundColor: Colors.red,
),
);
}
}
}
class User {
late String name;
late String id;
User.fromJson(Map<String, dynamic> json) {
name = json['name'];
id = json['id'];
}
}
I am new to Flutter and am currently working on a Flutter app that downloads files from given links. The issue is that when only one link app is working fine but when more than one link arrive file does not download. I receive the link data in json file then I parsed the json and used these links inside the listview.builder. I tried very much but could not find the solution. Here is the code for the screen. Main issue is that I think state is not managed well.
dsharing.json file contain name and links of files
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import '../services/services.dart';
class ReceiveScreen extends StatefulWidget {
const ReceiveScreen({Key? key, }) : super(key: key);
#override
State<ReceiveScreen> createState() => _ReceiveScreenState();
}
class _ReceiveScreenState extends State<ReceiveScreen> {
Map<int, double> progress = {};
int received = 0;
int total = 0;
var _url = "http://192.168.1.100:50500";
List<Receiver> receivers = [];
#override
initState()
{
super.initState();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Receive Files"),
) ,
body: Column(
children: [
ElevatedButton(
onPressed: ()async
{
await getUrls();
},
child: const Text("Get Response")
),
Text(rsponse),
FutureBuilder(
future: getUrls(),
builder: (context, AsyncSnapshot<Files> snapshot)
{
if(!snapshot.hasData)
{
return const Center(child: CircularProgressIndicator());
}
Files files = snapshot.data!;
return ListView.builder(
itemCount: files.names!.length,
shrinkWrap: true,
itemBuilder: (context, index)
{
return Column(
children: [
ElevatedButton(
onPressed: () async
{
final path = "/storage/emulated/0/Download/${files.names![index]}";
await Dio().download(
files.urls![index],
path,
onReceiveProgress: (received, total)
{
progress[index] = received/total;
}
);
},
child: Text("${files.names![index] } Download")
),
LinearProgressIndicator(
value: progress[index],
minHeight: 20,
)
],
);
}
);
}
)
],
)
);
}
String rsponse = "";
fetchDataApi() async
{
var response = await get(Uri.parse("$_url/dsharing.json"));
if(response.statusCode == 200)
{
return jsonDecode(response.body);
}
}
Future<Files> getUrls() async
{
var data = await fetchDataApi();
return Files.fromJson(data, _url);
}
}
class Files
{
final List? names;
final List? urls;
Files({ this.names, this.urls});
factory Files.fromJson(Map map, String url)
{
var fileNames = [];
String name = map['name'];
if(name.contains(":"))
{
int index = name.indexOf(":") + 1;
name = name.substring(index + 1, name.length);
var x = name.replaceAll(" ", '^*&');
fileNames = x.split("^*&").toList();
}
else
{
fileNames.add(name);
}
var x = map['data'].toString().split("|dsharing|").toList();
var fileUrls = x.map((i) => url + "?/q="+ i).toList();
return Files(
names: fileNames,
urls: fileUrls
);
}
}
I want to render all of the pdfs' first page as images and pass them to Home Screen. I make Splash Screen's duration to 30second. But I think it is not right because there can be hundreds of pdfs in someone's phone storage and Splash Screen's duration can be longer than 30seconds. So is there any solution to my problem? Here is my code. Enlighten me pls.
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:native_pdf_renderer/native_pdf_renderer.dart';
import 'package:splash_screen_view/SplashScreenView.dart';
import 'constant.dart';
import 'package:permission_handler/permission_handler.dart';
import 'home_screen.dart';
class Splashscreens extends StatefulWidget {
_SplashscreensState createState() => _SplashscreensState();
}
class _SplashscreensState extends State<Splashscreens> {
List<FileSystemEntity>? filepdf;
List<Uint8List>? imagepdf = [];
void initState() {
super.initState();
getFile();
}
getFile() async {
await Permission.storage.request();
final myDir = Directory('/storage/emulated/0/documents/');
filepdf = myDir.listSync(recursive: true, followLinks: true);
for (int index = 0; index < filepdf!.length; index++) {
final document = await PdfDocument.openFile(filepdf![index].path);
final page = await document.getPage(1);
final pageImage = await page.render(width: page.width, height: page.height);
setState(() {
imagepdf!.add(pageImage!.bytes);
});
}
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: SplashScreenView(
navigateRoute: HomeScreen(filepdf, imagepdf),
duration: 25000,
imageSize: 650,
imageSrc: "assets/image/jensenpdfviewerlogo.jpg",
colors: [
Colors.purple,
Colors.blue,
Colors.yellow,
Colors.red,
Colors.orange,
Color(0xFFECECEC)
],
pageRouteTransition: PageRouteTransition.SlideTransition,
text: "LOADING......",
textType: TextType.ColorizeAnimationText,
textStyle: fontStyle,
backgroundColor: Color(0xFF4E4AC2),
),
),
);
}
}
Here is my suggestion
class Splashscreens extends StatefulWidget {
_SplashscreensState createState() => _SplashscreensState();
}
class _SplashscreensState extends State<Splashscreens> {
List<FileSystemEntity>? filepdf;
List<Uint8List>? imagepdf = [];
Future<Map<String, dynamic>> getFile() async {
await Permission.storage.request();
final myDir = Directory('/storage/emulated/0/documents/');
filepdf = myDir.listSync(recursive: true, followLinks: true);
for (int index = 0; index < filepdf!.length; index++) {
final document = await PdfDocument.openFile(filepdf![index].path);
final page = await document.getPage(1);
final pageImage = await page.render(width: page.width, height: page.height);
setState(() {
imagepdf!.add(pageImage!.bytes);
});
}
var data = {
"file_pdf": filepdf,
"image_pdf": imagepdf
};
return data;
}
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: getFile(),
builder: (BuildContext context, AsyncSnapshot<Map<String, dynamic>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.done:
Map<String, dynamic> data = snapshot.data!;
List<FileSystemEntity>? _filePdf = data["file_pdf"];
List<Uint8List>? _imagepdf = data["image_pdf"];
return YourResultScreen();
default:
return Container();
}
}
);
}
}
I'm developing a Flutter mobile application which uses Google APIs. In one of the screens of my application I want to let the user type in a place (city, address, ...) and call the Google Places API to generate a list of suggestions based on user input. Whenever the text input changes a new GET request is issued.
To handle user input I am using a TextEditingController and in order to have a better user experience I want to use FutureBuilder class in order to show a loading spinner when the data is not ready. This is the code:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
class Info extends StatefulWidget {
static const routeName = '/info';
#override
_InfoState createState() => _InfoState();
}
class _InfoState extends State<Info> {
final controller = TextEditingController();
#override
void initState() {
// Start listening to changes.
controller.addListener(buildPredictionList);
super.initState();
}
#override
void dispose() {
// Clean up the controller when the widget is disposed.
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Info'),
),
body: Column(
children: <Widget>[
TextField(
controller: controller,
),
Container(
height: 200,
child: buildPredictionList(),
),
],
),
);
}
Widget buildPredictionList() {
return FutureBuilder(
future: fetchPredictions, // <-- Error! fetchPredictions expects a parameter!
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
Prediction pred = snapshot.data[index];
return Card(
child: ListTile(
leading: Icon(Icons.pin_drop),
title: Text('${pred.description}'),
),
);
},
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return CircularProgressIndicator();
},
);
}
}
class Prediction {
final String placeId;
final String description;
Prediction({this.placeId, this.description});
factory Prediction.fromJson(Map<String, dynamic> json) {
return Prediction(
placeId: json['place_id'],
description: json['description'],
);
}
}
Future<List<Prediction>> fetchPredictions(String query) async {
const GOOGLE_API_KEY = '...';
final lat = 40.758058;
final lng = -73.985626;
final radius = 2000;
final lang = 'en';
var url =
'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=$query&key=$GOOGLE_API_KEY&location=$lat,$lng&radius=$radius&language=$lang&strictbounds=true';
final response = await http.get(url);
if (response.statusCode == 200) {
var predictionsJson = json.decode(response.body)['predictions'] as List;
List<Prediction> predictions = predictionsJson
.map((predictionJson) => Prediction.fromJson(predictionJson))
.toList();
return predictions;
} else {
throw Exception('Failed to fetch Predictions');
}
}
My async function fetchPredictions expects an argument, which is the query string used for the GET request (so the input address, city, ...). But I cannot wrap this in an anonymous function because the future argument is expecting a return type of Future.
Thanks in advance!