How to get user mobile number in flutter android and iOS - flutter

How to get user mobile number in flutter android and iOS.
final String mobileNumber = await MobileNumber.mobileNumber;

simple complete example
flutter main.dart file
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mobile_number/mobile_number.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _mobileNumber = '';
List<SimCard> _simCard = <SimCard>[];
#override
void initState() {
super.initState();
MobileNumber.listenPhonePermission((isPermissionGranted) {
if (isPermissionGranted) {
initMobileNumberState();
} else {}
});
initMobileNumberState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initMobileNumberState() async {
if (!await MobileNumber.hasPhonePermission) {
await MobileNumber.requestPhonePermission;
return;
}
String mobileNumber = '';
// Platform messages may fail, so we use a try/catch PlatformException.
try {
mobileNumber = (await MobileNumber.mobileNumber)!;
_simCard = (await MobileNumber.getSimCards)!;
} on PlatformException catch (e) {
debugPrint("Failed to get mobile number because of '${e.message}'");
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_mobileNumber = mobileNumber;
});
}
Widget fillCards() {
List<Widget> widgets = _simCard
.map((SimCard sim) => Text(
'Sim Card Number: (${sim.countryPhonePrefix}) - ${sim.number}\nCarrier Name: ${sim.carrierName}\nCountry Iso: ${sim.countryIso}\nDisplay Name: ${sim.displayName}\nSim Slot Index: ${sim.slotIndex}\n\n'))
.toList();
return Column(children: widgets);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
children: <Widget>[
Text('Running on: $_mobileNumber\n'),
fillCards()
],
),
),
),
);
}
}
pubspec.yaml file
name: flutter_mobilenumber
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.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
mobile_number: ^1.0.4
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.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:
# 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
android app build.gradle file
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion 30
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.flutter_mobilenumber"
minSdkVersion 17
targetSdkVersion 30
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
}
flutter {
source '../..'
}
here result :
[![enter image description here][1]][1]
details in link

Related

Flutter & Sqflite: MissingPluginException(No implementation found for method getDatabasesPath on channel com.tekartik.sqflite)

I'm currently trying to create a DB in my flutter app.
In a database.dart file I have:
void CreateBD() async{
WidgetsFlutterBinding.ensureInitialized();
final database = openDatabase(
//on choisi le path de la bd
join(await getDatabasesPath(), 'hyrule_database.db'),
//initialisation des tables
onCreate: (db, version) {
// Run the CREATE TABLE statement on the database.
return db.execute(
'CREATE TABLE foods(id INTEGER PRIMARY KEY, name TEXT,image TEXT, description TEXT, cookingEffect TEXT, category TEXT, commonLocations list<TEXT>, heartsRecovered INTEGER);'
'CREATE TABLE nonfoods(id INTEGER PRIMARY KEY, name TEXT,image TEXT, description TEXT,category TEXT, commonLocations list<TEXT>, drops list<TEXT>);'
'CREATE TABLE equipments(id INTEGER PRIMARY KEY, name TEXT,image TEXT, description TEXT, attack INTEGER, category TEXT, commonLocations list<TEXT>, defense INTEGER);'
'CREATE TABLE materials(id INTEGER PRIMARY KEY, name TEXT,image TEXT, description TEXT, cookingEffect TEXT, category TEXT, commonLocations list<TEXT>, heartsRecovered INTEGER);'
'CREATE TABLE monsters(id INTEGER PRIMARY KEY, name TEXT,image TEXT, description TEXT, category TEXT, commonLocations list<TEXT>, drops list<TEXT>);'
'CREATE TABLE treasure(id INTEGER PRIMARY KEY, name TEXT,image TEXT, description TEXT, category TEXT, commonLocations list<TEXT>, drops list<TEXT>)',
);
},
//version afin de laisser la posibilité de upgrade et downgrade
version: 1,
);
}
Future<Database> connectBD()async{
final database = openDatabase(
join(await getDatabasesPath(), 'hyrule_database.db'),
);
return database;
}
And for every table i've create CRUD functions , here an exemple with food table:
// Insertion
Future<void> insertFood(Food food) async {
final db = await connectBD();
await db.insert(
'foods',
food.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
//récupération
Future<List<Food>> foods() async {
final db = await connectBD();
final List<Map<String, dynamic>> maps = await db.query('foods');
return List.generate(maps.length, (i) {
return Food(
id: maps[i]['id'],
name: maps[i]['name'],
image: maps[i]['image'],
heartsRecovered: maps[i]['hearts_recovered'],
description: maps[i]['description'],
cookingEffect: maps[i]['cooking_effect'],
commonLocations: maps[i]['common_locations'],
category: maps[i]['category'],
);
});
}
//update
Future<void> updateFood(Food food) async {
final db = await connectBD();
await db.update(
'foods',
food.toMap(),
where: 'id = ?',
whereArgs: [food.id],
);
}
//delete
Future<void> deleteFood(int id) async {
final db = await connectBD();
await db.delete(
'foods',
where: 'id = ?',
whereArgs: [id],
);
}
Then I try to execute the creation, and I only end up with the error :
Error: MissingPluginException(No implementation found for method getDatabasesPath on channel com.tekartik.sqflite)
the file I use to execute look like :
import 'package:flutter/material.dart';
import 'package:projet_flutter/Utils/hyrule_bd.dart';
import 'package:projet_flutter/Utils/fill_bd.dart';
import 'package:projet_flutter/models/food_model.dart';
import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
class TestApp extends StatefulWidget {
#override
State<StatefulWidget> createState() => _TestState();
}
class _TestState extends State<TestApp> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
CreateBD();
//remplirBD();
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: const Text('Fetch Data Example'),
),
body: Center(
child:FutureBuilder<List<Food>>(
future: foods(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text('${snapshot.data}');
} else if (snapshot.hasError) {
print("erreur test: ${snapshot.error}");
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
));
}
}
My pubspec.yaml :
name: projet_flutter
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter 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.14.0 <3.0.0"
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
http: 0.13.4
sqflite: any
path: any
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^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
# 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
I'm currently learning Flutter dev, so i was wondering what went wrong?
Sqflite doesn't support web (https://github.com/tekartik/sqflite), which was what I was trying to build.
Sometimes this happens after adding new dependencies into pubspec file.
Try running the following command from the project terminal:
flutter clean
And then re-run the project.

Flutter build not running with geocoding and location package

I tried to run a simple project but i gives me errors:
Launching lib\main.dart on ASUS Z01QD in debug mode...
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:processDebugResources'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
> Failed to transform play-services-base-16.0.1.aar (com.google.android.gms:play-services-base:16.0.1) to match attributes {artifactType=android-compiled-dependencies-resources, org.gradle.status=release}.
> Execution failed for AarResourcesCompilerTransform: C:\Users\win\.gradle\caches\transforms-2\files-2.1\f260781842f212c36494d469961b4620\jetified-play-services-base-16.0.1.
> AAPT2 aapt2-4.1.0-6503028-windows Daemon #0: Unexpected error during compile 'C:\Users\win\.gradle\caches\transforms-2\files-2.1\f260781842f212c36494d469961b4620\jetified-play-services-base-16.0.1\res\drawable-xhdpi-v4\common_google_signin_btn_text_dark_normal_background.9.png', attempting to stop daemon.
This should not happen under normal circumstances, please file an issue if it does.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 1m 58s
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)
main.dart ->
import 'package:flutter/material.dart';
import 'package:locationflutter/splashscreen.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(
// 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: SplashScreen(),
);
}
}
splashscreen.dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:location/location.dart';
import 'package:locationflutter/location_service.dart';
import 'package:locationflutter/mainscreen.dart';
class SplashScreen extends StatefulWidget {
const SplashScreen({Key? key}) : super(key: key);
#override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
#override
void initState() {
super.initState();
locationService();
}
Future<void> locationService() async {
Location location = new Location();
bool _serviceEnabled;
PermissionStatus _permissionLocation;
LocationData _locData;
_serviceEnabled = await location.serviceEnabled();
if(!_serviceEnabled) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
return;
}
}
_permissionLocation = await location.hasPermission();
if(_permissionLocation == PermissionStatus.denied) {
_permissionLocation = await location.requestPermission();
if(_permissionLocation != PermissionStatus.granted) {
return;
}
}
_locData = await location.getLocation();
setState(() {
UserLocation.lat = _locData.latitude!;
UserLocation.long = _locData.longitude!;
});
Timer(Duration(milliseconds: 500), () {
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) => MainScreen()));
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text("WELCOME"),
),
);
}
}
mainscreen.dart
import 'package:flutter/material.dart';
import 'package:geocoding/geocoding.dart';
import 'package:locationflutter/location_service.dart';
class MainScreen extends StatefulWidget {
const MainScreen({Key? key}) : super(key: key);
#override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
String country = '';
String name = '';
String street = '';
String postalCode = '';
#override
void initState() {
super.initState();
getLocation();
}
Future<void> getLocation() async {
List<Placemark> placemark = await placemarkFromCoordinates(UserLocation.lat, UserLocation.long);
print(placemark[0].country);
print(placemark[0].name);
print(placemark[0].street);
print(placemark[0].postalCode);
setState(() {
country = placemark[0].country!;
name = placemark[0].name!;
street = placemark[0].street!;
postalCode = placemark[0].postalCode!;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Lat : " + "${UserLocation.lat}"),
Text("Long : " + "${UserLocation.long}"),
Text("Country : " + "$country"),
Text("Name : " + "$name"),
Text("Street : " + "$street"),
Text("PostalCode : " + "$postalCode"),
],
),
),
);
}
}
location_service.dart
class UserLocation {
static double lat = 0;
static double long = 0;
}
pubspec.yaml
name: locationflutter
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:
flutter:
sdk: flutter
location: ^4.3.0
geocoding: ^2.0.1
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.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:
# 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
flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.8.1, on Microsoft Windows [Version 10.0.19043.1415], locale
en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
[√] Chrome - develop for the web
[√] Visual Studio - develop for Windows (Visual Studio Community 2022 17.0.4)
[√] Android Studio (version 2020.3)
[√] VS Code (version 1.63.2)
[√] Connected device (4 available)
! Device 127.0.0.1:5555 is offline.
• No issues found!
I don't know what am I doing wrong.
I Fixed this issue by:
In gradle-wrapper.properties I defined Gradle version 6.1.1
by adding at the last of the file
distributionUrl=https://services.gradle.org/distributions/gradle-6.1.1-all.zip
And in the project-level build.gradle I set version 4.0.2
by adding
classpath 'com.android.tools.build:gradle:4.0.2'
reference: solution

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 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

TypeAdapterGenerator:- Missing concrete implementation of 'getter TypeAdapter.typeId Try implementing the missing method

I'm learning Hive db in Flutter. When I use Flutter packages pub run build_runner build command its generate the data.g.dart file in it its has an error.
The full error:
{
"resource": "/E:/Mywork/AndroidApps/hive_todo/lib/data.g.dart",
"owner": "dart",
"code": "non_abstract_class_inherits_abstract_member",
"severity": 8,
"message": "Missing concrete implementation of 'getter TypeAdapter.typeId'.\nTry implementing the missing method, or make the class abstract.",
"source": "dart",
"startLineNumber": 9,
"startColumn": 7,
"endLineNumber": 9,
"endColumn": 18,
"tags": []
}
the data.g.dart code:
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'data.dart';
// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************
class dataAdapter extends TypeAdapter<data> {
#override
data read(BinaryReader reader) {
var numOfFields = reader.readByte();
var fields = <int, dynamic>{
for (var i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return data(
todo: fields[0] as String,
val: fields[1] as int,
);
}
#override
void write(BinaryWriter writer, data obj) {
writer
..writeByte(2)
..writeByte(0)
..write(obj.todo)
..writeByte(1)
..write(obj.val);
}
}
The data.dart code:
import 'package:hive/hive.dart';
part 'data.g.dart';
#HiveType()
class data {
#HiveField(0)
final String todo;
#HiveField(1)
final int val;
data({this.todo,this.val});
}
The main method code:
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart' as path_provider;
import 'data.dart';
import 'todo_page.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final appDocumentDir = await path_provider.getApplicationDocumentsDirectory();
Hive.init(appDocumentDir.path);
Hive.registerAdapter(dataAdapter());
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Hive Todo',
home: FutureBuilder(
future: Hive.openBox('data'),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError)
return Text(snapshot.error.toString());
else
return Todo_Page();
}
// Although opening a Box takes a very short time,
// we still need to return something before the Future completes.
else
return Scaffold(backgroundColor: Colors.red);
},
),
);
}
#override
void dispose() {
Hive.close();
super.dispose();
}
}
If I do quick fix, then the error is gone, but when I register the adapter in the main method
Hive.registerAdapter(dataAdapter(), 0);
it only gives error because of typeId. When I remove it,
Hive.registerAdapter(dataAdapter());
then it doesn't gives error. But I want the typeId in it.
My pubspec.yaml:
name: hive_todo
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.5.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
hive: ^1.2.0
hive_flutter: ^0.2.1
# For OS-specific directory paths
path_provider: ^1.3.1
# 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
hive_generator: ^0.5.1
build_runner:
# 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
I had a similar issue and found this solution on the hivedb/hive GitHub page:
In pubspec.yaml, use hive: 1.2.0 without the carat symbol in your dependencies.