Getting "Unhandled Exception: NoSuchMethodError: The method 'map' was called on null" - flutter

Main.dart file
import 'package:flutter/material.dart';
import 'package:weather_app/listModel.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:weather_app/model.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
var listModel;
bool circular = true;
#override
void initState() {
super.initState();
getData();
}
void getData() async {
var res = await http.get(Uri.parse('https://www.metaweather.com/api/location/2295420/'));
var r = json.decode(res.body);
setState(() {
listModel = ListModel.fromJson({"data": r});
print(listModel);
circular = false;
});
//
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('WEATHER REPORT'),
),
body: Center(
child: circular ? CircularProgressIndicator(): ListView.builder(itemCount: listModel.consolidatedWeather.length,itemBuilder: (BuildContext context, int index)=>
dataShow(listModel.consolidatedWeather[index],index)),
)
),
);
}
Widget dataShow(Model obj, index) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10),
child: Container(
height: 100,
// width: MediaQuery.of(context).size.width,
child: Card(
color: Colors.teal,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Name ${index + 1} : ${obj.weatherStateName}",
style: TextStyle(fontSize: 18, color: Colors.white),
),
SizedBox(
height: 10,
),
Text(
"PhoneNumber : ${obj.theTemp}",
style: TextStyle(fontSize: 18, color: Colors.white),
),
],
),
),
),
);
}
}
List Model.dart
import 'package:weather_app/model.dart';
class ListModel {
ListModel({
required this.consolidatedWeather,
});
List<Model> consolidatedWeather;
factory ListModel.fromJson(Map<String, dynamic> json) => ListModel(
consolidatedWeather: List<Model>.from(json["consolidated_weather"].map((x) => Model.fromJson(x))).toList(),
);
Map<String, dynamic> toJson() => {
"consolidated_weather": List<dynamic>.from(consolidatedWeather.map((x) => x.toJson())),
};
}
Model.dart
class Model {
Model({
required this.weatherStateName,
required this.weatherStateAbbr,
required this.applicableDate,
required this.theTemp,
});
String weatherStateName;
String weatherStateAbbr;
DateTime applicableDate;
double theTemp;
factory Model.fromJson(Map<String, dynamic> json) => Model(
weatherStateName: json["weather_state_name"],
weatherStateAbbr: json["weather_state_abbr"],
applicableDate: DateTime.parse(json["applicable_date"]),
theTemp: json["the_temp"].toDouble(),
);
Map<String, dynamic> toJson() => {
"weather_state_name": weatherStateName,
"weather_state_abbr": weatherStateAbbr,
"applicable_date": "${applicableDate.year.toString().padLeft(4, '0')}-${applicableDate.month.toString().padLeft(2, '0')}-${applicableDate.day.toString().padLeft(2, '0')}",
"the_temp": theTemp,
};
}
pupspec.yml
name: weather_app
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
meta: ^1.0.2
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
http: ^0.13.3
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
ERROR
Performing hot restart...
Syncing files to device Redmi Note 9 Pro...
Restarted application in 1,965ms.
E/flutter (26913): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: NoSuchMethodError: The method 'map' was called on null.
E/flutter (26913): Receiver: null
E/flutter (26913): Tried calling: map(Closure: (dynamic) => Model)
E/flutter (26913): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter (26913): #1 new ListModel.fromJson (package:weather_app/listModel.dart:11:72)
E/flutter (26913): #2 _MyAppState.getData.<anonymous closure> (package:weather_app/main.dart:30:29)
E/flutter (26913): #3 State.setState (package:flutter/src/widgets/framework.dart:1088:30)
E/flutter (26913): #4 _MyAppState.getData (package:weather_app/main.dart:29:5)
E/flutter (26913): <asynchronous suspension>
E/flutter (26913):
W/Choreographer(26913): Frame time is 0.009381 ms in the future! Check that graphics HAL is generating vsync timestamps using the correct timebase.
W/Choreographer(26913): Frame time is 0.021302 ms in the future! Check that graphics HAL is generating vsync timestamps using the correct timebase.
W/Choreographer(26913): Frame time is 0.006804 ms in the future! Check that graphics HAL is generating vsync timestamps using the correct timebase.
W/Choreographer(26913): Frame time is 0.064763 ms in the future! Check that graphics HAL is generating vsync timestamps using the correct timebase.
What can I try next to resolve this?

The getData() fn should go like this..
void getData() async {
var res = await http.get(Uri.parse('https://www.metaweather.com/api/location/2295420/'));
var r = json.decode(res.body);
setState(() {
listModel = ListModel.fromJson(r); // Change this line
print(listModel);
circular = false;
});
}

Related

issue with video_player and channel getting null

i got a issue that i try understand how i can fix this
i get this error message about the Unhandled Exception: PlatformException(channel-error, Unable to establish connection on channel., null, null)
i have try look into but i have no idea why or how it hapending the full message within the post
i try understand what the origin this happened i try clean the build folder via flutter clean this happend
i try run build runner it may missing something nope i got no idea what seem to be the issue here
[GETX] REPLACE ROUTE /splash
[GETX] NEW ROUTE /login
I/flutter (17459): ┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
I/flutter (17459): │ #0 LoggerService.info
package:demo_ecom/…/utils/logger_service.dart:19
I/flutter (17459): │ #1 _LoginScreenState.initState
package:demo_ecom/…/login/login_screen.dart:32
I/flutter (17459): ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
I/flutter (17459): │ 💡 Load Login Screen
I/flutter (17459): └───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
E/flutter (17459): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: PlatformException(channel-error, Unable to establish connection on channel., null, null)
E/flutter (17459): #0 VideoPlayerApi.initialize
package:video_player_platform_interface/messages.dart:156
E/flutter (17459): <asynchronous suspension>
E/flutter (17459):
E/flutter (17459): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: PlatformException(channel-error, Unable to establish connection on channel., null, null)
E/flutter (17459): #0 VideoPlayerApi.create
package:video_player_platform_interface/messages.dart:181
E/flutter (17459): <asynchronous suspension>
E/flutter (17459): #1 MethodChannelVideoPlayer.create
package:video_player_platform_interface/method_channel_video_player.dart:47
E/flutter (17459): <asynchronous suspension>
E/flutter (17459): #2 VideoPlayerController.initialize
package:video_player/video_player.dart:308
E/flutter (17459): <asynchronous suspension>
E/flutter (17459):
Lost connection to device.
the file that play this vid as follow
import 'dart:async';
import 'package:demo_ecom/common/utils/logger_service.dart';
import 'package:demo_ecom/widgets/login/login_buttons.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:video_player/video_player.dart';
import 'package:demo_ecom/generated/l10n.dart';
import 'login_form.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({Key key}) : super(key: key);
#override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final _formKey = GlobalKey<FormState>();
VideoPlayerController _controller;
bool _visible = false;
#override
void initState() {
super.initState();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
LoggerService().info('Load Login Screen');
_controller = VideoPlayerController.asset('assets/media/login-vid.mp4');
_controller.initialize().then((_) {
_controller.setLooping(true);
Timer(const Duration(milliseconds: 100), () {
setState(() {
_controller.play();
_visible = true;
});
});
});
}
#override
void dispose() {
super.dispose();
if (_controller != null) {
_controller.dispose();
_controller = null;
}
}
Widget _getVideoBackground() {
return AnimatedOpacity(
opacity: _visible ? 1.0 : 0.0,
duration: const Duration(milliseconds: 1000),
child: VideoPlayer(_controller),
);
}
Widget _getBackgroundColor() {
return Container(
color: Colors.black.withAlpha(120),
);
}
Widget _getContent(BuildContext context) {
final splogen_1 = S.of(context).login_slogen;
final splogen_2 = S.of(context).login_slogen2;
return Form(
key: _formKey,
child: ListView(
shrinkWrap: true,
padding: EdgeInsets.all(15.0),
children: <Widget>[
const SizedBox(
height: 40.0,
),
const Image(
image: AssetImage('assets/media/logo.jpg'),
width: 150.0,
),
Text(
splogen_1,
style: TextStyle(color: Colors.white, fontSize: 40),
textAlign: TextAlign.center,
),
Container(
margin: const EdgeInsets.only(left: 30.0, right: 30.0, top: 40.0),
alignment: Alignment.center,
child: Text(
splogen_2,
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 20),
),
),
LoginForm(),
LoginButtons()
],
),
);
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Center(
child: Stack(
children: <Widget>[
_getVideoBackground(),
_getBackgroundColor(),
_getContent(context),
],
),
),
),
);
}
}
the pubspec as follow
name: demo_ecom
description: Demo Ecom App
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+2
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
# Service locator
provider: ^5.0.0
# Connectivity
data_connection_checker: ^0.3.4
# Logging
logger: ^1.0.0
# Json
json_annotation: ^4.0.1
# firebase
firebase_core: ^0.7.0
firebase_remote_config: "^0.6.0"
firebase_auth: "^0.20.1"
firebase_crashlytics: ^0.4.0+1
#auth social
google_sign_in: "^4.5.1"
flutter_facebook_auth: "^1.0.0"
# localization
intl: ^0.17.0
# ui tools
flutter_password_strength: ^0.1.6
flutter_signin_button: ^1.1.0
animations: ^2.0.0
pull_to_refresh: ^1.6.4
get: ^3.26.0
flutter_easyloading: ^3.0.0
responsive_framework: ^0.1.0
animated_text_kit: ^4.1.0
flutter_spinkit: "^5.0.0"
convex_bottom_bar: ^3.0.0
introduction_screen: ^2.0.0
flash: ^1.5.1
material_floating_search_bar: ^0.3.3
video_player: ^2.0.0
chewie: ^1.0.0
# ui icons
cupertino_icons: ^1.0.2
font_awesome_flutter: ^9.0.0
flutter_icons: ^1.1.0
# misc tools
validators: ^2.0.1
dio: ^3.0.10
pretty_dio_logger: ^1.1.1
jiffy: ^4.0.0
equatable: ^2.0.0
meta: ^1.3.0
stack_trace: ^1.10.0
shared_preferences: ^2.0.5
async: ^2.5.0
# override requirement that conflict will rise if removed
dependency_overrides:
analyzer: ^1.3.0
yaml: ^3.1.0
intl: ^0.17.0
dart_style: ^2.0.0
args: ^2.0.0
glob: ^2.0.0
source_gen: ^1.0.0
logging: ^1.0.1
convert: ^3.0.0
crypto: ^3.0.0
vin_decoder: ^0.1.3
json_annotation: ^4.0.1
font_awesome_flutter: ^9.0.0
dev_dependencies:
# add build runner if not already added
build_runner: ^1.12.2
flutter_test:
sdk: flutter
# Linting
lint: ^1.5.3
# Json
json_serializable: ^4.1.0
# misc tools
mockito: ^5.0.2
flutter_launcher_icons: ^0.9.0
environment_config: ^2.2.5
flutter_rename_app: ^1.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
assets:
- assets/fonts/
- assets/media/
- assets/icons/
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-package
# To hide the notification bar, use the fullscreen parameter. Has no affect in web since web
# has no notification bar. Defaults to false.
# NOTE: Unlike Android, iOS will not automatically show the notification bar when the app loads.
# To show the notification bar, add the following code to your Flutter app:
# WidgetsFlutterBinding.ensureInitialized();
# SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.bottom, SystemUiOverlay.top]);
#fullscreen: true
# If you have changed the name(s) of your info.plist file(s), you can specify the filename(s)
# with the info_plist_files parameter. Remove only the # characters in the three lines below,
# do not remove any spaces:
#info_plist_files:
# - 'ios/Runner/Info-Debug.plist'
# - 'ios/Runner/Info-Release.plist'
flutter_intl:
enabled: true
localizely:
project_id: c4305176-c927-4336-80bd-7bbc91f25b3d
flutter_icons:
image_path: 'assets/assets/icons/app_icon.png'
android: true
ios: true
flutter_rename_app:
application_name: Demo Ecom
dart_package_name: demo_ecom
application_id: com.wolberg.pro.demo
bundle_id: com.wolberg.pro.demo
android_package_name: com.wolberg.pro.demo
targets:
$default:
builders:
injectable_generator:injectable_builder:
options:
auto_register: true
# auto registers any class with a name matches the given pattern
class_name_pattern:
"Service$|Repository$"
# auto registers any class inside a file with a
# name matches the given pattern
file_name_pattern: "_service$|_repository$"
#flutter pub run flutter_rename_app
i got no idea what i can do not sure what i did here wrong thanks for the helpers

I have a generated a QR code but the source code does not scan the generated QR code

I have a generated a QR code but the source code does not scan the generated QR code.
I have a QR code scanner template but it does not scan the generated QR code.
It can only Generate a QR code but it does not scan the Code.
The onPressed method is supposed to be scanning the generated code.
I get this error when I click the floating Button
Unhandled Exception: MissingPluginException(No implementation found for method scanBarcode on channel flutter_barcode_scanner)
import 'package:flutter/material.dart';
//import 'package:qr_flutter/qr_flutter.dart';
//import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';
//import 'package:qr_code';;
import 'package:qrscan/qrscan.dart' as scanner;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
title: "flutter Demo",
theme: ThemeData(
primaryColor: Colors.blue,
),
home: MyHomePage(title: "Flutter QR"),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String barcode = "";
Future scanBarcode() async {
String barcodeResult = await scanner.scan();
setState(() {
barcode = barcodeResult;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
children: <Widget>[
/*QrImage(
data: "Savanna, R25",
backgroundColor: Colors.white,
size: 200,
)*/
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => scanBarcode(),
tooltip: "increment",
child: Icon(Icons.add),
),
);
}
}
My Pubspec.yaml file with plugins
name: fluttersqflite
description: A new Flutter application.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.0
qr_flutter: ^3.0.1
flutter_barcode_scanner: ^0.1.7
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
Give a try to this plugin- qrscan
and in your dart file write this:-
import 'package:qrscan/qrscan.dart' as scanner;
Function for scan:-
Future _scan() async {
String barcode = await scanner.scan();
setState(() {
barcode = barcodeResult;
});
}
And in your floating action button:-
floatingActionButton: FloatingActionButton(
onPressed: ()=>_scan(),
tooltip: "increment",
child: Icon(Icons.add),
),
And ya remember to add permission for this dependency

Image does not show on leading part of list tile when using Circle Avatar and back ground image

I am building this app and just have a small UI problem. I am using a ListView builder. On the leading part of the tile, I want a circular icon to display with the desired image.
I believe my implementation is correct but when I run my code the circle avatar does come out on the leading part of the tile but it does not display the desired image. Instead, it just shows a blue circle on the leading end of each tile.
I am also getting an exception from the terminal. I will attach my code and the exception that I am getting. I would really appreciate suggestions from anyone. Thank you all!
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
List<String> titles = ["Covid-19 Cases", "Covid-19 Vaccine Tracker",
"Dr. John Campbell Youtube Channel", "Medcram YouTube Channel"];
List<String> files = ["cases.png", "vaccineIMG.png", "dr.johncampbell.png",
"Medcram.png"];
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.black54,
appBar: AppBar(
backgroundColor: Colors.redAccent,
title: Text("Your Covid-19 Briefing"),
),
body: ListView.builder(
itemCount: titles.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
onTap: () {
_launchUrl(index);
},
title: Text(
titles[index],
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
letterSpacing: 1.0,
color: Colors.black,
),
),
leading: CircleAvatar(
backgroundImage: AssetImage('assets/${files[index]}'),
),
),
);
}
),
),
);
}
_launchUrl(index) async {
List<String> _urlsToLaunch = [
"https://www.worldometers.info/coronavirus/",
"https://www.nytimes.com/interactive/2020/science/coronavirus-vaccine-tracker.html",
"https://www.youtube.com/c/Campbellteaching/videos/",
"https://www.youtube.com/c/Medcram/videos"
];
if (await canLaunch(_urlsToLaunch[index])) {
await launch(_urlsToLaunch[index]);
} else {
throw "Could not open $_urlsToLaunch";
}
}
}
Error:
════════ Exception caught by image resource service ════════════════════════════════════════════════
The following assertion was thrown resolving an image codec:
Unable to load asset: assets/cases.png
When the exception was thrown, this was the stack:
#0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
<asynchronous suspension>
#1 AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:664:31)
#2 AssetBundleImageProvider.load (package:flutter/src/painting/image_provider.dart:648:14)
#3 ImageProvider.resolveStreamForKey.<anonymous closure> (package:flutter/src/painting/image_provider.dart:501:13)
...
Image provider: AssetImage(bundle: null, name: "assets/cases.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#e7274(), name: "assets/cases.png", scale: 1.0)
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by image resource service ════════════════════════════════════════════════
Unable to load asset: assets/vaccineIMG.png
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by image resource service ════════════════════════════════════════════════
Unable to load asset: assets/dr.johncampbell.png
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by image resource service ════════════════════════════════════════════════
Unable to load asset: assets/Medcram.png
════════════════════════════════════════════════════════════════════════════════════════════════════
pubspec.yaml file:
name: coronavirus_news_updates
description: A new Flutter application.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
url_launcher: ^5.4.11
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.3
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
Have you included your assets in your pubspec.yaml file?
flutter:
assets:
- assets/your_image_name.png
or to incude the entire folder:
flutter:
assets:
- assets/

image asset not loading in flutter firebase project

I am following one tutorial on flutter and I am trying to load an image, unfortunately, the image was unable to load. I always have an error in console that the image was unable to load.my code is as followed:
import 'dart:ffi';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
final GoogleSignIn googleSignIn = new GoogleSignIn();
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
bool isAuth = false;
#override
Void initState() {
super.initState();
//detect when user sign in
googleSignIn.onCurrentUserChanged.listen((account) {
handleSignIn(account);
}, onError:(err){
print('error signing in:$err');
}
);
//re-authenticated when user sign in the app
googleSignIn.signInSilently(suppressErrors: false).then((account){
handleSignIn(account);
}).catchError((err){
print('error signing in:$err');
});
}
handleSignIn(GoogleSignInAccount account){
if (account != null) {
print(account);
setState(() {
isAuth = true;
});
} else {
setState(() {
isAuth = false;
});
}
}
login() {
googleSignIn.signIn();
}
logOut(){
googleSignIn.signOut();
}
Widget buildAuthScreen() {
return RaisedButton(
child:Text("LogOut"),
onPressed: (){
logOut();
},
);
}
Scaffold unAuthBuildScreen() {
return Scaffold(
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [
Theme.of(context).primaryColor,
Theme.of(context).accentColor,
],
),
),
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
"FlutterShare",
style: TextStyle(
//fontFamily: "Signatra",
fontSize: 50.0,
color: Colors.white,
),
),
GestureDetector(
onTap: () => print("tapped"),
child: Container(
width: 260.0,
height: 60.0,
decoration: BoxDecoration(
image: DecorationImage(
// image:AssetImage(bund"assets/images/google_sigin_button.png"),
image: AssetImage("assets/images/google_sigin_button.png"),
fit: BoxFit.fill),
),
),
),
],
),
),
);
}
#override
Widget build(BuildContext context) {
return isAuth ? buildAuthScreen() : unAuthBuildScreen();
}
}
pubspec.yaml is as follows.Please help me
name: fluttershare
description: A new Flutter project.
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
firebase_auth: ^0.15.5+3
firebase_database: ^3.1.3
cloud_firestore: ^0.13.4+1
image_picker: ^0.6.4
firebase_storage: ^3.1.5
google_sign_in: ^4.4.1
geolocator: ^5.3.1
uuid: ^2.0.4
timeago: ^2.0.26
path_provider: ^1.6.4
flutter_svg:
cached_network_image: ^2.0.0
firebase_messaging: ^6.0.13
image: ^2.1.4
animator: ^1.0.0+5
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
uses-material-design: true
assets:
- assets/images/google_signin_button.png
- assets/images/upload.svg
- assets/images/search.svg
- assets/images/activity_feed.svg
- assets/images/no_content.svg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
please help I have been on this for the past 3 days
Here is the Android’s density to Flutter pixel ratio
Android density qualifier Flutter pixel ratio
ldpi 0.75x
mdpi 1.0x
hdpi 1.5x
xhdpi 2.0x
xxhdpi 3.0x
xxxhdpi 4.0x
Best way to add images is to create an asset directory structure like that.
Put your images base on the density mapping to appropriate folder, flutter will pick image based on the device density.
You don't need to add every image path in pubspec.yaml only root folder is enough. Make sure assets and pubspec.yaml are in same directory level.
flutter:
assets:
- assets/images/
Hope it will solve your problem.
I think if you're using firebase for the authentication, you should use firebase storage to store your images.
You need these imports.
import 'package:firebase_storage/firebase_storage.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cached_network_image/cached_network_image.dart';
And in the main function you need this code.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
UserCredential userCredential = await FirebaseAuth.instance
.signInAnonymously(); // you need to indentify your user
print(userCredential);
runApp(MyApp());
}
You can load your images with this code.
FutureBuilder<dynamic>(
future: FirebaseStorage().ref('google_sigin_button.png').getDownloadURL(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
if (snapshot.connectionState != ConnectionState.waiting) {
return Image(
image: CachedNetworkImageProvider(snapshot.data.toString()),
fit: BoxFit.cover,
);
} else {
return Text('Loading image....');
}
},
),
If you need more information how this actually work, you should see my github repository where you can find an example for this.
https://github.com/orosiferenc3/Flutter_Firebase_Storage_connection

fromCsv returns a cannot open file exception

I am trying to use the ml_algo package to get a dataset using the fromCsv method present in the ml_algo package. I have put the csv file into an asset folder and still get an error.
I have tried all possible ways from flutter clean to invalidate cache and restart and even tried putting it on my phone and I gave the absolute path still it does not work
The following is the dart code:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:ml_dataframe/ml_dataframe.dart';
import 'package:ml_preprocessing/ml_preprocessing.dart';
import 'package:ext_storage/ext_storage.dart';
import 'package:permission/permission.dart';
import 'package:path_provider/path_provider.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
Future<void> initialiseDataframe() async {
/* var permissionsRequested = await Permission.requestSinglePermission(PermissionName.Storage);
print(permissionsRequested);
var permissionsStatus = await Permission.getSinglePermissionStatus(PermissionName.Storage);
print(permissionsStatus.toString());
*/
Directory tempDir = await getTemporaryDirectory();
String tempdir = tempDir.absolute.path;
print(tempdir);
final String directory = await ExtStorage.getExternalStorageDirectory();
print(directory);
final dataFrame = await fromCsv('wheat.csv',
headerExists: true,
columns: [2,3,5,6,7,8,9,10,11,12,13,14,15,16,
17,18,19,20,21,22,23,24,25]);
final normaliser = Normalizer();
final transformedDataset = normaliser.process(dataFrame);
print(transformedDataset.toMatrix());
}
#override
void initState() {
initialiseDataframe();
}
}
and here is the pubspec.yaml file
name: linear_regression
description: A new Flutter application.
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
ml_dataframe: ^0.0.11
ml_preprocessing: ^5.0.1
ml_algo: ^13.3.7
ext_storage: ^1.0.2
permission: ^0.1.5
path_provider: ^1.6.1
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- assets/res/wheat.csv
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
and the error stack
E/flutter (26103): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: FileSystemException: Cannot open file, path = 'asset/res/wheat.csv' (OS Error: No such file or directory, errno = 2)
E/flutter (26103): #0 _File.open.<anonymous closure> (dart:io/file_impl.dart:366:9)
E/flutter (26103): #1 _rootRunUnary (dart:async/zone.dart:1134:38)
E/flutter (26103): #2 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (26103): #3 _FutureListener.handleValue (dart:async/future_impl.dart:139:18)
E/flutter (26103): #4 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:680:45)
E/flutter (26103): #5 Future._propagateToListeners (dart:async/future_impl.dart:709:32)
E/flutter (26103): #6 Future._completeWithValue (dart:async/future_impl.dart:524:5)
E/flutter (26103): #7 Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:554:7)
E/flutter (26103): #8 _rootRun (dart:async/zone.dart:1126:13)
E/flutter (26103): #9 _CustomZone.run (dart:async/zone.dart:1023:19)
E/flutter (26103): #10 _CustomZone.runGuarded (dart:async/zone.dart:925:7)
E/flutter (26103): #11 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
E/flutter (26103): #12 _microtaskLoop (dart:async/schedule_microtask.dart:43:21)
E/flutter (26103): #13 _startMicrotaskLoop (dart:async/schedule_microtask.dart:52:5)
E/flutter (26103):
The problem is that you're trying to access a dataset by using its absolute path, but the path you used is wrong since it's altered during runtime. Unfortunately, Flutter doesn't provide us with the correct absolute path for its assets in runtime.
There is a solution of the issue in ml_algo 15.6.3 and ml_dataframe 0.4.0: you need to read your dataset asset using rootBundle.loadString and feed the resulting string to a DataFrame.fromRawCsv(...) constructor:
import 'package:flutter/services.dart' show rootBundle;
import 'package:ml_dataframe/ml_dataframe.dart';
final rawCsvContent = await rootBundle.loadString('assets/res/wheat.csv');
final samples = DataFrame.fromRawCsv(rawCsvContent);