I'm trying to calculate supertrend based on this moving average code.
But not be able to get exact value like superTrend. Here is the basic code which I was using. The first one is EMA, it's is working perfectly but not be able to calculate superTrend like this.
import 'dart:ui';
import '../../models/candle.dart';
import '../../models/indicator.dart';
import 'dart:math';
class EMA extends Indicator {
EMA({
required int period,
required Color color,
}) : super(
name: "EMA $period",
dependsOnNPrevCandles: period,
calculator: (int index, List<Candle> candles) {
double multiplier = (2 / (period + 1));
double sum = 0;
for (int i = 0; i < period; i++) {
sum += candles[i + index].close;
}
double ema = sum / period; //(summ.close / period);
ema = multiplier * (candles[index].close - ema) + ema;
return [ema];
},
indicatorComponentsStyles: [
IndicatorStyle(
name: "EMA $period", color: color),
],
);
}
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../../models/candle.dart';
import '../../models/indicator.dart';
class SupertrendIndicator extends Indicator {
SupertrendIndicator(
{required int length, required double multiplier, required Color color})
: super(
name: "Supertrend $length/$multiplier",
dependsOnNPrevCandles: length + 1,
calculator: (index, candles) {
final candle = candles[index];
// Calculate basic upper and lower bands
final basicUpper = (candle.high + candle.low) / 2 +
multiplier * _atr(candles, index, length);
final basicLower = (candle.high + candle.low) / 2 -
multiplier * _atr(candles, index, length);
// Calculate final upper and lower bands
final finalUpper = basicUpper;
final finalLower = basicLower;
// Calculate Supertrend value
final supertrend = candle.close > basicUpper
? finalUpper
: candle.close < basicLower
? finalLower
: previousSupertrend > previousBasicUpper
? basicLower
: basicUpper;
return [
supertrend,
];
},
indicatorComponentsStyles: [
IndicatorStyle(name: "Supertrend", color: color),
]);
static double _atr(List<Candle> candles, int index, int length) {
double sum = 0;
for (int i = 0; i < length; i++) {
final trueRange1 = math.max(
candles[i].high - candles[i].low,
(i > 0 ? candles[i].high - candles[i - 1].close : 0),
);
final trueRange2 = math.max(
trueRange1,
(i > 0 ? candles[i - 1].close - candles[i].low : 0),
);
sum += trueRange2;
}
return sum / length;
}
}
Related
I have 2 list
List a = [0,2,0];
List b = [0,3,0];
Now I want to create a function to calculate this list and return a list of percentages.
Return [0,67,0]
void main() {
getPercentage();
}
int? getPercentage(){
List<int> a = [0,2,0];
List<int> b = [0,3,0];
for (int i = 0; i < a.length; i++) {
int percentage = ((a[i]/b[i]*100).toInt());
return percentage;
}
}
I tried this.
The issue occurs when the number is divided by 0
You can replace 0 with 1.
List<int>? getPercentage() {
List<int> a = [0, 2, 0];
List<int> b = [0, 3, 0];
List<int> percentage = [];
for (int i = 0; i < a.length; i++) {
int x = a[i] <= 0 ? 1 : a[i];
int y = b[i] <= 0 ? 1 : b[i];
final p = (x / y * 100).toInt();
percentage.add(p);
}
return percentage;
}
void main() {
print(getPercentage()); //[100, 66, 100]
}
The following should work:
void main() {
getPercentage();
}
List<int> getPercentage(){
List<int> a = [0,2,0];
List<int> b = [0,3,0];
List<int> result = [];
for (int i = 0; i < a.length; i++) {
int percentage = b == 0 ? 0 : (a[i] / b[i] * 100).toInt();
result.add(percentage);
}
return result;
}
Alternatively use this function for any A/B int list with nan check:
List<int> getPercentage(List<int> ListA, List<int> ListB) {
int maxLength = min(ListA.length, ListB.length); // check if has same # items
List<int> result = [];
for (int i = 0; i < maxLength; i++) {
var calc = (ListA[i] / ListB[i]) * 100; // calc % A/B of item i
calc = (calc).isNaN ? 0 : calc; //check if is nan (divided by zero) return 0
result.add((calc).toInt()); //add to result list
}
return result;
}
So i have small double values and i need to convert them into string in order to display in my app. But i care only about first two significant digits.
It should work like this:
convert(0.000000000003214324) = '0.0000000000032';
convert(0.000003415303) = '0.0000034';
We can convert double to string, then check every index and take up to two nonzero (also .) strings. But the issue comes on scientific notation for long double.
You can check Convert long double to string without scientific notation (Dart)
We need to find exact String value in this case. I'm taking help from this answer.
String convert(String number) {
String result = '';
int maxNonZeroDigit = 2;
for (int i = 0; maxNonZeroDigit > 0 && i < number.length; i++) {
result += (number[i]);
if (number[i] != '0' && number[i] != '.') {
maxNonZeroDigit -= 1;
}
}
return result;
}
String toExact(double value) {
var sign = "";
if (value < 0) {
value = -value;
sign = "-";
}
var string = value.toString();
var e = string.lastIndexOf('e');
if (e < 0) return "$sign$string";
assert(string.indexOf('.') == 1);
var offset =
int.parse(string.substring(e + (string.startsWith('-', e + 1) ? 1 : 2)));
var digits = string.substring(0, 1) + string.substring(2, e);
if (offset < 0) {
return "${sign}0.${"0" * ~offset}$digits";
}
if (offset > 0) {
if (offset >= digits.length) return sign + digits.padRight(offset + 1, "0");
return "$sign${digits.substring(0, offset + 1)}"
".${digits.substring(offset + 1)}";
}
return digits;
}
void main() {
final num1 = 0.000000000003214324;
final num2 = 0.000003415303;
final v1 = convert(toExact(num1));
final v2 = convert(toExact(num2));
print("num 1 $v1 num2 $v2");
}
Run on dartPad
I'm trying to add all elements in a list of lists by index and average them:
List<List<double>> data = [[1.0, 2.0, 3.0], [2.0, 3.0, 5.0], [8.0, 7.0, 2.0]]
The result should be a list of doubles each summed up and then divided by the total lengths of above data:
[11.0, 12.0, 10.0] // divide these by 3
[3.67, 4.0, 3.33] // should be the result
What is the best way to do this? This is taking too long in my flutter app (actual data list contains 60 lists of 2000 doubles each) and yes, I am also asserting the length of each list is equal. and is not empty or having unexpected data types.
Well I really don't know about the speed you need.
Try this method to see if it works for your dataset. Maybe your method is faster!
void main() {
List<List<double>> data = [[1.0, 2.0, 3.0], [2.0, 3.0, 5.0], [8.0, 7.0, 2.0]];
List<double> dataSum = List<double>();
// original data
print(data);
for (var item in data){
dataSum.add(item.fold(0, (p, c) => p + c) / item.length);
}
// output
print(dataSum);
}
Important:
Anyways, if you do a large task in time, you can use a async function with a Future to prevent the application to hang and not suffer because of the long wait.
UPDATE: After OP's comment
This code should give you the result you are expecting.
void main() {
List<List<double>> data = [[1.0, 2.0, 3.0], [2.0, 3.0, 5.0], [8.0, 7.0, 2.0]];
int numLists = data.length;
int numElements = data[0].length;
double sum;
List<double> dataSum = List<double>();
for(var i = 0; i < numElements; i++ ) {
sum = 0.0;
for(var j = 0; j < numLists; j++ ) {
sum += data[j][i]; //inverted indexes
}
dataSum.add(sum/numLists);
}
// output
print(dataSum);
}
My contribution for a Matrix NxM, I've modified your data for a more generic solution:
extension chesu<T> on List<List<T>> {
List<List<T>> transpose() {
final rowNum = this.length;
final colNum = this[0].length;
var list = List<List<T>>.generate(colNum, (i) => List<T>());
if (rowNum == 0 || colNum == 0) return null;
for (var r = 0; r < rowNum; r++)
for (var c = 0; c < colNum; c++) list[c].add(this[r][c]);
return list;
}
}
main(List<String> args) {
final data = [[1.0, 2.0, 3.0, 4.0], [2.0, 3.0, 5.0, 8.0], [6.0, 7.0, 7.0, 9.0]];
print(data.transpose().map((e) => e.reduce((v, e) => v+e)).map((e) => e/3));
}
Result:
(3.0, 4.0, 5.0, 7.0)
There is a new package named scidart that contains interesting functions like transpose, it tries to emulate numpy from Python.
UPDATE 1: Working with Big Data
UPDATE 2: I made a fool mistake with sum(), extension is fixed now, sorry.
import 'dart:math';
extension on List<List<double>> {
List<List<double>> transpose() {
final rowNum = this.length;
final colNum = this[0].length;
var list = List<List<double>>.generate(colNum, (i) => List<double>());
if (rowNum == 0 || colNum == 0) return null;
for (var r = 0; r < rowNum; r++)
for (var c = 0; c < colNum; c++) list[c].add(this[r][c]);
return list;
}
List<double> sum() => this.map((l) => l.reduce((v, e) => v+e)).toList();
}
class Stats {
List<List<double>> _data;
int _rows, _cols;
List<double> _sum, _avg;
Stats(List<List<double>> data) {
_data = data.transpose();
_rows = _data.length;
_cols = _data[0].length;
}
int get rows => _rows;
int get cols => _cols;
List<double> get sum {
if ([0, null].contains(_sum)) _sum = _data.sum();
return _sum;
}
List<double> get avg {
if ([0, null].contains(_avg)) _avg = sum.map((e) => e / _cols).toList();
return _avg;
}
}
main(List<String> args) {
// final data = [[1.0, 2.0, 3.0, 4.0], [2.0, 3.0, 5.0, 8.0], [6.0, 7.0, 7.0, 9.0]];
// final data = [[1.0, 2.0, 3.0], [2.0, 3.0, 5.0], [8.0, 7.0, 2.0]];
final data = List<List<double>>.generate(60, (i) => List<double>.generate(2000, (j) => Random().nextDouble()*30));
print('Creating big data...');
final stats = Stats(data);
final stopwatch = Stopwatch()..start();
print('Calculating statistics...');
print('Sum: ${stats.sum.take(5)}');
print('Average: ${stats.avg.take(5)}');
stopwatch.stop();
print('\nJob finished at ${stopwatch.elapsedMilliseconds/1000} seconds.');
}
Result:
Creating big data...
Calculating statistics...
Sum: (928.8075263386316, 934.3418807027017, 815.2172548417801, 833.6855783984151, 828.1013228547513)
Average: (15.480125438977193, 15.572364678378362, 13.586954247363002, 13.894759639973586, 13.801688714245854)
Job finished at 0.024 seconds.
For operations on list you have to iterate over it's items (for, map, forEach ...etc) which would take time (depending on the list length) so I guess you have to do some benchmarking.
Try this
List<double> sum = [];
List<double> average = [];
sum = data.reduce((a, b) {
List<double> list = [];
for (int i = 0; i < b.length; i++) {
list.add(a[i] + b[i]);
}
return list;
});
average = sum.map((e) => e / 3).toList();
print(sum);
print(average);
Let me suggest more compact solution:
List<List<double>> data = [[1.0, 2.0, 3.0], [2.0, 3.0, 5.0], [8.0, 7.0, 2.0]]
var result = <double>[];
final innerListSize = data[0].length;
for (int i = 0; i < innerListSize; i++) {
result.add(data.map((e) => e[i]).average);
}
I want to use this game https://github.com/yum650350/tissuebox in my Flutter project. I tried calling different parts of the main page but it wasn't coming up properly even though the game itself is working.
I want to integrate it in my iOS app and want to call it with a
function which opens a separate page where the user can play the game.
Is there a way I can do it?
So this is what I tried:
I called the method of the game in a separate screen
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(new MaterialApp(
debugShowCheckedModeBanner: false,
home: FirstScreen(),
));
}
class FirstScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First Screen'),
),
body: Center(
child: RaisedButton(
color: Colors.red,
child: Text('Go to Second Screen'),
onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute<Null>(builder: (BuildContext context) {
**???**
}));
},
),
),
);
}
}
But I don't know what to call in ?? this part since the game isn't wrapped in any class. This is the code of the game I want to call.
import 'package:shared_preferences/shared_preferences.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/gestures.dart';
import 'package:flame/sprite.dart';
import 'package:flame/flame.dart';
import 'package:flame/util.dart';
import 'package:flame/game.dart';
import 'dart:math';
tissuemain() async {
var util = Util();
await util.fullScreen();
await util.setOrientation(DeviceOrientation.portraitUp);
//loadimages
//tissuebox : 0,1,2,3,4,5,6
//background : b
//crown : c
//tissue : t
await Flame.images.loadAll(['b', '0', '1', '2', '3', '4', '5', '6', 't', 'c']);
audioLoad(c) async => (await Flame.audio.load(c)).path;
setAudio(a, s, v) async {
await a.setUrl(await audioLoad(s), isLocal: true);
a.setVolume(v);
}
//audios
//single drag : s.mp3
//double drag : s.mp3
//triple drag : s.mp3
//tick tock : tk.mp3
//game over : a.mp3
GameTable.setAudioList(GameTable.audioList1, await audioLoad('s.mp3'));
GameTable.setAudioList(GameTable.audioList2, await audioLoad('d.mp3'));
GameTable.setAudioList(GameTable.audioList3, await audioLoad('t.mp3'));
await setAudio(GameTable.tickTock, 'tk.mp3', 1.0);
await setAudio(GameTable.gameOver, 'a.mp3', .5);
var game = GameTable((await SharedPreferences.getInstance()).getInt('hs') ?? 0);
var hDrag = HorizontalDragGestureRecognizer();
var vDrag = VerticalDragGestureRecognizer();
hDrag.onUpdate = game.onDragUpdate;
hDrag.onStart = game.onDragStart;
hDrag.onEnd = game.onDragEnd;
vDrag.onUpdate = game.onDragUpdate;
vDrag.onStart = game.onDragStart;
vDrag.onEnd = game.onDragEnd;
runApp(game.widget);
util.addGestureRecognizer(hDrag);
util.addGestureRecognizer(vDrag);
}
enum Drag { tissue, box, none }
class GameTable extends Game {
//Audio
//These are workarounds for the ios memory leak
static var
tickTock = AudioPlayer(),
gameOver = AudioPlayer(),
audioList1 = [AudioPlayer(), AudioPlayer(), AudioPlayer()],
audioList2 = [AudioPlayer(), AudioPlayer()],
audioList3 = [AudioPlayer(), AudioPlayer()],
audioIndex1 = 0,
audioIndex2 = 0,
audioIndex3 = 0;
static getPlayIndex(int audioPlayer) {
if (audioPlayer == 1)
audioIndex1 = audioIndex1 < audioList1.length - 1 ? audioIndex1 + 1 : 0;
else if (audioPlayer == 2)
audioIndex2 = audioIndex2 < audioList2.length - 1 ? audioIndex2 + 1 : 0;
else if (audioPlayer == 3) audioIndex3 = audioIndex3 < audioList3.length - 1 ? audioIndex3 + 1 : 0;
return audioPlayer == 1 ? audioIndex1 : audioPlayer == 2 ? audioIndex2 : audioIndex3;
}
static get tissue1 => audioList1[getPlayIndex(1)];
static get tissue2 => audioList2[getPlayIndex(2)];
static get tissue3 => audioList3[getPlayIndex(3)];
static setAudioList(List<AudioPlayer> al,String audioName) => al.forEach((x) {
x.setUrl(audioName, isLocal: true);
x.setVolume(.2);
});
//
var background = Sprite('b'),
crown = Sprite('c'),
initialPoint = Offset.zero,
destPoint = Offset.zero,
dragState = Drag.none,
gameing = false,
gameover = false,
timePass = .0,
heighScore = 0,
score = 0,
timePassTemp = 0;
double tileSize, point1;
double get k => screenSize.width / 5 / tileSize;
Size screenSize;
Rect rect;
TissueBox tissueBox;
saveHighScore() async => await (await SharedPreferences.getInstance()).setInt('hs', heighScore);
GameTable(this.heighScore) {
init();
}
init() async {
resize(await Flame.util.initialDimensions());
rect = Rect.fromLTWH(.0, screenSize.height - tileSize * 23, tileSize * 9, tileSize * 23);
tissueBox = TissueBox(this);
}
#override
render(Canvas c) {
paintText(txt, offset, center, fontSize) {
var painter = TextPainter(
text: TextSpan(
style: TextStyle(
color: Colors.white,
fontSize: fontSize,
fontFamily: 'NS'),
text: txt),
textScaleFactor: k,
textDirection: TextDirection.ltr);
painter.layout();
painter.paint(c, center ? Offset(offset.dx - painter.width / 2, offset.dy) : offset);
}
background.renderRect(c, rect);
tissueBox.render(c);
var horCenter = tissueBox.initialLeft + tissueBox.boxRect.width / 2;
if (gameing)
paintText(timePass.toStringAsFixed(timePass < 1 ? 1 : 0) + 's', Offset(horCenter + 8, k * 23), true, k * 10);
var heighScoreTxt = heighScore.toString();
paintText(heighScoreTxt, Offset(heighScoreTxt.length==1?44.0:heighScoreTxt.length>2?22.0:33.0, k * 30), false, k * 12);
crown.renderRect(c, Rect.fromLTWH(28.0, k * 10, 49.2, 39.0));
paintText(score.toString(), Offset(horCenter, k * 50), true, k * 25);
heighScore = score > heighScore ? score : heighScore;
}
#override
update(double t) {
tissueBox.update(t);
timePass -= gameing || gameover ? t : 0;
if (timePass < 0 && gameing) {
tissueBox.isAway = true;
gameing = false;
timePass = 2;
gameover = true;
saveHighScore();
tissueBox.newGame();
} else if (gameing && !gameover) {
var floor = timePass.floor();
if (floor < timePassTemp && floor < 6 && floor != 0)
TissueBox.delay(Duration(milliseconds: 300), () => GameTable.tickTock.resume());
timePassTemp = floor;
}
gameover = timePass <= 0 && gameover ? false : gameover;
}
resize(s) {
screenSize = s;
tileSize = screenSize.width / 9;
}
onDragStart(DragStartDetails detail) {
var point = detail.globalPosition;
dragState = tissueBox.tissue.rect.contains(point) ? Drag.tissue : tissueBox.boxRect.contains(point) ? Drag.box : Drag.none;
initialPoint = Offset(point.dx == 0 ? initialPoint.dx : point.dx, point.dy == 0 ? initialPoint.dy : point.dy);
point1 = (tissueBox.tissue.rect.left - point.dx).abs();
}
onDragUpdate(DragUpdateDetails detail) {
if (gameover || dragState == Drag.none) return;
var point = detail.globalPosition;
destPoint = Offset(point.dx == 0 ? destPoint.dx : point.dx, point.dy == 0 ? destPoint.dy : point.dy);
if (dragState == Drag.tissue) {
if (initialPoint.dy - destPoint.dy > 100) {
if (gameing != true && gameover != true) {
gameing = true;
timePass = 10;
score = 0;
}
var sub = (point1 - (tissueBox.tissue.rect.left - point.dx).abs()).abs();
var addPoint = sub < 3 ? 3 : sub < 6 ? 2 : 1;
dragState = Drag.none;
tissueBox.nextTissue(addPoint);
playTissueAudio(addPoint);
score += addPoint;
}
} else if (dragState == Drag.box) {
tissueBox.boxRect = Rect.fromLTWH(tissueBox.initialLeft + destPoint.dx - initialPoint.dx, tissueBox.boxRect.top, TissueBox.boxSize.dx, TissueBox.boxSize.dy);
tissueBox.ismoving = true;
}
}
playTissueAudio(i) => (i == 1 ? GameTable.tissue1 : i == 2 ? GameTable.tissue2 : GameTable.tissue3).resume();
onDragEnd(DragEndDetails detail) {
initialPoint = Offset.zero;
dragState = Drag.none;
tissueBox.tissue.isMoving = false;
tissueBox.ismoving = false;
destPoint = initialPoint;
}
}
class TissueBox {
Rect get initialRect => Rect.fromLTWH(boxRect.center.dx - Tissue.width / 2, boxRect.top - boxRect.height + 20.3, Tissue.width, Tissue.width);
Sprite get getBoxSprite =>Sprite( rnd.nextInt(7).toString());
var tissueAwayList = List<TissueAway>(), rnd = Random(), ismoving = false, isAway = false;
Offset get getTissueUpPosition => Offset(initialRect.left, initialRect.top - 150);
final GameTable game;
Sprite boxSprite;
Rect boxRect;
int tissueCount;
Tissue tissue;
double get initialLeft => game.screenSize.width / 2 - TissueBox.boxSize.dx / 2;
double get initialTop => game.screenSize.height - game.tileSize * 5.5;
static var boxSize = Offset(150.0, 100.0);
TissueBox(this.game) {
boxRect = Rect.fromLTWH(initialLeft, initialTop, boxSize.dx, boxSize.dy);
tissueCount = 10 - rnd.nextInt(5);
tissue = Tissue(game, this);
boxSprite = getBoxSprite;
}
render(Canvas c) {
boxSprite.renderRect(c, boxRect);
tissue.render(c);
tissueAwayList.forEach((x) => x.render(c));
}
update(double t) {
tissue.update(t);
tissueAwayList.removeWhere((x) => x.isAway);
tissueAwayList.forEach((x) => x.update(t));
var distense = boxRect.left - initialLeft;
if (ismoving && !game.gameover) {
if (distense.abs() > 50 && tissueCount == 0){
isAway = true;
}
} else if (isAway && !game.gameover) {
boxRect = boxRect.shift(Offset(distense > 0 ? boxRect.left + game.k * 11 : boxRect.left - game.k * 11, boxRect.top));
if (boxRect.right < -50 || boxRect.left > game.screenSize.width + 50) {
newBox();
}
} else if (isAway && game.gameover) {
var target = Offset(boxRect.left, game.screenSize.height + Tissue.width) - Offset(boxRect.left, boxRect.top);
boxRect = boxRect.shift(
game.k * 11 < target.distance ?
Offset.fromDirection(target.direction, game.k * 11)
: target);
} else {
var target = Offset(initialLeft, initialTop) - Offset(boxRect.left, boxRect.top);
boxRect = boxRect.shift(
game.k * 11 < target.distance ?
Offset.fromDirection(target.direction, game.k * 11)
: target);
}
}
nextTissue(int pointsAdd) {
var duration = Duration(milliseconds: 100);
tissueAwayList.add(TissueAway(game, this));
if (pointsAdd > 1)
delay(duration, () {
tissueAwayList.add(TissueAway(game, this));
if (pointsAdd > 2)
delay(duration, () {
tissueAwayList.add(TissueAway(game, this));
});
});
tissue = Tissue(game, this, --tissueCount == 0);
}
newBox() {
boxSprite = getBoxSprite;
boxRect = Rect.fromLTWH(boxRect.right < -0 ? game.screenSize.width + 50 - boxSize.dx : -50.0, initialTop, boxSize.dx, boxSize.dy);
tissueCount = 10 - rnd.nextInt(5);
tissue = Tissue(game, this);
isAway = false;
ismoving = false;
}
newGame() async {
isAway = true;
GameTable.gameOver.resume();
await delay(Duration(seconds: 2), () {});
newBox();
}
static delay(duration, func()) async => await Future.delayed(duration, func);
}
class Tissue {
var tissueSprite = Sprite('t'), isMoving = false;
static var width = 100.0;
final TissueBox tissueBox;
final GameTable game;
bool isAway;
Rect rect;
Tissue(this.game, this.tissueBox, [this.isAway = false]) {
rect = tissueBox.initialRect;
}
render(Canvas c) => tissueSprite.renderRect(c, rect);
update(double t) => rect = isAway ? rect.shift(Offset.infinite) : tissueBox.initialRect;
}
class TissueAway extends Tissue {
TissueAway(GameTable game, TissueBox tissueBox) : super(game, tissueBox);
render(Canvas c) => tissueSprite.renderRect(c, rect);
update(double t) {
var speed = 500 * t;
Offset target = tissueBox.getTissueUpPosition - Offset(rect.left, rect.top);
if (speed < target.distance)
rect = rect.shift(Offset.fromDirection(target.direction, speed));
else
isAway = true;
}
}
The code in the main method will have a line that says runApp(...). The value of the ... is a widget that will be treated as the root widget of the app. In theory, you could just take that widget and pass it to your Navigator.push method and it should treat that widget as any other widget.
That being said, real life probably won't be as clean as this. There might be some initialization code in that app's main method or root widget that won't work properly if the app has long since already been initialized. Since virtually every Flutter app's root widget creates a WidgetsApp (or one of its derived classes MaterialApp or CupertinoApp), there might be some conflict that arrives from having one of those widgets being inserted as a descendent of another one of those widgets.
The game in question may work simply, or it might take some tweaking to work properly. That's something that will depend entirely on what app you are trying to embed into your own, so the only solution is to try it out and see for yourself.
I want to show random images in image.asset() this is what I have tried
static var listImagesnotFound = [
"assets/cactusno.jpg",
"assets/colorednot.jpg",
"assets/juno.jpg",
"assets/notfound.png",
"assets/robno.png",
"assets/spano.jpg"
];
static var _random = Random();
var imageToShow =
listImagesnotFound[_random.nextInt(listImagesnotFound.length)];
}
Image.asset(listImagesnotFound.toString()),
Try this:
dynamic listImagesnotFound = [
"assets/cactusno.jpg",
"assets/colorednot.jpg",
"assets/juno.jpg",
"assets/notfound.png",
"assets/robno.png",
"assets/spano.jpg"
];
Random rnd;
Widget buildImage(BuildContext context) {
int min = 0;
int max = listImagesnotFound.length-1;
rnd = new Random();
int r = min + rnd.nextInt(max - min);
String image_name = listImagesnotFound[r].toString();
return Image.asset(image_name);
}
Or
Image img() {
int min = 0;
int max = listImagesnotFound.length-1;
rnd = new Random();
int r = min + rnd.nextInt(max - min);
String image_name = listImagesnotFound[r].toString();
return Image.asset(image_name);
}
Then call your buildImage or img function like :
buildImage(context),
or
img(),
Random number can gererate any number so if you are not using min or max value it will return you an error if random number generated is larger then your assets list index.
Just change your code to,
Image.asset(imageToShow.toString()),