Is it possible to use multiple compute at the same time?
I'd like to call a heavy function on a list, which I want to run in parallel, but it crashes the app without any error message.
Am I supposed to do only one compute call at a time?
Here's my test code that crashes often (but not always).
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(home: MyHomePage());
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<List<int>> f;
#override
void initState() {
super.initState();
f = getFutures();
}
Future<List<int>> getFutures() async {
List<int> output = [];
List<Future<int>> futures = [];
for (int i = 0; i < 100; ++i) {
print("call getFuture");
futures.add(getFuture());
}
for (int i = 0; i < futures.length; ++i) {
var f = await futures[i];
output.add(f);
}
return output;
}
Future<int> getFuture() async {
print("call compute");
var i = await compute(count, 1000000000);
return i;
}
static int count(int max) {
print("start count");
int j;
for (int i = 0; i < max; ++i) {
j = i;
}
return j;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("test")),
body: FutureBuilder<List<int>>(
future: f,
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.done:
print(snapshot);
return ListView.builder(
itemCount: 100,
itemBuilder: (context, index) {
return Text("snapshot: ${snapshot.data[index]}");
});
break;
default:
return Center(child: CircularProgressIndicator());
}
}),
);
}
}
Related
I've made an inventory object for my game. Here is its code:
class player extends Phaser.GameObjects{
constructor(){
super();
this.stuff = [null,null,null,null,null,null,null,null,null,null];
}
collcet(item) {
this.space = 0;
while (this.space < 10){
if (this.items[this.space] == null){
this.items[this.space] == item;
break;
}
else {
this.space += 1;
}
}
}
has(item){
this.space = 0;
this.result = false
while (this.space < 10){
if (this.items[this.space] == item){
this.result = true;
break;
}
else {
this.space += 1;
}
}
return this.result;
}
takeOut(item){
this.space = 0;
while (this.space < 10){
if (this.items[this.space] == item){
this.items[this.space] == null;
break;
}
else {
this.space += 1;
}
}
}
}
I want to have a single inventory that is accessible in all scenes of my game, but I'm using switch statements to change scenes, which I faintly remember don't allow for data to be shared between scenes. Is there any way I can have this inventory work, or do I need to rethink the whole thing?
If it helps, I'm using Phaser 3 in VSCode, employing arcade physics.
Start or add your scenes first, then switch between them. When you start them, pass your game state:
export default class BootScene extends Phaser.Scene {
constructor() {
super({ key: "BootScene" });
}
preload() {
this.gameState = {
inventory: [ some stuff ],
}
}
create() {
const startScene = false;
this.scene.add("InventoryScene", InventoryScene, startScene, this.gameState);
this.scene.start("GameScene", this.gameState);
}
}
Now switch between your scenes:
export default class GameScene extends Phaser.Scene {
constructor() {
super({ key: "GameScene" });
}
init(gameState) {
this.gameState = gameState;
}
update() {
if player presses "i" {
this.scene.switch("InventoryScene");
}
}
The state you passed is available within the scene.
export default class InventoryScene extends Phaser.Scene {
constructor() {
super({ key: "InventoryScene" });
}
init(gameState) {
this.gameState = gameState;
}
update() {
const { some stuff } = this.gameState.inventory;
if player presses "esc" {
this.scene.switch("GameScene");
}
}
I want to Update the new value of the 'holecode' variable in 'inputform.dart' then get this new value to the 'otpscreen.dart'
The Problem that in each time I try to get the value of the 'holecode' string variable I get the 'default' value which I initialize it.I tried to make the 'holecode' variable as late String holecode; but it return Null in the second Screen in each time I try to get it's value.
inputform.dart:
import 'package:flutter/material.dart';
class Inputform extends StatefulWidget {
List<String> code = ["","","","","",""];
String holeCode = "default";
#override
State<Inputform> createState() => InputformState();
}
class InputformState extends State<Inputform> {
#override
Widget build(BuildContext context) {
return TextFormField(
onChanged: (value) {
setState(() {
widget.code[0] = value;
widget.holeCode = widget.code[0] + 222205;
});
if (value.length == 1) {
FocusScope.of(context).nextFocus();
}
}
),
},
otp.dart:
import 'package:flutter/material.dart';
class OtpVerification extends StatefulWidget {
#override
State<StatefulWidget> createState() => Otp();
}
class Otp extends State<OtpVerification> {
final Inputform ani= new Inputform ();
#override
Widget build(BuildContext context) {
return Scaffold(
child:
FlatButton(
onPressed: () {
// trying to print the new value in this screen but it
//return the default value 'default'
print(ani.holeCode);
),
);
}
Try this:
Have your InputForm like so:
class Inputform extends StatefulWidget {
final ValueChanged<String> onHoleCodeChanged;
const Inputform({
Key? key,
required this.onHoleCodeChanged,
}) : super(key: key);
#override
State<Inputform> createState() => InputformState();
}
class InputformState extends State<Inputform> {
List<String> code = ["", "", "", "", "", ""];
String holeCode = "default";
#override
Widget build(BuildContext context) {
return TextFormField(onChanged: (value) {
setState(() {
code[0] = value;
holeCode = code[0] + "222205";
widget.onHoleCodeChanged(holeCode);
});
if (value.length == 1) {
FocusScope.of(context).nextFocus();
}
});
}
}
And have your OTP class like so:
class OtpVerification extends StatefulWidget {
#override
State<StatefulWidget> createState() => Otp();
}
class Otp extends State<OtpVerification> {
late Inputform ani;
#override
void initState() {
ani = Inputform(
onHoleCodeChanged: (v) {
setState(() {
aniHoleCode = v;
});
},
);
super.initState();
}
String aniHoleCode = "";
#override
Widget build(BuildContext context) {
return Scaffold(
body: FlatButton(
child: Text("Button"),
onPressed: () {print(aniHoleCode);},
),
);
}
}
I expected that validate() function of child class returns the type of checks() child class function. But as you see it returns the type of parent class function.
Playground
Could you explain why and how to fix it?
class Test {
process() {
const attrs = this.validate(); // (method) Test.validate(): void
return attrs;
}
validate() {
const attrs = this.checks();
return attrs;
}
protected checks() {}
}
class SubTest extends Test {
process() {
const attrs = this.validate(); // (method) Test.validate(): void
return attrs;
}
protected checks() {
return 'hello';
}
}
class Test {
process() {
const attrs = this.validate(); // (method) Test.validate(): void
return attrs;
}
validate<T>(): T {
const attrs = this.checks();
return attrs;
}
protected checks(): any {}
}
class SubTest extends Test {
process() {
const attrs = this.validate<ReturnType<SubTest['checks']>>(); // (method) Test.validate(): Number
return attrs;
}
protected checks(): Number {
return 1;
}
}
class Sub2Test extends Test {
process() {
const attrs = this.validate<ReturnType<Sub2Test['checks']>>(); // (method) Test.validate(): String
return attrs;
}
protected checks(): String {
return 'ssssss';
}
}
const instance = new SubTest();
const response = instance.process();
console.log(response);
I am still new to flutter and am learning building apps. I have been trying to run this code for but every time I run it I get a red screen on the android emulator and an error which goes "Failed Assertion: Line 22 pos 14 'url != null': is not true".
This is my main file which runs the app
import "package:flutter/material.dart";
import "src/app.dart";
voidmain() {
runApp(MyApp());
}
My App file has this code
import 'package:flutter/material.dart';
import 'package:http/http.dart' show get;
import 'models/image_models.dart';
import 'dart:convert';
import 'widgets/image_list.dart';
class MyApp extends StatefulWidget {
createState() {
return AppState();
}
}
class AppState extends State<MyApp> {
int counter = 0;
List<ImageModels> images = [];
void fetchImage() async {
counter++;
var response =
await get('http://jsonplaceholder.typicode.com/photos/$counter');
var imagemodel = ImageModels.fromjson(json.decode(response.body));
setState(() {
images.add(imagemodel);
});
}
Widget build(context) {
return MaterialApp(
home: Scaffold(
body: ImageList(images),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
fetchImage();
}),
appBar: AppBar(title: Text("Ola Amigo!")),
));
}
}
Heres the ImageModel Class
class ImageModels {
int id;
String url;
String title;
ImageModels(this.id, this.url, this.title);
ImageModels.fromjson(Map<String, dynamic> parsedjson) {
id = parsedjson[id];
title = parsedjson[title];
url = parsedjson[url];
}
}
and lastly the ImageList
import 'package:flutter/material.dart';
import '../models/image_models.dart';
class ImageList extends StatelessWidget {
final List<ImageModels> image;
ImageList(this.image);
Widget build(context) {
return ListView.builder(
itemCount: image.length,
itemBuilder: (context, int index) {
return buildImage(image[index]);
});
}
Widget buildImage(ImageModels image) {
return Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey)
),
padding: EdgeInsets.all(20.0),
margin: EdgeInsets.all(20.0),
child: Image.network(image.url),
);
}
}
Can someone please take a look at it and tell me what am I doing wrong and how can I resolve this issue.
Thank you
You can copy paste run full code below
You have error in ImageModels, please revise to
code snippet
factory ImageModels.fromjson(Map<String, dynamic> parsedjson) => ImageModels(
parsedjson["id"],
parsedjson["url"],
parsedjson["title"],
);
working demo
full code
import 'dart:convert';
import 'package:http/http.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
createState() {
return AppState();
}
}
class AppState extends State<MyApp> {
int counter = 0;
List<ImageModels> images = [];
void fetchImage() async {
counter++;
var response =
await get('https://jsonplaceholder.typicode.com/photos/$counter');
print(response.body);
var imagemodel = ImageModels.fromjson(json.decode(response.body));
print(imagemodel.url);
setState(() {
images.add(imagemodel);
print(images[0].url);
});
}
Widget build(context) {
return MaterialApp(
home: Scaffold(
body: ImageList(images),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
fetchImage();
}),
appBar: AppBar(title: Text("Ola Amigo!")),
));
}
}
class ImageModels {
int id;
String url;
String title;
ImageModels(this.id, this.url, this.title);
factory ImageModels.fromjson(Map<String, dynamic> parsedjson) => ImageModels(
parsedjson["id"],
parsedjson["url"],
parsedjson["title"],
);
}
class ImageList extends StatelessWidget {
final List<ImageModels> image;
ImageList(this.image);
Widget build(context) {
return ListView.builder(
itemCount: image.length,
itemBuilder: (context, int index) {
print(image[index].url);
return buildImage(image[index]);
});
}
Widget buildImage(ImageModels image) {
return Container(
decoration: BoxDecoration(border: Border.all(color: Colors.grey)),
padding: EdgeInsets.all(20.0),
margin: EdgeInsets.all(20.0),
child: Image.network(image.url),
);
}
}
I'm facing issue to fetch json data from Flutter mobile app.
Code as follow:
import 'package:flutter/material.dart';
import 'package:flutter_app/pages/main_page.dart';
class App extends StatelessWidget
{
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: "Flutter NodeJS",
home: MainPage(),
);
}
}
void main(){
runApp(App());
}
main_page.dart
import 'package:flutter/material.dart';
import 'package:flutter_app/modules/http.dart';
import 'package:flutter_app/pages/add_user_page.dart';
class MainPage extends StatefulWidget
{
#override
State<StatefulWidget> createState() {
return MainPageState();
}
}
class User
{
String id;
String first_name,email;
User(this.id, this.first_name,this.email);
}
class MainPageState extends State<MainPage>
{
List<User> users = [];
Future<void> refreshUsers()async{
var result = await http_get('users');
if(result.ok)
{
setState(() {
users.clear();
var in_users = result.data as List<dynamic>;
in_users.forEach((in_user){
users.add(User(
in_user['id'].toString(),
in_user['first_name'],
in_user['email']
));
});
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Users"),
//email: Text("Email"),
actions: <Widget>[
IconButton(
icon: Icon(Icons.add),
onPressed: (){
Navigator.of(context).push(MaterialPageRoute(
builder: (context){
return AddUserPage();
}
));
},
)
],
),
body: RefreshIndicator(
onRefresh: refreshUsers,
child: ListView.separated(
itemCount: users.length,
itemBuilder: (context, i) => ListTile(
leading: Icon(Icons.person),
title: Text(users[i].first_name+"\n" + users[i].email),
//email: Text(users[i].email),
),
separatorBuilder: (context, i) => Divider(),
),
),
);
}
}
http.dart
import 'dart:convert';
import "package:http/http.dart" as http;
class RequestResult
{
bool ok;
dynamic data;
RequestResult(this.ok, this.data);
}
//'https://jsonplaceholder.typicode.com/users/1
//http://192.168.183.179:8081/api/users/
const PROTOCOL = "http";
const DOMAIN = "https://jsonplaceholder.typicode.com/users/1";
Future<RequestResult> http_get(String route, [dynamic data]) async
{
var dataStr = jsonEncode(data);
var url = "$PROTOCOL://$DOMAIN/$route?data=$dataStr";
var result = await http.get(url);
return RequestResult(true, jsonDecode(result.body));
}
Future<RequestResult> http_post(String route, [dynamic data]) async
{
var url = "$PROTOCOL://$DOMAIN/$route";
var dataStr = jsonEncode(data);
var result = await http.post(url, body: dataStr, headers:{"Content-Type":"application/json"});
return RequestResult(true, jsonDecode(result.body));
}
When I'm fetch json data from "https://jsonplaceholder.typicode.com/users/1". Its working fine.
enter image description here
When I try to fetch json data from "https://192.168.183.179:8081/api/users". Its give error:
at Object.createErrorWithStack (http://localhost:15340/dart_sdk.js:4348:12)
at Object._rethrow (http://localhost:15340/dart_sdk.js:37892:16)
at async._AsyncCallbackEntry.new.callback (http://localhost:15340/dart_sdk.js:37886:13)
at Object._microtaskLoop (http://localhost:15340/dart_sdk.js:37718:13)
at _startMicrotaskLoop (http://localhost:15340/dart_sdk.js:37724:13)
at http://localhost:15340/dart_sdk.js:33243:9
What I'm doing wrong
Regards,
SAO
Check in Postman whether the ip address is returning data.
Another case would be the data obtained, could not be transffered correctly to the app. Check the variables and types where the data is stored.