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.
I am consuming data from an API and whenever I try to do so, I keep getting this error.
Type List Dynamic Is Not A Subtype Of Type Map String Dynamic
In my attempt to find answers, I came across this Similar Question
I have also gone through this Another Similar Question
And this as well A similar question again
From this similar question, I realized that there seems to be a data structure mismatch but I can't seem to get the solution to it.
Below are excerpts of my code
This is the Object Model
class Book {
int? id = 0;
String? title = "";
String? description = "";
String? image = "";
String? author = "";
Book({
this.id,
this.title,
this.description,
this.image,
this.author,
});
Book.fromJson(Map<String, dynamic> parsedJson) {
id = parsedJson['id'];
title = parsedJson['title'];
description = parsedJson['description'];
image = parsedJson['image'];
author = parsedJson['author'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['title'] = this.title;
data['description'] = this.description;
data['image'] = this.image;
data['author'] = this.author;
return data;
}
}
This is the Controller Class that seems to contain the error. I am able to print the content coming from the backend though.
import 'dart:io';
import 'package:elibrary/model/books.dart';
import 'package:elibrary/services/repository/book_repository.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class BookController extends GetxController {
BookRepository bookRepository = BookRepository();
RxBool isLoading = false.obs;
RxList<Book> bookList = <Book>[].obs;
#override
void onInit() {
super.onInit();
fetchBooksList();
}
Future<void> fetchBooksList() async {
isLoading(true);
try {
Response bookResponse = await bookRepository.fetchBooks();
if (bookResponse.statusCode == 200) {
for (var element in bookResponse.body) {
bookList.add(Book.fromJson(element));
}
} else {
Get.snackbar(
'Error Occurred',
bookResponse.statusText.toString(),
snackPosition: SnackPosition.BOTTOM,
colorText: Colors.white,
backgroundColor: Colors.red,
);
}
} catch (e) {
debugPrint(
e.toString(),
);
Get.snackbar(
"Error Occurred",
e.toString(),
snackPosition: SnackPosition.BOTTOM,
colorText: Colors.white,
backgroundColor: Colors.green,
duration: Duration(seconds: 5),
).show();
} finally {
isLoading(false);
}
}
}
I did try changing the model object to this
import 'dart:convert';
Book bookFromJson(String str) => Book.fromJson(json.decode(str));
String bookToJson(Book data) => json.encode(data.toJson());
class Book {
Book({
this.id,
this.title,
this.description,
this.image,
this.author,
});
int id;
String title;
String description;
String image;
String author;
factory Book.fromJson(Map<String, dynamic> json) => Book(
id: json["id"],
title: json["title"],
description: json["description"],
image: json["image"],
author: json["author"],,
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"description": description,
"image": image,
"author": author,
};
}
And then I tried the controller this way also
import 'dart:io';
import 'package:elibrary/model/books.dart';
import 'package:elibrary/services/repository/book_repository.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class BookController extends GetxController {
BookRepository bookRepository = BookRepository();
RxBool isLoading = false.obs;
RxList<Book> bookList = <Book>[].obs;
#override
void onInit() {
super.onInit();
fetchBooksList();
}
Future<void> fetchBooksList() async {
isLoading(true);
try {
Response bookResponse = await bookRepository.fetchBooks();
if (bookResponse.statusCode == 200) {
bookList.assAll(
bookFromJson(bookResponse.bodyString ?? ''),
)
} else {
Get.snackbar(
'Error Occurred',
bookResponse.statusText.toString(),
snackPosition: SnackPosition.BOTTOM,
colorText: Colors.white,
backgroundColor: Colors.red,
);
}
} catch (e) {
debugPrint(
e.toString(),
);
Get.snackbar(
"Error Occurred",
e.toString(),
snackPosition: SnackPosition.BOTTOM,
colorText: Colors.white,
backgroundColor: Colors.green,
duration: Duration(seconds: 5),
).show();
} finally {
isLoading(false);
}
}
}
```
```
Again I tried decoding the response this way
```
```
var jsonList = jsonDecode(bookResponse.bodyString ?? '')
.map((book) => Book.fromJson(book))
.toList();
bookList.assignAll(jsonList);
debugPrint('Total Book List is: ${bookList.length}');
All these attempts produce the same error.
These is the API Response
I/flutter ( 5788): key = data, value = [{id: 1, name: dolore, icon: http://192.168.1.102:8000/images/categories/https://via.placeholder.com/640x480.png/007766?text=architecto}, {id: 2, name: repellat, icon: http://192.168.1.102:8000/images/categories/https://via.placeholder.com/640x480.png/004444?text=voluptatum}, {id: 3, name: est, icon: http://192.168.1.102:8000/images/categories/https://via.placeholder.com/640x480.png/005577?text=et}, {id: 4, name: quasi, icon: http://192.168.1.102:8000/images/categories/https://via.placeholder.com/640x480.png/00cc00?text=deserunt}, {id: 5, name: provident, icon: http://192.168.1.102:8000/images/categories/https://via.placeholder.com/640x480.png/008888?text=et}, {id: 6, name: quo, icon: http://192.168.1.102:8000/images/categories/https://via.placeholder.com/640x480.png/007777?text=dolorem}, {id: 7, name: expedita, icon: http://192.168.1.102:8000/images/categories/https://via.placeholder.com/640x480.png/00aa88?text=adipisci}, {id: 8, name: quia, icon: http://192.168.1.102:8000/images/categor
I/flutter ( 5788): result = {"data":[{"id":1,"name":"dolore","icon":"http:\/\/192.168.1.102:8000\/images\/categories\/https:\/\/via.placeholder.com\/640x480.png\/007766?text=architecto"},{"id":2,"name":"repellat","icon":"http:\/\/192.168.1.102:8000\/images\/categories\/https:\/\/via.placeholder.com\/640x480.png\/004444?text=voluptatum"},{"id":3,"name":"est","icon":"http:\/\/192.168.1.102:8000\/images\/categories\/https:\/\/via.placeholder.com\/640x480.png\/005577?text=et"},{"id":4,"name":"quasi","icon":"http:\/\/192.168.1.102:8000\/images\/categories\/https:\/\/via.placeholder.com\/640x480.png\/00cc00?text=deserunt"},{"id":5,"name":"provident","icon":"http:\/\/192.168.1.102:8000\/images\/categories\/https:\/\/via.placeholder.com\/640x480.png\/008888?text=et"},{"id":6,"name":"quo","icon":"http:\/\/192.168.1.102:8000\/images\/categories\/https:\/\/via.placeholder.com\/640x480.png\/007777?text=dolorem"},{"id":7,"name":"expedita","icon":"http:\/\/192.168.1.102:8000\/images\/categories\/https:\/\/via.placeholder.com\/640x480.png\/0
I/flutter ( 5788): Total Book List is: 0
I/flutter ( 5788): type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
Your response is map, you need use ["data"] on it to get your list you want. So in your Book class change this:
Book bookFromJson(String str) => Book.fromJson(json.decode(str));
to this:
List<Book> bookFromJson(String str) => (json.decode(str)["data"] as List).map((e) => Book.fromJson(e)).toList();
You are receiving a JSON list and you have to pass each item of it to Book.parseJson function.
List<Book> bookFromJson(String str) {
Iterable jsonArray = json.decode(str);
return List<Book>.from(jsonArray.map((json) => Book.fromJson(json)));
}
Html Codes
I have to get "<img src=" value. How can i do this?
I tried this :
responseBody = responseBody.substring(responseBody.indexOf('<img src=""'));
var lt = responseBody.substring(0, responseBody.indexOf('" />'));
and this :
for (var i = 0; i < count; i++) {
print(document.getElementsByClassName("firma-isim")[i].getElementsByTagName("img")[0].getElementsByTagName("src").first;
}
But didn't work. Is there an easy way to do this? How can I do this?
Thanks.
HTML :
<div class="populer-firmalar">
<span class="firma-sol" data-kaydir=".pop-firma,sol,1"><i class="fa fa-angle-left"></i></span>
<span class="firma-sag" data-kaydir=".pop-firma,sag,1"><i class="fa fa-angle-right"></i></span>
<div class="populer-firma-holder">
<ul class="pop-firma">
<li class="active">
<div class="firma-resim">
<img src="https://kimbufirma.com/firma/wp-content/uploads/2021/02/a3-dijital-web-tasarim-ve-yazilim-ajansi.cropped.270x200.jpg" alt="A3 DİJİTAL | WEB TASARIM VE YAZILIM AJANSI" width="270" height="200">
</div>
You can use html parser and html dom
var document = parse(body);
dom.Element link = document.querySelector('img');
String imageLink = link != null ? link.attributes['src'] : '';
Make sure to import these
import 'package:html/dom.dart' as dom;
import 'package:html/parser.dart' show parse;
I use Regular Expressions:
NetService:
import 'dart:convert';
import 'dart:io';
import 'package:meta/meta.dart';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
import 'package:path/path.dart' as p;
class NetService {
/* ---------------------------------------------------------------------------- */
static Future<T> getJson<T>(String url) {
return http.get(Uri.parse(url))
.then((response) {
if (response.statusCode == 200) {
return jsonDecode(response.body) as T;
}
print('Status Code : ${response.statusCode}...');
return null;
})
.catchError((err) => print(err));
}
/* ---------------------------------------------------------------------------- */
static Future<String> getRaw(String url) {
return http.get(Uri.parse(url))
.then((response) {
if (response.statusCode == 200) {
return response.body;
}
print('Status Code : ${response.statusCode}...');
return null;
})
.catchError((err) => print(err));
}
}
Main:
import 'dart:async';
import 'package:_samples2/networking.dart';
const kUrl = 'https://kimbufirma.com/firma/';
var regExp = RegExp(r'<a href="[\w\d\:\.\-\/]+"><img src="([\w\d\:\.\-\/]+)"');
class WebSite {
static Future<String> fetchWebPage () async {
print('Start fetching...');
return await NetService.getRaw(kUrl)
.whenComplete(() => print('Fetching done!\n'));
}
}
void main(List<String> args) async {
var data = await WebSite.fetchWebPage();
var images = regExp.allMatches(data).map((e) => e.group(1)).toList();
// print(images);
print(images.where((e) => e.contains('a3')));
print(images[1]);
}
Result:
Start fetching...
Fetching done!
(https://kimbufirma.com/firma/wp-content/uploads/2021/02/a3-dijital-web-tasarim-ve-yazilim-ajansi.cropped.270x200.jpg)
https://kimbufirma.com/firma/wp-content/uploads/2021/02/a3-dijital-web-tasarim-ve-yazilim-ajansi.cropped.270x200.jpg
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());
}
}
here is my service:
get(id: string): Observable<PaginaModel> {
return this.http.get<PaginaModel>('api/pagini/get/' + id);
}
the model:
import { LinieModel } from "./linie.model";
export class PaginaModel {
linii: LinieModel[] = [];
}
and here how i call it:
ngOnInit() {
this.canvas = document.getElementById('AfisareCanvas') as HTMLCanvasElement;
this.ctx = this.canvas.getContext('2d');
this.service.get('5b9bad0c457b4e1c70af18f8').subscribe(data => {
console.log(data); //here data is string (like using stringify)
console.log(data.linii.length); //undefined error
});
}
i tried using JSON.parse but didnt work.