How to spot different locations with colors on Map? - flutter

Let me tell you what my motive is. I am making an app in which the locations which are highly affected by COVID is displayed by red, orange, and green colors. They are actually containers which are circular in shape and of these three colors.
But, I am not getting the output as I have created this.
Please see the code:-
import 'package:flutter/material.dart';
import 'package:latlong/latlong.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class MapIntegration extends StatefulWidget {
#override
_MapIntegrationState createState() => _MapIntegrationState();
}
class _MapIntegrationState extends State<MapIntegration> {
List redZoneData = new List();
List orangeZoneData = new List();
List greenZoneData = new List();
Map overallData = {
"Gujarat": LatLng(20.5937, 78.9629),
"Dehi": LatLng(20.5937, 78.9629)
};
int n = 2;
Map mapData;
var totalConfirmed;
var dataCalc;
var death;
var stateCode;
mapDataValue() async {
final url = 'https://api.rootnet.in/covid19-in/stats/latest';
final response = await http.get(url);
mapData = json.decode(response.body);
if (response.statusCode == 200) {
setState(() {
for (int index = 0;
index < mapData['data']['regional'].length;
index++) {
totalConfirmed = mapData['data']['regional'][index]['totalConfirmed'];
death = mapData['data']['regional'][index]['deaths'];
dataCalc = double.parse((totalConfirmed / death).toStringAsFixed(2));
stateCode = mapData['data']['regional'][index]['loc'];
if (dataCalc <= 40.00) {
redZoneData.add(stateCode);
} else {
// print(stateCode);
if (dataCalc > 40.00 && dataCalc <= 50.00) {
orangeZoneData.add(stateCode);
} else {
greenZoneData.add(stateCode);
}
}
}
print(redZoneData);
print(orangeZoneData);
print(greenZoneData);
});
} else {
throw Exception('loading failed...');
}
}
Widget dataEvaluation() {
var marker;
for (int index = 0; index < mapData['data']['regional'].length; index++) {
if (redZoneData.contains(mapData['data']['regional'][index]['loc'])) {
marker = new Marker(
width: 80.0,
height: 80.0,
point: new LatLng(20.5937, 78.9629),
builder: (ctx) => new Container(
height: 10,
width: 10,
decoration: new BoxDecoration(
shape: BoxShape.circle,
color: Colors.red,
),
),
);
} else if (orangeZoneData
.contains(mapData['data']['regional'][index]['loc'])) {
marker = new Marker(
width: 80.0,
height: 80.0,
point: new LatLng(20.5937, 78.9629),
builder: (ctx) => new Container(
height: 10,
width: 10,
decoration: new BoxDecoration(
shape: BoxShape.circle,
color: Colors.orange,
),
),
);
} else if (greenZoneData
.contains(mapData['data']['regional'][index]['loc'])) {
marker = new Marker(
width: 80.0,
height: 80.0,
point: new LatLng(20.5937, 78.9629),
builder: (ctx) => new Container(
height: 10,
width: 10,
decoration: new BoxDecoration(
shape: BoxShape.circle,
color: Colors.green,
),
),
);
}
}
return marker;
}
#override
void initState() {
mapDataValue();
super.initState();
}
#override
Widget build(BuildContext context) {
return Container(
height: MediaQuery.of(context).size.height / 1.3,
child: Column(
children: [
Container(
decoration: new BoxDecoration(
borderRadius: new BorderRadius.circular(30.0),
),
height: MediaQuery.of(context).size.height / 1.5,
alignment: Alignment.centerRight,
child: FlutterMap(
options: new MapOptions(
center: LatLng(22.5937, 78.9629),
zoom: 4.3,
),
layers: [
new TileLayerOptions(
urlTemplate:
'https://api.mapbox.com/styles/v1/shivam7007/ckevbwl2u6ty11an4bfbicex7/tiles/256/{z}/{x}/{y}#2x?access_token=pk.eyJ1Ijoic2hpdmFtNzAwNyIsImEiOiJja2VsMzRrcmcweW9vMnlwaXNiMzFrYjV2In0.CVRHP4CkMz_5UybuZ3CaIA',
additionalOptions: {
'acessToken':
'pk.eyJ1Ijoic2hpdmFtNzAwNyIsImEiOiJja2V0bXl4OXIxbmRrMnRvZWdkaWM5a29zIn0.doc-sYseA4b-Z7ylnp0Ttg',
'id': 'mapbox.mapbox-streets-v8',
},
),
new MarkerLayerOptions(
markers: [
dataEvaluation(),
],
),
],
),
),
Text('$dataCalc'),
],
),
);
}
}
And calling dataEvaluation() in MarkerLayerOption widget throws an error called "The element type 'Widget' can't be assigned to the list type 'Marker'."
Actually I have created a function calling dataEvaluation() which will calculate whether the STATE is present in the red, orange, or green zone, and according to that it will return the container based on the color red, orange, or gree, and that container will work as a spot on the map.
Please solve this, if you are finding any difficulty in understanding the question then please let me know. But please solve this. I am stuck finding nowhere.
API is = https://api.rootnet.in/covid19-in/stats/latest

I found this. It is easy as flutter provides you to write the single line code in the Widgets, so you can easily do the same.
for (var index in mapDataFinal)
if (redZoneData.contains(index))
new Marker(
width: 80.0,
height: 80.0,
point: new LatLng(26.8467, 80.9462),
builder: (ctx) => new Container(
height: 10,
width: 10,
decoration: new BoxDecoration(
shape: BoxShape.circle,
color: Colors.red,
),
),
)
Don't need to put curly braces over there.
Full Code is here:
new MarkerLayerOptions(markers: [
for (var index in mapDataFinal)
if (redZoneData.contains(index))
new Marker(
width: 80.0,
height: 80.0,
point: new LatLng(26.8467, 80.9462),
builder: (ctx) => new Container(
height: 10,
width: 10,
decoration: new BoxDecoration(
shape: BoxShape.circle,
color: Colors.red,
),
),
)
else if (orangeZoneData.contains(index))
new Marker(
width: 80.0,
height: 80.0,
point: new LatLng(10.8505, 76.2711),
builder: (ctx) => new Container(
height: 10,
width: 10,
decoration: new BoxDecoration(
shape: BoxShape.circle,
color: Colors.orange,
),
),
)
else if (greenZoneData.contains(index))
new Marker(
width: 80.0,
height: 80.0,
point: new LatLng(22.2587, 71.1924),
builder: (ctx) => new Container(
height: 10,
width: 10,
decoration: new BoxDecoration(
shape: BoxShape.circle,
color: Colors.green,
),
),
)
]),

Related

Can't figure out this Error "Bad state: Tried to read a provider that threw during the creation of its value.'"

I'm following this tutorial (https://www.youtube.com/watch?v=KO_PYJKHglo) and currently facing some problems. Where it all started is somewhere at 8:56 in the youtube video.
This is my main.dart file
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:secondlife_mobile/model.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: ChangeNotifierProvider(
create: (context) => PlayerModel(), child: const PlayerApp()),
),
);
}
class PlayerApp extends StatefulWidget {
const PlayerApp({super.key});
#override
State<PlayerApp> createState() => _PlayerAppState();
}
class _PlayerAppState extends State<PlayerApp> with TickerProviderStateMixin {
AnimationController? _controller;
Animation? _waveAnim;
Animation? _waveConstAmpAnim;
late PlayerModel model;
#override
void initState() {
super.initState();
_controller =
AnimationController(vsync: this, duration: const Duration(seconds: 20))
..addListener(() => setState(() {}));
_waveAnim =
Tween<double>(begin: 1, end: 1).animate(_controller! /*null safe*/);
_waveConstAmpAnim = Tween<double>(begin: 0, end: 1).animate(CurvedAnimation(
curve: Curves.easeInSine, parent: _controller! /*null safe*/));
_controller!.forward(); //null safe 6:32
}
#override
Widget build(BuildContext context) {
final height = MediaQuery.of(context).size.height;
final width = MediaQuery.of(context).size.width;
model = Provider.of<PlayerModel>(context);
return Scaffold(
body: Stack(
children: <Widget>[
Positioned(
height: height,
width: width,
child: Material(
elevation: 16,
color: const Color(0xFFd6dde5), //Background Color
borderRadius: BorderRadius.circular(20),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 30.0,
),
child: Column(
children: <Widget>[
const SizedBox(
height: 90,
),
const Text(
'Music title',
),
const SizedBox(
height: 15,
),
const Text(
'Music artist',
),
const SizedBox(
height: 75,
),
buildRecordPlayer(),
const SizedBox(
height: 60,
),
Row(
children: const <Widget>[
Text('time'),
SizedBox(
width: 8,
),
/*buildWave(width),*/
SizedBox(
width: 8,
),
Text('end'),
],
)
],
),
),
),
)
],
),
);
}
Widget buildRecordPlayer() {
return Container(
height: 270,
width: 270,
alignment: Alignment.center,
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/vinyl.png'),
fit: BoxFit.fitHeight,
colorFilter: ColorFilter.mode(
Colors.blue,
BlendMode.color,
),
),
shape: BoxShape.circle,
),
child: ClipOval(
child: Image.asset(
'assets/images/SL.png',
height: 165,
width: 165,
fit: BoxFit.fill,
),
),
);
}
}
And this is my model.dart file
import 'dart:math';
import 'package:flutter/material.dart';
import 'musicdata.dart';
class PlayerModel extends ChangeNotifier {
List<Music> musicList = [];
int _currentTrack = 0;
PlayerModel() {
for (int i = 0; i < Data.nameList.length; i++) {
musicList
.add(Music(artistName: Data.artistList[i], name: Data.nameList[i]));
}
musicList.removeWhere(
(musicItem) => musicItem.name == null || musicItem.artistName == null,
);
for (var musicItem in musicList) {
musicItem.duration = Duration(
minutes: Random().nextInt(5).clamp(1, 5),
seconds: Random().nextInt(59),
);
}
for (var music in musicList) {
print(music.name);
}
}
int get currentTrack => _currentTrack;
set currentTrack(int currentTrack) {
_currentTrack = currentTrack;
notifyListeners();
}
resetList() {
for (var music in musicList) {
music.isPlaying = false;
}
}
}
class Music {
String? name;
String? artistName;
Duration? duration;
bool? isPlaying = false;
Music({this.duration, this.artistName, this.isPlaying, this.name});
}
When I run this code with 'Run Without Debugging' this shows up.
So I started debugging and this showed up.
And this is how my debug console looks like right now.

Looking up a deactivated widget's ancestor is unsafe.Flutter integaration test

type here
iam new to flutter and trying to learn test integration test package and i have come around this error.
The following assertion was thrown while finalizing the widget
tree:
Looking up a deactivated widget's ancestor is unsafe.
At this point the state of the widget's element tree is no longer
stable.
To safely refer to a widget's ancestor in its dispose() method,
save a reference to the ancestor by calling
dependOnInheritedWidgetOfExactType() in the widget's
didChangeDependencies() method.
and to the little understanding that i have this is the class throwing that error
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
import 'package:wildai/helper/check_connectivity.dart';
import 'package:wildai/helper/common_methods.dart';
import 'package:wildai/helper/screen_config.dart';
import 'package:wildai/helper/toast_helper.dart';
import 'package:wildai/redux/actions.dart';
import 'package:wildai/redux/app_state.dart';
import 'package:wildai/redux/middleware/checkin_calls/checkin_update_get_data_call.dart';
import 'package:wildai/redux/middleware/homescreen_calls/update_single_view_calls.dart';
import 'package:wildai/src/models/dashboard/dashboard_model.dart';
import 'package:wildai/src/widgets/buttons/custom_radio_button.dart';
import 'package:wildai/src/widgets/custom_margins.dart';
import 'package:wildai/src/widgets/my_bottom_sheet.dart';
import 'package:wildai/utils/custom_alert.dart';
import 'package:wildai/utils/my_custom_text_theme.dart';
import 'package:wildai/helper/http_wrapper_custom.dart' as http;
import 'package:wildai/utils/my_redesign_icons.dart';
class EditCheckInOverlayPage extends StatefulWidget {
EditCheckInOverlayPage(this.title, this.avaiableCheckinItem,
this.updateCheckinsUrl, this.keyValue,
{Key key, this.showLoading = false, this.checkInRequestBody})
: super(key: key);
final String title;
final Map avaiableCheckinItem;
final String keyValue;
final String updateCheckinsUrl;
final Map checkInRequestBody;
bool showLoading;
\_EditCheckInOverlayPageState createState() =\> \_EditCheckInOverlayPageState();
}
class \_EditCheckInOverlayPageState extends State\<EditCheckInOverlayPage\> {
String micIconString = 'assets/icons/microphone.png';
Map responseBody = {'show_checkins': {}};
List\<AvaiableCheckinItemModel\> avaiableCheckinItems;
DateTime delayTime = DateTime.now();
final FlutterSecureStorage storage = new FlutterSecureStorage();
final store = StoreProvider.of\<AppState\>(SizeConfig.rootPagecOntext);
#override
void initState() {
super.initState();
avaiableCheckinItems = widget.avaiableCheckinItem\[widget.keyValue\];
List\<int\> requiredIntList = \[\];
for (var i = 0; i \< avaiableCheckinItems.length; i++) {
if (avaiableCheckinItems\[i\].require) {
requiredIntList.add(i);
}
}
for (int index in requiredIntList) {
var temp = avaiableCheckinItems\[index\];
avaiableCheckinItems.removeAt(index);
avaiableCheckinItems.insert(0, temp);
}
}
#override
void dispose() {
super.dispose();
if (mounted && !responseBody\['show_checkins'\].isEmpty) {
updateAvaiableCheckInsResponse();
print('///////////////////////////////');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.transparent,
body: Align(
alignment: Alignment.bottomCenter,
child: MyBottomModelSheet.titleSheet(
title: 'Edit ${widget.title} Check-ins',
height: 530,
onClose: () {
Navigator.pop(context);
},
body: sortDetailsContainer()),
),
);
}
Widget titleWidget() {
return Container(
decoration: BoxDecoration(color: Colors.white, boxShadow: \[
BoxShadow(
blurRadius: 25,
color: SizeConfig.primaryTextColour.withOpacity(.3),
)
\]),
child: Row(
children: \[
Expanded(
child: Padding(
padding: cmargin(top: 31, left: 30, right: 30),
child: Text(
'Edit ${widget.title} Check-Ins'.toUpperCase(),
style: MyCustomTextStyles().buttonTextSmall.copyWith(
color: SizeConfig.primaryTextColour.withOpacity(.4),
),
),
),
)
\],
),
);
}
Widget searchbarWidget() {
final \_formKey = GlobalKey\<FormState\>();
return Container(
color: Colors.white,
child: Padding(
padding: cmargin(left: 25, right: 25, bottom: 20, top: 22),
child: Container(
height: HelperMethods().getMyDynamicHeight(36),
decoration: BoxDecoration(
color: Color(0xff767680).withOpacity(.12),
borderRadius: BorderRadius.circular(10)),
child: Row(
children: \[
Padding(
padding: cmargin(left: 8, right: 7.37),
child: Container(
height: HelperMethods().getMyDynamicHeight(15.78),
width: HelperMethods().getMyDynamicWidth(15.63),
child: Icon(
MyAwesomeIcons.loupe,
color: Color(0xff8E8E93),
size: HelperMethods().getMyDynamicWidth(15.63),
),
),
),
Expanded(
child: Form(
key: \_formKey,
child: TextFormField(
onSaved: (String \_value) {
if (!\_formKey.currentState.validate() ||
\_value.isEmpty) {
return;
}
print(\_value);
},
style: MyCustomTextStyles().body.copyWith(
color: SizeConfig.primaryTextColour, height: 1),
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'Search',
hintStyle: MyCustomTextStyles().body.copyWith(
color: Color(0xff3C3C43).withOpacity(.6),
height: 1.1,
),
),
),
),
),
Padding(
padding: cmargin(right: 9.63),
child: Container(
height: HelperMethods().getMyDynamicHeight(16.37),
width: HelperMethods().getMyDynamicWidth(11),
child: Image.asset(
micIconString,
color: Color(0xff8E8E93),
fit: BoxFit.contain,
),
),
),
\],
),
),
));
}
Widget closeButton() {
return Container(
color: Colors.transparent,
height: HelperMethods().getMyDynamicWidth(55),
width: SizeConfig.screenWidth,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: \[
Padding(
padding: cmargin(right: 30, bottom: 25),
child: InkWell(
borderRadius: BorderRadius.circular(50),
onTap: () {
Navigator.pop(context);
},
child: Container(
decoration: BoxDecoration(
color: Colors.black.withOpacity(.2),
shape: BoxShape.circle,
),
height: HelperMethods().getMyDynamicWidth(30),
width: HelperMethods().getMyDynamicWidth(30),
child: Icon(
MyAwesomeIcons.close,
key: Key("close_button"),
size: HelperMethods().getMyDynamicWidth(30),
)),
),
)
\],
),
);
}
Widget sortDetailsContainer() {
return Expanded(
child: ModalProgressHUD(
inAsyncCall: false,
color: Colors.transparent,
child:
Container(
width: SizeConfig.screenWidth,
color: Colors.white,
child: Padding(
padding: cmargin(),
child: ListView(
padding: cmargin(),
children: List.generate(
avaiableCheckinItems.length + 1,
(index) => index == avaiableCheckinItems.length
? Container(
height: 50,
)
: InkWell(
key: Key(avaiableCheckinItems[index].displayName),
onTap: () {
//delayTime = DateTime.now();
if (avaiableCheckinItems[index].require &&
avaiableCheckinItems[index].selected) {
return;
}
avaiableCheckinItems[index].selected =
!avaiableCheckinItems[index].selected;
addToResponseBody(avaiableCheckinItems[index]);
setState(() {});
},
child: Container(
decoration: BoxDecoration(
border: Border(
top: BorderSide(
color: SizeConfig.primaryTextColour
.withOpacity(.4),
width: HelperMethods()
.getMyDynamicFontSize(.35)))),
child: Padding(
padding: cmargin(
left: 30, top: 20, bottom: 20, right: 30),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width:
HelperMethods().getMyDynamicWidth(244),
child: Row(
crossAxisAlignment:
CrossAxisAlignment.center,
children: [
Flexible(
child: Text(
avaiableCheckinItems[index]
.displayName,
style: MyCustomTextStyles()
.formText
.copyWith(
color: SizeConfig
.primaryTextColour,
height: 1),
),
),
avaiableCheckinItems[index].require
? Text(
' (required)',
style: MyCustomTextStyles()
.labelSmall
.copyWith(
color: SizeConfig
.primaryTextColour),
)
: Container()
],
),
),
Opacity(
opacity: avaiableCheckinItems[index]
.require &&
avaiableCheckinItems[index].selected
? .2
: 1,
child: CustomRadioButton(
onTap: (value) {
if (avaiableCheckinItems[index]
.require &&
avaiableCheckinItems[index]
.selected) {
return;
}
avaiableCheckinItems[index].selected =
!avaiableCheckinItems[index]
.selected;
addToResponseBody(
avaiableCheckinItems[index]);
setState(() {});
},
selected:
avaiableCheckinItems[index].selected,
),
)
],
),
),
),
)),
),
),
),
),
);
}
addToResponseBody(AvaiableCheckinItemModel checkInItem) {
if (responseBody\['show_checkins'\].containsKey(checkInItem.modelName)) {
responseBody\['show_checkins'\]\[checkInItem.modelName\]
\[checkInItem.dbVariable\] = checkInItem.selected;
} else {
responseBody\['show_checkins'\]\[checkInItem.modelName\] = {
checkInItem.dbVariable: checkInItem.selected
};
}
print(responseBody);
return;
}
updateAvaiableCheckInsResponse() {
Conn().connectivityResult().then((conn) async {
if (conn) {
final store = StoreProvider.of\<AppState\>(SizeConfig.rootPagecOntext);
String body = json.encode(responseBody);
responseBody = {'show_checkins': {}};
String token = await storage.read(key: "wildUserToken");
DashboardCheckInsModel oldCheckins =
store.state.dashboardDataModel.checkins;
store.state.dashboardDataModel.checkins = DashboardCheckInsModel();
store.dispatch(SetDashboardObject(store.state.dashboardDataModel));
if (widget.showLoading) {
await \_createCheckins(oldCheckins);
}
final response =
await http.post(Uri.encodeFull(widget.updateCheckinsUrl),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
"Authorization": "Token $token"
},
body: body);
if (response.statusCode == 200) {
store.state.dashboardDataModel.checkins = oldCheckins;
store.dispatch(updateDashboardCheckinCall(forceRefresh: true));
} else if (response.statusCode == 400 || response.statusCode == 500) {
var res = json.decode(response.body);
store.dispatch(SetDashboardObject(store.state.dashboardDataModel));
String msg = res\['details'\];
CustomAlert().showCustomAlert(
context, "Oops! Something went wrong. ", msg, AlertType.info);
} else {
store.dispatch(SetDashboardObject(store.state.dashboardDataModel));
// throw Exception("failed to load calendar");
}
} else {
ShowMyToastHelper().showCheckConnectionToast(context, 2);
}
});
}
Future \_createCheckins(DashboardCheckInsModel dashboardCheckInsModel) async {
await Conn().connectivityResult().then((bool conn) async {
if (conn) {
String body = json.encode(widget.checkInRequestBody);
String token = await storage.read(key: "wildUserToken");
final response = await http.post(
Uri.encodeFull(dashboardCheckInsModel.endpoints.submitCheckin.url),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
"Authorization": "Token $token"
},
body: body);
if (response.statusCode == 200) {
store.dispatch(checkInsUpdateGetDataCall(silenty: true));
}
} else {
ShowMyToastHelper().showCheckConnectionToast(context, 2);
}
});
}
}
the problem is the script runs and performs its actions but the test fails.
any guidance would be appreciated.if there is anymore information needed for clarification i'll be happy to provide it.

How can I design such custom JoystickView in Flutter?

I want to build JoystickView like this:
I ended up with this design:
Here is my code:
JoystickView(
showArrows: true,
innerCircleColor: Color(0xFF9510AC),
backgroundColor: Color(0xFF2D9BF0),
//size: 100,
size: MediaQuery.of(context).size.width * 0.45,
),
A very humble and kind-hearted soul Day Vy helped me giving the design with the code. I really appreciate his effort. God bless him.
Here is the code and Screen record.
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
enum JoystickDirection {
FORWARD,
REVERSE,
LEFT,
RIGTH,
STABLE,
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MainHandle(),
);
}
}
class MainHandle extends StatefulWidget {
#override
_MainHandleState createState() => _MainHandleState();
}
class _MainHandleState extends State<MainHandle> {
JoystickDirection joystickDirection = JoystickDirection.STABLE;
GlobalKey joystickBubbleKey = GlobalKey();
GlobalKey joyPadKey = GlobalKey();
Alignment bubblealignment = Alignment(0.1, 0.1);
double width = 70.0, height = 70.0;
double _x = 0;
double _y = 0;
Color color = Colors.white24;
var joyPadBox;
var joyPadpos;
late RenderBox bubbleBox;
_onDragStarted(DragUpdateDetails details) {
_dragwithinConstraints(details);
}
_dragwithinConstraints(DragUpdateDetails details) {
// first check if its within pad rectangular box
var offset = details.globalPosition;
if (offset.dx >= joyPadpos.dx + (bubbleBox.size.width / 2) &&
offset.dy >= joyPadpos.dy + (bubbleBox.size.height / 2) &&
offset.dy <=
joyPadpos.dy +
(joyPadBox.size.height) -
(bubbleBox.size.height / 2) &&
offset.dx <=
joyPadpos.dx + joyPadBox.size.width - (bubbleBox.size.width / 2)) {
setState(() {
if (details.delta.dy > 0) {
print("Dragging in +Y direction");
joystickDirection = JoystickDirection.FORWARD;
} else
joystickDirection = JoystickDirection.REVERSE;
bubblealignment = Alignment(offset.dx - (bubbleBox.size.width / 2),
offset.dy - (bubbleBox.size.height / 2));
});
}
}
_intitialPoint() {
this.joyPadBox = joyPadKey.currentContext?.findRenderObject() as RenderBox;
this.joyPadpos = joyPadBox.localToGlobal(Offset.zero);
this.bubbleBox =
joystickBubbleKey.currentContext?.findRenderObject() as RenderBox;
setState(() {
joystickDirection = JoystickDirection.STABLE;
bubblealignment = Alignment(
joyPadpos.dx +
(joyPadBox.size.width / 2) -
(bubbleBox.size.width / 2),
joyPadpos.dy +
(joyPadBox.size.height / 2) -
(bubbleBox.size.height / 2));
});
}
initState() {
super.initState();
WidgetsBinding.instance?.addPostFrameCallback((d) {
_intitialPoint();
});
}
_tiltForwardShandow() {
return BoxShadow(
offset: Offset(0, 10.0),
blurRadius: 5.0,
spreadRadius: 2,
color: Colors.grey.shade400);
}
_tiltBackwordShandow() {
return BoxShadow(
offset: Offset(0, -10.0),
blurRadius: 5.0,
spreadRadius: 2,
color: Colors.grey.shade400);
}
BoxShadow _resolveTilt() {
switch (joystickDirection) {
case JoystickDirection.FORWARD:
return _tiltForwardShandow();
// TODO: Handle this case.
break;
case JoystickDirection.REVERSE:
return _tiltBackwordShandow();
// TODO: Handle this case.
break;
case JoystickDirection.LEFT:
// TODO: Handle this case.
break;
case JoystickDirection.RIGTH:
// TODO: Handle this case.
break;
case JoystickDirection.STABLE:
return BoxShadow();
// TODO: Handle this case.
break;
}
return BoxShadow();
}
_joyStickBubble() {
return Container(
key: joystickBubbleKey,
height: 50,
width: 50,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
color.mix(Colors.black, .1),
color,
color,
color.mix(Colors.white, .5),
],
stops: [
0.0,
.3,
.6,
1.0,
]),
shape: BoxShape.circle,
boxShadow: [
_resolveTilt(),
BoxShadow(color: Colors.grey.shade400),
BoxShadow(
color: Colors.grey.shade300,
blurRadius: 12,
spreadRadius: -12)
]));
}
Widget draggable() {
return Positioned(
top: bubblealignment.y,
left: bubblealignment.x,
child: Container(
height: 50,
width: 50,
child: _joyStickBubble(),
),
);
}
#override
Widget build(BuildContext context) {
return Material(
child: Transform(
alignment: Alignment.center,
transform: Matrix4.rotationY(0.1),
child: AnimatedContainer(
duration: Duration(seconds: 10),
child: GestureDetector(
onPanEnd: (details) {
_intitialPoint();
},
onPanUpdate: (details) {
_onDragStarted(details);
// bubblealignment = Alignment(details.delta.dx, details.delta.dy);
// if (details.delta.dx > 0) {
// print("Dragging in +X direction");
// } else
// print("Dragging in -X direction");
// if (details.delta.dy > 0) {
// print("Dragging in +Y direction");
// setState(() {
// joystickDirection = JoystickDirection.FORWARD;
// });
// } else
// setState(() {
// joystickDirection = JoystickDirection.REVERSE;
// });
},
child: Stack(
alignment: Alignment.center,
children: [
Container(
key: joyPadKey,
height: 200,
width: 200,
child: Column(
children: [
Container(
alignment: Alignment.topCenter,
child: Padding(
padding: EdgeInsets.symmetric(vertical: 40),
child: Text(
"Forwards",
style: TextStyle(
shadows: <Shadow>[_resolveTilt()],
),
),
)),
Spacer(),
Container(
alignment: Alignment.topCenter,
child: Padding(
padding: EdgeInsets.symmetric(vertical: 40),
child: Text(
"Reverse",
style: TextStyle(
shadows: <Shadow>[
_resolveTilt(),
],
),
),
)),
],
),
decoration:
BoxDecoration(shape: BoxShape.circle, boxShadow: [
_resolveTilt(),
BoxShadow(color: Colors.grey.shade400),
BoxShadow(
color: Colors.grey.shade300,
blurRadius: 12,
spreadRadius: -12)
])),
// Container(
// alignment: Alignment.center,
// height: 200,
// width: 200,
// child: Stack(
// children: [
// Align(
// alignment: Alignment.topCenter,
// child: Icon(Icons.keyboard_arrow_up)),
// Align(
// alignment: Alignment.centerRight,
// child: Icon(Icons.keyboard_arrow_right)),
// Align(
// alignment: Alignment.centerLeft,
// child: Icon(Icons.keyboard_arrow_left)),
// Align(
// alignment: Alignment.bottomCenter,
// child: Icon(Icons.keyboard_arrow_down)),
// ],
// ),
// ),
Container(
height: 30,
width: 200,
decoration: BoxDecoration(shape: BoxShape.rectangle,
// borderRadius: BorderRadius.circular(25),
boxShadow: [
_resolveTilt(),
BoxShadow(color: Colors.grey.shade400),
BoxShadow(
color: Colors.white,
blurRadius: 6,
spreadRadius: -1)
])),
draggable(),
],
),
),
),
),
);
}
}
extension ColorUtils on Color {
Color mix(Color? another, double amount) {
return Color.lerp(this, another, amount)!;
}
}
Joystick
Custom Joystick

Error while trying to load an asset: FormatException: Illegal scheme character - error while using image picker

I am trying to enable to the app user to change his/her profile picture and upload it via camera or gallery, I used
the image picker package for this purpose,
this is my code snippet:
`
class ProfilePic extends StatefulWidget {
const ProfilePic({
Key key,
}) : super(key: key);
#override
_ProfilePicState createState() => _ProfilePicState();
}
class _ProfilePicState extends State<ProfilePic> {
File image = new File("");
final _picker = ImagePicker();
#override
Widget build(BuildContext context) {
return SizedBox(
height: 115,
width: 115,
child: Stack(
fit: StackFit.expand,
overflow: Overflow.visible,
children: [
CircleAvatar(
backgroundImage: AssetImage(image.uri.toFilePath()),
// child: ClipRRect(
// borderRadius: BorderRadius.circular(50),
// child: image != null
// ? Image.file(
// image,
// width: 115,
// height: 115,
// fit: BoxFit.fitHeight,
// )
// : Container(
// decoration: BoxDecoration(
// color: Colors.grey[100],
// borderRadius: BorderRadius.circular(50)),
// width: 100,
// height: 100,
// child: Icon(
// Icons.camera_alt,
// color: Colors.grey[800],
// ),
// ),
// ),
),
Positioned(
right: -16,
bottom: 0,
child: SizedBox(
height: 46,
width: 46,
child: FlatButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50),
side: BorderSide(color: Colors.white),
),
color: Color(0xFFF5F6F9),
onPressed: () {
_showPicker(context);
},
child: SvgPicture.asset("icons/cameraIcon.svg"),
),
),
)
],
),
);
}
_imgFromCamera() async {
PickedFile pickedFile =
await _picker.getImage(source: ImageSource.camera, imageQuality: 50);
setState(() {
image = File(pickedFile.path);
});
}
_imgFromGallery() async {
PickedFile pickedFile =
await _picker.getImage(source: ImageSource.gallery, imageQuality: 50);
setState(() {
image = File(pickedFile.path);
});
}
void _showPicker(context) {
showModalBottomSheet(
context: context,
builder: (BuildContext bc) {
return SafeArea(
child: Container(
child: new Wrap(
children: <Widget>[
new ListTile(
leading: new Icon(Icons.photo_library),
title: new Text('Gallerie'),
onTap: () {
_imgFromGallery();
Navigator.of(context).pop();
}),
new ListTile(
leading: new Icon(Icons.photo_camera),
title: new Text('Caméra'),
onTap: () {
_imgFromCamera();
Navigator.of(context).pop();
},
),
],
),
),
);
});
}
}
`
PS: I am using Chrome for debugging.
Its select the image from the device but doesn't change the state to upload the image, am asking if it is a flutter web related problem so in a real device or emulator can work smoothly?
Any suggestion please.
AssetImage takes asset files that you have referenced in your pubspec.yaml. you should use FileImage instead if you are trying to display images from the camera or gallery.
example: FileImage(image)
You can read more here

The data from my firestore isn't displayed

I tried to build an application, which shows the user some places on a google maps. The data for the places (location, name) should the app take from the firestore. The app already can display the maker in the google maps, but I also want some details in the bottom of the application in an Animated Builder, but it doesn't work. The problem is, that I can't get the name of the place with specify['name'] in my _restaurantList function, but in the initMarker function it works. I think it has to do something with the _restaurantList(specify) and the return _restaurantList(index) but I don't know what the mistake is. I also tried to use specify instead of index in the _restaurantList(index), but then I got an error. But I think I have to use _restaurantList(specify) in order to use specify['name'] afterwards.
Does anyone know what my mistake is?
That's my code:
void initMarker(specify, specifyId) async {
// await Firebase.initializeApp();
var markerIdVal = specifyId;
final MarkerId markerId = MarkerId(markerIdVal);
final Marker marker = Marker(
markerId: markerId,
position:
LatLng(specify['location'].latitude, specify['location'].longitude),
infoWindow: InfoWindow(title: specify['name'], snippet: 'Shop'),
);
print(specify['location'].latitude);
nameTest = specify['name'];
setState(() {
markers[markerId] = marker;
print(markerId.toString() + '__________________________');
});
}
getMarkerData() async {
Firestore.instance.collection('seller').getDocuments().then((myMockDoc) {
if (myMockDoc.documents.isNotEmpty) {
for (int i = 0; i < myMockDoc.documents.length; i++) {
length = myMockDoc.documents.length;
print(length);
initMarker(
myMockDoc.documents[i].data(), myMockDoc.documents[i].documentID);
}
}
});
}
_restaurantList(specify) {
return AnimatedBuilder(
animation: _pageController,
builder: (BuildContext context, Widget widget) {
double value = 1;
if (_pageController.position.haveDimensions) {
//value = _pageController.page - index;
value = (1 - (value.abs() * 0.3) + 0.06).clamp(0.0, 1.0);
}
return Center(
child: SizedBox(
height: Curves.easeInOut.transform(value) * 175.0,
width: Curves.easeInOut.transform(value) * 350.0,
child: widget,
),
);
},
child: InkWell(
onTap: () {
null;
},
child: Stack(
children: [
Center(
child: Container(
margin: EdgeInsets.symmetric(
horizontal: 10.0,
vertical: 20.0,
),
height: 125.0,
width: 275.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
boxShadow: [
BoxShadow(
color: Colors.black54,
offset: Offset(0.0, 4.0),
blurRadius: 10.0,
),
]),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color: Colors.white),
child: Text(
specify['name'],
),
),
),
)
],
),
),
);
}
And this is in the Scaffold:
Positioned(
bottom: 20.0,
child: Container(
height: 200.0,
width: MediaQuery.of(context).size.width,
child: PageView.builder(
controller: _pageController,
itemCount: length,
itemBuilder: (BuildContext context, int index) {
return _restaurantList(index);
},
),
),
)