I am from Javascript developer and start developing on flutter for company use.
I currently facing an issue about setting profile value to gui.
//profile.dart
import 'package:flutter/material.dart';
import 'package:profile/profile.dart';
import 'package:cs_app/models/user.dart';
import 'package:cs_app/models/cs_data.dart';
import 'package:cs_app/models/profile_data.dart';
import 'package:provider/provider.dart';
class AdminPage extends StatefulWidget {
const AdminPage({Key? key}) : super(key: key);
#override
State<AdminPage> createState() => _AdminPageState();
}
profile_value(key) async {
var value = await profileData.user_profile(key);
print("rtn: " + value);
// rtn: admin, can get the print value
return value;
}
class _AdminPageState extends State<AdminPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Profile(
imageUrl:
"https://images.unsplash.com/photo-1598618356794-eb1720430eb4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80",
name: profile_value("username"), // run func, get rtn value, render
website: profile_value("website"),
designation: profile_value("designation"),
email: "xxx#gmail.com",
phone_number: "12345456",
),
));
}
}
//profile_data.dart
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:cs_app/views/login.dart';
import 'dart:convert';
import 'package:cs_app/models/sharedPref.dart';
class profileData {
static user_profile(key) async {
var value = await SharedPref().read("user");
var decode_value = json.decode(value);
var key_decode_value = decode_value[key];
print("key: " + key);
print("value: " + key_decode_value);
// key: username
// value: admin
return key_decode_value;
}
}
In my mindset is when _AdminPageState run, the key will run profile_value(key) to get rtn value.
But it keeps return The argument type 'Future' can't be assigned to the parameter type 'String'.
Future<String>profile_value(key) async {
var value = await profileData.user_profile(key);
print("rtn: " + value);
// rtn: admin, can get the print value
return value;
}
Method profile_value is Future<String>, so you need to add await in front of name.
name: await profile_value("username"),
In flutter, if you use async func, it's will return a value the same Promise in JS. You must use await or .then to handle it.
Related
I am trying to download and show offline my html content in my app. Downloading media and converting to base64 string works fine for images. However, when it comes to audio and video, it doesnt work properly. I have tried on htmlviewer website and audio works. I am sharing exact same code with you.
import 'dart:convert';
import 'dart:developer';
import 'dart:io' as io;
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/basic.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pqsmobile/controllers/userController.dart' as userController;
import 'package:webview_flutter/webview_flutter.dart';
class HtmlDeneme extends StatefulWidget {
const HtmlDeneme({Key? key}) : super(key: key);
#override
State<HtmlDeneme> createState() => _HtmlDenemeState();
}
class _HtmlDenemeState extends State<HtmlDeneme> {
String? a ;
#override
Widget build(BuildContext context) {
return Scaffold(
body:
/*Column(
children: [
IconButton(
onPressed: (() async{
await _download("https://samplelib.com/lib/preview/mp3/sample-6s.mp3","aswd");
}),
icon: Icon(Icons.downhill_skiing),
),
Container(
height: 100,
child:
a != null ? WebView(
initialUrl: Uri.dataFromString(' <audio controls=\"controls\" controlslis=\"nodownload\" src="data:audio/mp3;base64,$a"/>', mimeType:'audio/mp3' ).toString(),
) : Container()
),
],
)*/
Column(
children: [
IconButton(
onPressed: (() async{
await _download("https://samplelib.com/lib/preview/mp3/sample-6s.mp3","aswdsadsa");
}),
icon: Icon(Icons.downhill_skiing),
),
a != null ?
Html(
data: '''<audio controls=\"controls\" controlslist=\"nodownload\" src="data:audio/mp3;base64,$a"/> ''',
)
/*Html(
data: '''<p><span style=\"font-family:Arial,Helvetica,sans-serif\"><span style=\"font-size:16px\"><span style=\"color:#ffffff\"><strong><span style=\"background-color:#2980b9\">Listen to the passage. For questions 1-5, choose the best answer.</span></strong></span></span></span></p>\n\n<div class=\"ckeditor-html5-audio\" style=\"float:left; margin-right:10px; text-align:left\">\n<audio controls=\"controls\" controlslist=\"nodownload\" src=\"http://app.pqsglobal.org/uploads/2022-02-01/uiFiles/2fac1d07-5e1e-47f1-968b-136e0c27da84.mp3\"> </audio>\n</div>\n\n<p> </p>\n\n<p> </p>\n\n<p> <img style=\"height:10px; width:50px\" src='data:image/png;base64,$a'"/></p>\n'''
)*/
: Container(),
],
),
);
}
_download(String url, String name) async {
Directory tempDir = await getApplicationDocumentsDirectory();
final file = File('${tempDir.path}/${name}');
try {
//log(internalDir!.path.toString());
final String tokenx = await userController.getToken();
final response = await Dio().get(url,
options: Options(
responseType: ResponseType.bytes,
followRedirects: false,
receiveTimeout: 0));
final raf = file.openSync(mode: io.FileMode.write);
raf.writeFromSync(response.data);
await raf.close();
setState(() {
final bytes = File('${tempDir.path}/${name}').readAsBytesSync();
a = base64Encode(bytes);
//log(a.toString());
});
return file;
} catch (e) {
log(e.toString());
}
}
}
I use this plugin in my flutter app - webview_flutter. I need to show the local HTML file in webview. This is not from assets, but I have a path to this file.
I try it:
Read the file as a string
var file = File(_path);
var data = await file.readAsString();
prepare the string
String _getHtml() {
var html = Uri.dataFromString(data, mimeType: 'text/html').toString();
return html;
}
Show this string in my webview
WebView(
initialUrl: _getHtml(),
)
But I have get error(on step Uri.dataFromString) :
How fix it? Any tips?
From here
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';
class HelpScreen extends StatefulWidget {
#override
HelpScreenState createState() {
return HelpScreenState();
}
}
class HelpScreenState extends State<HelpScreen> {
WebViewController _controller;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Help')),
body: WebView(
initialUrl: 'about:blank',
onWebViewCreated: (WebViewController webViewController) {
_controller = webViewController;
_loadHtmlFromAssets();
},
),
);
}
_loadHtmlFromAssets() async {
String fileText = await
rootBundle.loadString('assets/help.html');
_controller.loadUrl( Uri.dataFromString(
fileText,
mimeType: 'text/html',
encoding: Encoding.getByName('utf-8')
).toString());
}
}
I make an application with Google maps in which you can find a place and build a path to it on the map. I want to show places and addresses below it according to what the user types.After showing the results, I need to get its latitude and longitude to mark on the map.
I tried to use a flutter_google_places: 0.2.3 but functions(GoogleMapsPlaces, Prediction) were not defined. Next i used flutter_google_places_autocomplete: 0.1.3 and everything was fine. Unfortunately when i tride to run the project I got an error:
Compiler message:
file:///C:/Users/admin/AppData/Roaming/Pub/Cache/hosted/pub.dartlang.org/flutter_google_places_autocomplete-0.1.3/lib/src/flutter_google_places_autocomplete.dart:337:35:
Error: Too many positional arguments: 0 allowed, but 1 found. Try
removing the extra positional arguments.
_places = new GoogleMapsPlaces(widget.apiKey);
^ file:///C:/Users/admin/AppData/Roaming/Pub/Cache/hosted/pub.dartlang.org/google_maps_webservice-0.0.14/lib/src/places.dart:22:3:
Context: Found this candidate, but the arguments don't match.
GoogleMapsPlaces({ ^ Compiler failed on
C:\Users\admin\AndroidStudioProjects\advertise_me\lib\main.dart
FAILURE: Build failed with an exception.
Where: Script 'C:\Users\admin\flutter\packages\flutter_tools\gradle\flutter.gradle'
line: 647
What went wrong: Execution failed for task ':app:compileflutterBuildDebugandroid-arm64'.
Process 'command 'C:\Users\admin\flutter\bin\flutter.bat'' finished with non-zero exit value 1
Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
Get more help at https://help.gradle.org
BUILD FAILED in 9s Finished with error: Gradle task assembleDebug
failed with exit code 1
My pubspes.yaml:
dependencies: flutter:
sdk: flutter
cupertino_icons: ^0.1.2 url_launcher: ^4.2.0+1
google_maps_flutter: bottom_sheet_stateful: ^0.1.1
flutter_google_places_autocomplete: 0.1.3 geocoder: 0.1.2
google_maps_webservice: 0.0.14
My code:
import 'package:flutter/material.dart';
import 'package:advertise_me/login_screen.dart';
import 'dart:async';
import 'package:google_maps_webservice/geocoding.dart';
//import 'package:flutter_google_places/flutter_google_places.dart';
import 'package:flutter_google_places_autocomplete/flutter_google_places_autocomplete.dart';
import 'package:geocoder/geocoder.dart';
void main() => runApp(MyApp());
const kGoogleApiKey = "My key";
GoogleMapsPlaces _places = GoogleMapsPlaces(apiKey: kGoogleApiKey);
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: demo(),
),
);
}
}
class demo extends StatefulWidget {
#override
demoState createState() => new demoState();
}
class demoState extends State<demo> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
alignment: Alignment.center,
child: RaisedButton(
onPressed: () async {
Prediction p = await showGooglePlacesAutocomplete(
context: context, apiKey: kGoogleApiKey);
displayPrediction(p);
},
child: Text('Find address'),
)
)
);
}
Future<Null> displayPrediction(Prediction p) async {
if (p != null) {
PlacesDetailsResponse detail =
await _places.getDetailsByPlaceId(p.placeId);
var placeId = p.placeId;
double lat = detail.result.geometry.location.lat;
double lng = detail.result.geometry.location.lng;
var address = await Geocoder.local.findAddressesFromQuery(p.description);
print(lat);
print(lng);
}
}
}
How do i fix this error?
Any help is much appreciated.
flutter_google_places_autocomplete is deprecated and you should use flutter_google_places instead. See documentation : https://pub.dev/packages/flutter_google_places_autocomplete
And once you use flutter_google_places, use
Prediction p = await PlacesAutoComplete.show() instead of showGooglePlacesAutoComplete()
======= updated answer =====
import 'package:flutter/material.dart';
//import 'package:advertise_me/login_screen.dart';
import 'dart:async';
import 'package:flutter_google_places/flutter_google_places.dart';
import 'package:geocoder/geocoder.dart';
import 'package:google_maps_webservice/places.dart';
void main() => runApp(MyApp());
const kGoogleApiKey = "My key";
GoogleMapsPlaces _places = GoogleMapsPlaces(apiKey: kGoogleApiKey);
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: demo(),
),
);
}
}
class demo extends StatefulWidget {
#override
demoState createState() => new demoState();
}
class demoState extends State<demo> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
alignment: Alignment.center,
child: RaisedButton(
onPressed: () async {
Prediction p = await PlacesAutocomplete.show(
context: context, apiKey: kGoogleApiKey);
displayPrediction(p);
},
child: Text('Find address'),
)
)
);
}
Future<Null> displayPrediction(Prediction p) async {
if (p != null) {
PlacesDetailsResponse detail =
await _places.getDetailsByPlaceId(p.placeId);
var placeId = p.placeId;
double lat = detail.result.geometry.location.lat;
double lng = detail.result.geometry.location.lng;
var address = await Geocoder.local.findAddressesFromQuery(p.description);
print(lat);
print(lng);
}
}
}
use import 'package:google_maps_webservice/places.dart'; along with, import 'package:flutter_google_places/flutter_google_places.dart';
Use complete list of function parameters like:
Prediction p = await PlacesAutocomplete.show( offset: 0, radius: 1000, types: [], strictbounds: false,
region: "ar", context: context, apiKey: googleAPIKey, mode: Mode.overlay, language: "es", components: [Component(Component.country, "ar")] );
I have web application writed in React JS and Java Spring boot. In my Board Component I have form with textarea and button. While debugging when I click on button I am redirect to PostMapping in UserController spring project. My method has one parameter. It's #RequestBody String query.
I get text from textarea in HTML character codes in hex code. I need to plain text from this String.
I get something what look like this:
CREATE+TABLE+users+%28%0A%09id+INT%2C%0A%09fullName+VARCHAR%28220%29+NOT+NULL%2C%0A%09city+VARCHAR%28120%29+NOT+NULL%2C%0A%09country+VARCHAR%2860%29+NOT+NULL%2C%0A%09PRIMARY+KEY%28id%29%0A%29%3 ...
where + does mean space
I was trying resolve this problem.
Nothing works.
First way:
byte[] s = DatatypeConverter.parseHexBinary(query);
System.out.println(new String(s, "UTF-8"));
Second way:
Apache Commons Codec - Hex
byte[] bytes = Hex.decodeHex(query.toCharArray());
System.out.println(new String(bytes, "UTF-8"));
Here is my code
Spring project:
UserController class
#Controller
#RequestMapping("fiddle")
public class MainController {
#PostMapping
public ResponseEntity<?> processingQueries(#RequestBody String query) {
System.out.println(query);
return new ResponseEntity<String>("Query prcessed successfully.", HttpStatus.OK);
}
}
React JS project:
Board component
import React from 'react';
import TableButton from './TableButton';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { processQueries } from '../actions/queryActions';
class Board extends React.Component {
constructor() {
super();
this.state = {
query: 'Write here your SQL query...'
}
this.onChange = this.onChange.bind(this);
this.resetField = this.resetField.bind(this);
this.onSubmitRun = this.onSubmitRun.bind(this);
}
onChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
resetField(e) {
this.setState({ query: '' });
}
onSubmitRun(e) {
e.preventDefault();
console.log(this.state.query);
this.props.processQueries(this.state.query, this.props.history);
}
render() {
return (
<div className="box flex-stretch">
<div className="blue smallClass">
<TableButton />
</div>
<div className="mediumClass">
<form onSubmit={this.onSubmitRun}>
<textarea
name="query"
className="txtArea"
value={this.state.query}
onChange={this.onChange}
onClick={this.resetField}
rows="27"
>
Write here your SQL queries...
</textarea>
<input type="submit" value="Run" className="runButton"/>
</form>
</div>
<div className="red largeClass">
One of three columns
</div>
</div>
);
}
}
Board.propTypes = {
query: PropTypes.string
}
const mapStateToProps = state => ({
query: state.query
})
export default connect(mapStateToProps, { processQueries })(Board);
queryReducer
import { PROCESS_QUERY } from '../actions/types';
const initialState = {
query: ''
}
export default function(state = initialState, action) {
switch(action.type) {
case PROCESS_QUERY:
return {
...state,
query: action.payload
}
default:
return state;
}
}
queryActions
import axios from 'axios';
import { GET_ERRORS, PROCESS_QUERY } from './types';
export const processQueries = (query, history) => async dispatch =>
{
try {
console.log(query);
await axios.post("/fiddle", query);
history.push("/fiddle");
dispatch({
type: PROCESS_QUERY,
payload: ''
})
} catch(error) {
dispatch({
type: GET_ERRORS,
payload: error.response.data
})
}
}
I need to convert this string from textarea to plain text. Data inserted to textarea are plan SQL queries.
All you need to decode string with UrlDecoder.
String result = java.net.URLDecoder.decode(query, StandardCharsets.UTF_8.displayName());
For some reason the response JSON is not mapping correctly
Here is my html.
profile-search.component.html
<h3>Enter Username</h3>
<input (keyup)="search($event.target.value)" id="name" placeholder="Search"/>
<ul>
<li *ngFor="let package of packages$ | async">
<b>{{package.name}} v.{{package.repos}}</b> -
<i>{{package.stars}}</i>`enter code here`
</li>
</ul>
Here is component that the html pulls from.
profile-search.component.ts
import { Component, OnInit } from '#angular/core';
import { Observable, Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';
import { NpmPackageInfo, PackageSearchService } from './profile-search.service';
#Component({
selector: 'app-package-search',
templateUrl: './profile-search.component.html',
providers: [ PackageSearchService ]
})
export class PackageSearchComponent implements OnInit {
withRefresh = false;
packages$: Observable<NpmPackageInfo[]>;
private searchText$ = new Subject<string>();
search(packageName: string) {
this.searchText$.next(packageName);
}
ngOnInit() {
this.packages$ = this.searchText$.pipe(
debounceTime(500),
distinctUntilChanged(),
switchMap(packageName =>
this.searchService.search(packageName, this.withRefresh))
);
}
constructor(private searchService: PackageSearchService) { }
toggleRefresh() { this.withRefresh = ! this.withRefresh; }
}
Service that component pulls from.
profile-search.service.ts
import { Injectable, Input } from '#angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '#angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { HttpErrorHandler, HandleError } from '../http-error-handler.service';
export interface NpmPackageInfo {
name: string;
}
export const searchUrl = 'https://api.github.com/users';
const httpOptions = {
headers: new HttpHeaders({
'x-refresh': 'true'
})
};
function createHttpOptions(packageName: string, refresh = false) {
// npm package name search api
// e.g., http://npmsearch.com/query?q=dom'
const params = new HttpParams({ fromObject: { q: packageName } });
const headerMap = refresh ? {'x-refresh': 'true'} : {};
const headers = new HttpHeaders(headerMap) ;
return { headers, params };
}
#Injectable()
export class PackageSearchService {
private handleError: HandleError;
constructor(
private http: HttpClient,
httpErrorHandler: HttpErrorHandler) {
this.handleError = httpErrorHandler.createHandleError('HeroesService');
}
search (packageName: string, refresh = false): Observable<NpmPackageInfo[]> {
// clear if no pkg name
if (!packageName.trim()) { return of([]); }
// const options = createHttpOptions(packageName, refresh);
// TODO: Add error handling
return this.http.get(`${searchUrl}/${packageName}`).pipe(
map((data: any) => {
return data.results.map(entry => ({
name: entry.any[0],
} as NpmPackageInfo )
)
}),
catchError(this.handleError('search', []))
);
}
}
I have tried to alter
return this.http.get(`${searchUrl}/${packageName}`).pipe(
map((data: any) => {
return data.results.map(entry => ({
name: entry.any[0],
} as NpmPackageInfo )
)
to
login: data.login, and login: entry.login but keep getting the below error.
http-error-handler.service.ts:33 TypeError: Cannot read property 'map'
of undefined
at MapSubscriber.project (profile-search.service.ts:49)
at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next
(map.js:75)
at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next
(Subscriber.js:93)
at MapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/map.js.MapSubscriber._next
(map.js:81)
at MapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next
(Subscriber.js:93)
at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterSubscriber._next
(filter.js:85)
at FilterSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next
(Subscriber.js:93)
at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber.notifyNext
(mergeMap.js:136)
at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/InnerSubscriber.js.InnerSubscriber._next
(InnerSubscriber.js:20)
at InnerSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next
(Subscriber.js:93)
results in data.results is probably undefined, check that the data object matches the schema you're expecting it to.
map working on array but this.http.get(${searchUrl}/${packageName}) return object not array.
so data.results is undefined.
This is how I converted my object into an array, if anyone has a better way of doing please let me know.
return this.http.get(`${searchUrl}/${packageName}`).pipe(
map((data: any) => {
console.log(data);
var profile = Object.keys(data).map(function(key) {
return [(key) + ': ' + data[key]];
}
);
console.log(profile);
data = profile;
return data;
}),
catchError(this.handleError<Error>('search', new Error('OOPS')))
);
}
}
I fixed this issue by eliminating ".results"
from
.map((data: any) => this.convertData(data.results))
to
.map((data: any) => this.convertData(data))
To avoid the error, change
map((items) => items.map
to
map((items) => items?.map
Then set your result set as an empty array:
this.list = data ?? [];
PS: Used with Angular 14. In older versions you may need to change last one to data ? data : []