Linear Progress indicator could not manage its state while downloading files - flutter

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
);
}
}

Related

multiselection list view with data from DB

I am trying to read data from postgresql, display in listview, select (single/multiple) displayed items and process further. Able to do with sample data but while displaying data from Postgres DB facing challenges at highlighted area. Any suggestions would be appreciated.
(I am trying to read data from postgresql, display in listview, select (single/multiple) displayed items and process further. Able to do with sample data but while displaying data from Postgres DB facing challenges at highlighted area. Any suggestions would be appreciated.)
**app_db.dart**
import 'package:postgres/postgres.dart';
class AppDatabase {
PostgreSQLConnection? connection;
PostgreSQLResult? _fetchSellerDataResult;
AppDatabase() {
connection = (connection == null || connection!.isClosed == true
? PostgreSQLConnection("10.0.2.2", 5432, "dev", username: "postgres", password: "admin")
: connection);
fetchDataFuture = [];
}
// Fetch Data Section
List<dynamic> fetchDataFuture = [];
Future<List<dynamic>> fetchSellerData() async {
try {
await connection!.open();
await connection!.transaction((fetchDataConn) async {
_fetchSellerDataResult = await fetchDataConn.query(
"select cust_id, cust_name, mmt, available_amount, false AS isSelected from api_positionstest2",
allowReuse: false,
timeoutInSeconds: 30,
);
if (_fetchSellerDataResult!.affectedRowCount > 0) {
fetchDataFuture = _fetchSellerDataResult!.toList(growable: true);
} else {
fetchDataFuture = [];
} });
} catch (exc) {
fetchDataFuture = [];
exc.toString();
}
return fetchDataFuture;
}}
**model_positions.dart**
import 'package:e2/Models/app_db.dart';
class ModelsPositions {
List<dynamic> sellerDataFuture = [];
Future<List<dynamic>> fetchSellerData() async {
sellerDataFuture = await AppDatabase().fetchSellerData();
return sellerDataFuture;
}}
**MasterPositions.dart**
class MasterPositions {
String custID;
String custName;
double mtm;
double availableCash;
bool isSelected = false;
MasterPositions(
{required this.custID,
required this.custName,
required this.mtm,
required this.availableCash});}
**master_control.dart**
import 'package:flutter/material.dart';
import 'package:e2/Models/model_positions.dart';
class MasterControl extends StatefulWidget {
const MasterControl({super.key});
#override
State<MasterControl> createState() => _MasterControlState();
}
class _MasterControlState extends State<MasterControl> {
List<MasterPositions> selectedContacts = [];
List<MasterPositions> fetchedPositions = [];
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) => Scaffold(
body: FutureBuilder<List<dynamic>>(
future: ModelsPositions().fetchSellerData(),
builder: (context, snapshot) {
final positions = snapshot.data ?? [];
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
if (snapshot.hasError) {
return Center(child: Text('Error while loading Master Positions screen'));
} else {
return buildPositions(positions);
} } }), );
Widget buildPositions(List<dynamic> positions) {
return ListView.builder(
physics: BouncingScrollPhysics(),
itemCount: positions.length,
itemBuilder: (context, index) {
final pos = positions[index];
final custID = pos.elementAt(0).toString();
final custName = pos.elementAt(1).toString();
final mtm = double.tryParse(pos.elementAt(2)) ?? 0.0;
final availableCash = double.tryParse(pos.elementAt(3)) ?? 0.0;
final isSelected = pos.elementAt(4);
return ListTile(
horizontalTitleGap: -5,
title: Card(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(custID),
const SizedBox(height: 5),
Text(custName)],),),],),),
leading: isSelected
? Icon( Icons.check_circle, color: Colors.green[700],)
: const Icon(Icons.check_circle_outline, color: Colors.grey,),
onTap: () {
setState(() {
positions[index].elementAt(4) = !positions[index].elementAt(4); `**--> suggestion needed here**`
if (positions[index] == true) {
selectedContacts.add(
MasterPositions(custID: custID, custName: custName, mtm: mtm, availableCash: availableCash));
} else if (positions[index] == false) {
selectedContacts.removeWhere(
(element) => element.custID == pos[index].custID);
}}); }, );});}
}

Flutter - The operator '[]' isn't defined for the type 'Object'. - record not displayed with the widget

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;
}
}
}

Flutter download audio zip file and play in application

Hello friend i am new in flutter i need help i have project where almost different zip file hosted on sever every zip file have different audio with categories now i want if user want to download that zip file and extract audio then able to play in application it not visible in phone memory ?here example of code but this is for images and one zip file i take code from this url
https://www.coderzheaven.com/2019/06/07/download-zip-extract-it-and-show-the-images-file-in-list-in-ui/
here my code
import 'package:flutter/material.dart';
import 'dart:io';
import 'package:archive/archive.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
class DownloadAssetsDemo extends StatefulWidget {
DownloadAssetsDemo() : super();
final String title = "Download & Extract ZIP Demo";
#override
DownloadAssetsDemoState createState() => DownloadAssetsDemoState();
}
class DownloadAssetsDemoState extends State<DownloadAssetsDemo> {
//
bool _downloading;
String _dir;
List<String> _images, _tempImages;
String _zipPath = 'https://coderzheaven.com/youtube_flutter/images.zip';
String _localZipFileName = 'images.zip';
#override
void initState() {
super.initState();
_images = List();
_tempImages = List();
_downloading = false;
_initDir();
}
_initDir() async {
if (null == _dir) {
_dir = (await getApplicationDocumentsDirectory()).path;
}
}
Future<File> _downloadFile(String url, String fileName) async {
var req = await http.Client().get(Uri.parse(url));
var file = File('$_dir/$fileName');
return file.writeAsBytes(req.bodyBytes);
}
Future<void> _downloadZip() async {
setState(() {
_downloading = true;
});
_images.clear();
_tempImages.clear();
var zippedFile = await _downloadFile(_zipPath, _localZipFileName);
await unarchiveAndSave(zippedFile);
setState(() {
_images.addAll(_tempImages);
_downloading = false;
});
}
unarchiveAndSave(var zippedFile) async {
var bytes = zippedFile.readAsBytesSync();
var archive = ZipDecoder().decodeBytes(bytes);
for (var file in archive) {
var fileName = '$_dir/${file.name}';
if (file.isFile) {
var outFile = File(fileName);
//print('File:: ' + outFile.path);
_tempImages.add(outFile.path);
outFile = await outFile.create(recursive: true);
await outFile.writeAsBytes(file.content);
}
}
}
buildList() {
return Expanded(
child: ListView.builder(
itemCount: _images.length,
itemBuilder: (BuildContext context, int index) {
return Image.file(
File(_images[index]),
fit: BoxFit.fitWidth,
);
},
),
);
}
progress() {
return Container(
width: 25,
height: 25,
padding: EdgeInsets.fromLTRB(0.0, 20.0, 10.0, 20.0),
child: CircularProgressIndicator(
strokeWidth: 3.0,
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: <Widget>[
_downloading ? progress() : Container(),
IconButton(
icon: Icon(Icons.file_download),
onPressed: () {
_downloadZip();
},
),
],
),
body: Container(
child: Column(
children: <Widget>[
buildList(),
],
),
),
);
}
}
_initDir() async {
if (null == _dir) {
_dir = (await getApplicationDocumentsDirectory()).path;
print("current dir--$_dir")
}
}
use like this

Flutter: Catch data over Websocket, save it inside a Json and display it in a Chart

I hope somebody can help me out on a problem that i have.
I try to explain the problem the best i can.
The idea is the following for a Desktop App
First i tried to fetch and save data locally in a Json file that i get over WebSocket. What is working.
Second i tried to display the data of the local Json file inside a Chart. What is also working.
After i tried to combine the two above scenarios i one app and here i get the following error.
Exception has occurred.
FileSystemException (FileSystemException: read failed, path = 'C:\Users\7ke19\Documents/Measure/measure.json' (OS Error: The process cannot access the file because another process has locked a portion of the file.
, errno = 33))
In my app i am using the following packages.
Getx for the state manegment. https://pub.dev/packages/get
Localstorage for the Json storage. https://pub.dev/packages/localstorage
Syncfusion_flutter_charts for the Chart. https://pub.dev/packages/syncfusion_flutter_charts
Path_provider to get access to file and folders. https://pub.dev/packages/path_provider
I think i get the above error because at some moment inside my code the app is trying to read a write to the file at the same time.
Follows the code that i have.
The code is divided in three separated files.
Main Function:
import 'package:flutter/material.dart';
import 'package:flutter_application_2/controller/diagram_controller.dart';
import 'package:flutter_application_2/home_screen.dart';
import 'package:get/get.dart';
void main() async {
Get.put(DiagramController());
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const GetMaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
);
}
}
HomeScreen:
import 'package:flutter_application_2/controller/diagram_controller.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: GetBuilder<DiagramController>(
init: DiagramController(),
initState: (_) {},
builder: (gtxs1) {
return FutureBuilder(
future: gtxs1.getJsonData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
//********Showing if Websocket is Connected or Disconnected*******
child: gtxs1.connectedS1Status
? const Text(
"WEBSOCKET: CONNECTED",
style: TextStyle(
fontSize: 18,
color: Colors.green,
),
)
: const Text(
"WEBSOCKET: DISCONNECTED",
style: TextStyle(
fontSize: 18,
color: Colors.red,
),
),
),
//**********************Showing Range Diagram **********************
Column(
children: [
const Text(
'Range Diagram:',
),
const SizedBox(
height: 5,
),
SizedBox(
width: 800,
height: 280,
child: SfCartesianChart(
title: ChartTitle(
borderWidth: 2,
alignment: ChartAlignment.near,
),
series: gtxs1.getSeriesRange(),
legend: Legend(isVisible: true),
),
),
],
),
const SizedBox(
height: 20,
),
//**********************Showing Force Diagram **********************
Column(
children: [
const Text(
'Force Diagram:',
),
const SizedBox(
height: 5,
),
SizedBox(
width: 800,
height: 280,
child: SfCartesianChart(
title: ChartTitle(
borderWidth: 2,
alignment: ChartAlignment.near,
),
series: gtxs1.getSeriesForce(),
legend: Legend(isVisible: true),
),
),
],
),
],
);
} else {
return const CircularProgressIndicator();
}
},
);
},
),
);
}
}
Controller:
// ignore_for_file: avoid_print
import 'package:get/get.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:syncfusion_flutter_charts/charts.dart';
import 'package:path_provider/path_provider.dart';
import 'package:web_socket_channel/io.dart';
import 'package:localstorage/localstorage.dart';
final MeasureList list = MeasureList(); //List for LocalStorage
bool initialized = false; //for LocalStorage
int istcyclesJson = 0; //variable for istcycles
List<dynamic> istrangesensorJson = [0]; //variable for istrangesensor
List<dynamic> istforcesensorJson = [0]; //variable for istforcesensor
//***********************************************************************************************
//-----class MeasureItem for LocalStorage--------------------------------------------------------
//***********************************************************************************************
class MeasureItem {
int titleCountJson;
List<dynamic> titleRangeJson;
List<dynamic> titleForceJson;
MeasureItem({
required this.titleCountJson,
required this.titleRangeJson,
required this.titleForceJson,
});
toJSONEncodable() {
Map<String, dynamic> m = {};
m['count_array'] = titleCountJson;
m['range_array'] = titleRangeJson;
m['force_array'] = titleForceJson;
return m;
}
}
//***********************************************************************************************
//-----class MeasureList for LocalStorage--------------------------------------------------------
//***********************************************************************************************
class MeasureList {
List<MeasureItem> items = [];
toJSONEncodable() {
return items.map((item) {
return item.toJSONEncodable();
}).toList();
}
}
class DiagramController extends GetxController {
static DiagramController get to => Get.find();
List<List<ChartDataRange>> dataListRange = [];
List<List<ChartDataForce>> dataListForce = [];
LocalStorage storage = LocalStorage('/Measure/measure.json');
final MeasureList list = MeasureList();
late IOWebSocketChannel channel;
late bool connectedS1Status;
Directory? rootPath;
//**********************************************************************
#override
void onInit() {
connectedS1Status = false;
createFileFolder();
Future.delayed(
Duration.zero,
() async {
channelconnect();
},
);
Future.delayed(
const Duration(milliseconds: 1000),
() async {
loadStringRange();
loadStringForce();
},
);
super.onInit();
}
//***********************************************************************************************
//-----Channelconnect----------------------------------------------------------------------------
//***********************************************************************************************
channelconnect() {
try {
channel = IOWebSocketChannel.connect("ws://192.168.1.100:80");
channel.stream.listen(
(message) {
print(message);
Map<String, dynamic> jsondat = json.decode(message);
String data = json.encode(jsondat);
if (data.contains("cycle")) {
connectedS1Status = true;
update();
}
if (data.contains("count_array")) {
istcyclesJson = jsondat['count_array'];
istrangesensorJson = jsondat['range_array'];
istforcesensorJson = jsondat['force_array'];
_save();
//update();
}
},
onDone: () {
print("Web socket is closed");
connectedS1Status = false;
},
onError: (error) {
print(error.toString());
},
);
} catch (_) {
print("error on connecting to websocket.");
}
//update();
}
//***********************************************************************************************
//-----Functions to create and generate Json List using LocalStorage-----------------------------
//***********************************************************************************************
//...................................................
void _save() {
_addItem(istcyclesJson, istrangesensorJson, istforcesensorJson);
print("SAVE");
// update();
}
//...................................................
_addItem(int titlecount, List<dynamic> titlerange, List<dynamic> titleforce) {
final item = MeasureItem(
titleCountJson: titlecount,
titleRangeJson: titlerange,
titleForceJson: titleforce);
list.items.add(item);
_saveToStorage();
//update();
}
//...................................................
_saveToStorage() {
storage.setItem('measure', list.toJSONEncodable());
//update();
}
//***********************************************************************************************
//-----Functions to create Folder and File if not exist and write to the file some zero values
//-----not to get error when display the chart and the file is empty
//***********************************************************************************************
Future<File> createFileFolder() async {
rootPath = await getApplicationDocumentsDirectory();
Directory sampleFolder = Directory('${rootPath!.path}/Measure');
if (!sampleFolder.existsSync()) {
sampleFolder.createSync();
}
File sampleFile =
await File('${sampleFolder.path}/measure.json').create(recursive: true);
if (!sampleFile.existsSync()) {
sampleFolder.createSync();
}
final file = sampleFile;
return file.writeAsString(
'{"measure": [{"count": 0,"range_array": [0,0,0],"force_array": [0,0,0]}]}');
}
//**********************************************************************
Future<String> getJsonData() async {
rootPath = await getApplicationDocumentsDirectory();
Directory sampleFolder = Directory('${rootPath!.path}/Measure');
await File('${sampleFolder.path}/measure.json').create(recursive: true);
return await File('${sampleFolder.path}/measure.json').readAsString();
}
//**********************************************************************
Future loadStringRange() async {
final String jsonString = await getJsonData();
final dynamic jsonResponse = json.decode(jsonString);
List<dynamic> values = jsonResponse['measure'].last['range_array'];
List<ChartDataRange> chartDataR = [];
for (var j = 0; j < values.length; j++) {
chartDataR.add(ChartDataRange(j, values[j]));
}
dataListRange.add(chartDataR);
update();
}
//**********************************************************************
Future loadStringForce() async {
final String jsonString = await getJsonData();
final dynamic jsonResponse = json.decode(jsonString);
List<dynamic> values = jsonResponse['measure'].last['force_array'];
List<ChartDataForce> chartDataF = [];
for (var j = 0; j < values.length; j++) {
chartDataF.add(ChartDataForce(j, values[j]));
}
dataListForce.add(chartDataF);
update();
}
//**********************************************************************
List<ChartSeries<ChartDataRange, num>> getSeriesRange() {
List<ChartSeries<ChartDataRange, num>> seriesListRange = [];
for (var index = 0; index < dataListRange.length; index++) {
seriesListRange.add(
SplineSeries<ChartDataRange, num>(
dataSource: dataListRange[index],
xValueMapper: (ChartDataRange data, _) => data.x,
yValueMapper: (ChartDataRange data, _) => data.y,
),
);
}
return seriesListRange;
}
//**********************************************************************
List<ChartSeries<ChartDataForce, num>> getSeriesForce() {
List<ChartSeries<ChartDataForce, num>> seriesListForce = [];
for (var index = 0; index < dataListForce.length; index++) {
seriesListForce.add(
SplineSeries<ChartDataForce, num>(
dataSource: dataListForce[index],
xValueMapper: (ChartDataForce data, _) => data.x,
yValueMapper: (ChartDataForce data, _) => data.y,
),
);
}
return seriesListForce;
}
}
//**********************************************************************
class ChartDataRange {
final num x;
final num y;
ChartDataRange(this.x, this.y);
}
//**********************************************************************
class ChartDataForce {
final num x;
final num y;
ChartDataForce(this.x, this.y);
}

Flutter show to split very long text and show by dividing?

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;
}