Initializing Flutter-Fire flutter Web - flutter

I can't figure out where is the problem output gives me Connection failed Here is the screen out put image. I'm trying to Initializing FlutterFire (Flutter Web). I'm doing it with the proper guidelines of official documentation https://firebase.flutter.dev/docs/overview#initializing-flutterfire.But can't figure out where I'm doing the mistake.
When I remove or comment on this part of codes it run.
// Check for errors
if (snapshot.hasError) {
return Center(
child: Text('Connection failed'),
);
}
Here is my main.dart
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Phatafut Admin Panel',
theme: ThemeData(
primaryColor: Colors.greenAccent,
),
home: MyHomePage(title: 'Phatafut Admin Panel'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final Future<FirebaseApp> _initialization = Firebase.initializeApp();
final _formKey = GlobalKey<FormState>();
// FirebaseServices _services = FirebaseServices();
var _usernameTextController = TextEditingController();
var _passwordTextController = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
// // key:_formKey,
// appBar: AppBar(
// elevation: 0.0,
// title: Text('Grocery Store Admin Dashboard',style: TextStyle(color: Colors.white ),),
// centerTitle: true,
body: FutureBuilder(
// Initialize FlutterFire:
future: _initialization,
builder: (context, snapshot) {
// Check for errors
if (snapshot.hasError) {
return Center(
child: Text('Connection failed'),
);
}
// Once complete, show your application
if (snapshot.connectionState == ConnectionState.done) {
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Color(0xFF84c225), Colors.white],
stops: [1.0, 1.0],
begin: Alignment.topCenter,
end: Alignment(0.0, 0.0)),
),
child: Center(
child: Container(
width: 350,
height: 400,
child: Card(
elevation: 6,
shape: Border.all(color: Colors.green, width: 2),
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Container(
child: Column(
children: [
Image.asset('images/logo.png'),
Text(
'Grocery App ADMIN',
style: TextStyle(
fontWeight: FontWeight.w900,
fontSize: 20),
),
SizedBox(
height: 20,
),
TextFormField(
controller: _usernameTextController,
validator: (value) {
if (value.isEmpty) {
return 'Enter UserName';
}
return null;
},
decoration: InputDecoration(
labelText: 'UserName',
prefixIcon: Icon(Icons.person),
contentPadding: EdgeInsets.only(
left: 20, right: 20),
border: OutlineInputBorder(),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context)
.primaryColor,
width: 2))),
),
SizedBox(
height: 20,
),
TextFormField(
controller: _passwordTextController,
validator: (value) {
if (value.isEmpty) {
return 'Enter Password';
}
if (value.length < 6) {
return 'Minimum 6 character required';
}
return null;
},
obscureText: false,
decoration: InputDecoration(
labelText: 'Minimum 6 Characters',
prefixIcon: Icon(Icons.vpn_key_sharp),
hintText: 'Password',
contentPadding: EdgeInsets.only(
left: 20, right: 20),
border: OutlineInputBorder(),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Theme.of(context)
.primaryColor,
width: 2))),
),
],
),
),
Row(
children: [
Expanded(
child: TextButton(
style: TextButton.styleFrom(
primary: Colors.white,
backgroundColor: Colors.green,
onSurface: Colors.grey,
),
onPressed: () async {
if (_formKey.currentState.validate()) {
// _login(username: _usernameTextController.text, password: _passwordTextController.text);
}
},
child: Text(
'Login',
style: TextStyle(color: Colors.white),
)),
),
],
)
],
),
),
),
),
),
),
);
}
// Otherwise, show something whilst waiting for initialization to complete
return Center(
child: CircularProgressIndicator(),
);
},
),
);
}
}
here is my index.html
<!DOCTYPE html>
<html>
<head>
<base href="/">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A new Flutter project.">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="admin_panel">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<title>admin_panel</title>
<link rel="manifest" href="manifest.json">
</head>
<body>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-analytics.js";
const firebaseConfig = {
apiKey: "********",
authDomain: "********",
projectId: "*********",
storageBucket: "************",
messagingSenderId: "******",
appId: "**************",
measurementId: "******"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
</script>
<script>
var serviceWorkerVersion = null;
var scriptLoaded = false;
function loadMainDartJs() {
if (scriptLoaded) {
return;
}
scriptLoaded = true;
var scriptTag = document.createElement('script');
scriptTag.src = 'main.dart.js';
scriptTag.type = 'application/javascript';
document.body.append(scriptTag);
}
if ('serviceWorker' in navigator) {
// Service workers are supported. Use them.
window.addEventListener('load', function () {
// Wait for registration to finish before dropping the <script> tag.
// Otherwise, the browser will load the script multiple times,
// potentially different versions.
var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
navigator.serviceWorker.register(serviceWorkerUrl)
.then((reg) => {
function waitForActivation(serviceWorker) {
serviceWorker.addEventListener('statechange', () => {
if (serviceWorker.state == 'activated') {
console.log('Installed new service worker.');
loadMainDartJs();
}
});
}
if (!reg.active && (reg.installing || reg.waiting)) {
// No active web worker and we have installed or are installing
// one for the first time. Simply wait for it to activate.
waitForActivation(reg.installing ?? reg.waiting);
} else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
// When the app updates the serviceWorkerVersion changes, so we
// need to ask the service worker to update.
console.log('New service worker available.');
reg.update();
waitForActivation(reg.installing);
} else {
// Existing service worker is still good.
console.log('Loading app from service worker.');
loadMainDartJs();
}
});
// If service worker doesn't succeed in a reasonable amount of time,
// fallback to plaint <script> tag.
setTimeout(() => {
if (!scriptLoaded) {
console.warn(
'Failed to load app from service worker. Falling back to plain <script> tag.',
);
loadMainDartJs();
}
}, 4000);
});
} else {
// Service workers not supported. Just drop the <script> tag.
loadMainDartJs();
}
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>
Here is my pubspec.yaml
name: admin_panel
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.10.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.2
firebase_core: ^1.5.0
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
Thanks in advance

Try adding these lines under <body> in your index.html, the documentation suggests using version 8.6.1 this way:
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-analytics.js"></script>
And don't forget running flutter build web before deploying.

Related

Import Packages are not working/red underline. (Flutter) (Dart)

trying to use some packages and for some reason they aren't working/I am getting a red underline on each of them. Any answer on why this could be happening? as well as if there is a solution that could be provided, that would be much appreciated! I am new to this all and still learning!
For this set of code, the ones that are underlined would be
the logger package, dio package, and units package.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:simple_gradient_text/simple_gradient_text.dart';
import '../utils/dreams_utils.dart';
class ResourcesPage extends StatefulWidget{
#override
_ResourcesPageState createState() => _ResourcesPageState();
}
class _ResourcesPageState extends State<ResourcesPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: GradientText('Sleep Resources',
style: TextStyle(fontSize: 30.0,),
colors: [colorStyle("gradient1"), colorStyle("gradient2"),
colorStyle("gradient3"), colorStyle("gradient2"),
colorStyle("gradient1")]
),
backgroundColor: colorStyle("appHeader"),
),
backgroundColor: colorStyle("appBackground"),
resizeToAvoidBottomInset: true,
body: Center(
child: ListView(
shrinkWrap: true,
children: <Widget>[
new Container(
margin: EdgeInsets.all(30.0),
child: new Card(
color: Colors.transparent,
elevation: 400.0,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Image.asset("assets/images/SleepF.jpeg",
height: 400,
width: 400,
fit: BoxFit.fill,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new InkWell(
child: new Text('Sleep Foundation',
style: TextStyle(
color: colorStyle("main"),
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
onTap: () => launch('https://www.sleepfoundation.org/sleep-hygiene/healthy-sleep-tips')
),
),
Text('We work hard to bring you the most accurate and up-to-date information about different sleep health topics. Rest assured every Sleep Foundation guide is carefully vetted and fact-checked prior to publication.',
style: TextStyle(
color: colorStyle("main"),
fontSize: 15.0),
),
],
),
),
),
new Container(
margin: EdgeInsets.all(30.0),
child: new Card(
color: Colors.transparent,
elevation: 400.0,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Image.asset("assets/images/IFFA.png",
height: 400,
width: 400,
fit: BoxFit.fill,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new InkWell(
child: new Text('International Functional Foods Association',
style: TextStyle(
color: colorStyle("main"),
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
onTap: () => launch('https://iffassociation.org/learn/how-functional-foods-may-improve-sleep-and-immune-health?gclid=Cj0KCQiAys2MBhDOARIsAFf1D1eHFvfuovsyweVETX8I5DOztdqM_QmIN_1DjOtkDNOiKlHIn9RN1bAaAhsLEALw_wcB')
),
),
Text('We exist to ensure everyone, everywhere has an equal chance to take control of their own health and wellness. Functional foods are an important component of healthy, nutritious diets. A diet rich in functional foods promotes a healthy body, as well as a healthy mind.',
style: TextStyle(
color: colorStyle("main"),
fontSize: 15.0),
),
],
),
),
),
new Container(
margin: EdgeInsets.all(30.0),
child: new Card(
color: Colors.transparent,
elevation: 400.0,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Image.asset("assets/images/Kaiser.png",
height: 400,
width: 400,
fit: BoxFit.fill,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new InkWell(
child: new Text('Kaiser Permanente',
style: TextStyle(
color: colorStyle("main"),
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
onTap: () => launch('https://healthengagement.kaiserpermanente.org/wellness-topics/sleep/')
),
),
Text('We help people reach their health goals, by listening, supporting and guiding, so they can live their best lives.',
style: TextStyle(
color: colorStyle("main"),
fontSize: 15.0),
),
],
),
),
),
new Container(
margin: EdgeInsets.all(30.0),
child: new Card(
color: Colors.transparent,
elevation: 400.0,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Image.asset("assets/images/JHM.jpeg",
height: 400,
width: 400,
fit: BoxFit.fill,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new InkWell(
child: new Text('John Hopkins Medical',
style: TextStyle(
color: colorStyle("main"),
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
onTap: () => launch('https://www.hopkinsmedicine.org/health/wellness-and-prevention/sleep')
),
),
Text('At Johns Hopkins Medicine, your health and safety are our very highest priorities. We are ready to care for you and your family in our hospitals, surgery centers, and through in-person clinic and online video visits. Learn how we are keeping you safe and protected so that you can get the care you need.',
style: TextStyle(
color: colorStyle("main"),
fontSize: 15.0),
),
],
),
),
),
new Container(
margin: EdgeInsets.all(30.0),
child: new Card(
color: Colors.transparent,
elevation: 400.0,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Image.asset("assets/images/BMI.png",
height: 400,
width: 400,
fit: BoxFit.fill,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new InkWell(
child: new Text('Beautiful Mind International',
style: TextStyle(
color: colorStyle("main"),
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
onTap: () => launch('https://beauty-mind.org/sleep-guru/?gclid=Cj0KCQiAys2MBhDOARIsAFf1D1czPDb4ROkA_dhket7YAZrPB9H7AK4OqEclcbTaiU_OgDq9odhQ7x8aAhz7EALw_wcB')
),
),
Text('Beautiful Mind International project aims to educate people what is mental health, its issues, and ways to overcome them.',
style: TextStyle(
color: colorStyle("main"),
fontSize: 15.0),
),
],
),
),
),
new Container(
margin: EdgeInsets.all(30.0),
child: new Card(
color: Colors.transparent,
elevation: 400.0,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Image.asset("assets/images/CDC.png",
height: 400,
width: 400,
fit: BoxFit.fill,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new InkWell(
child: new Text('Centers for Disease Control and Prevention',
style: TextStyle(
color: colorStyle("main"),
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
onTap: () => launch('https://www.cdc.gov/sleep/index.html')
),
),
Text('The Centers for Disease Control and Prevention is the national public health agency of the United States.',
style: TextStyle(
color: colorStyle("main"),
fontSize: 15.0),
),
],
),
),
),
new Container(
margin: EdgeInsets.all(30.0),
child: new Card(
color: Colors.transparent,
elevation: 400.0,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Image.asset("assets/images/sleepnum1.jpeg",
height: 400,
width: 400,
fit: BoxFit.fill,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new InkWell(
child: new Text('Sleep Number',
style: TextStyle(
color: colorStyle("main"),
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
onTap: () => launch('https://www.sleepnumber.com/categories/beds-on-sale?acid=psnonbrand&ascid=Google%2BNational-_-google-_-NB_Number_Bed-_-Number_Bed_Exact-_-516451220073-_-b-_-kwd-846217698-_-mediacode-_-Beds-_-1&key=number%20beds&s_kwcid=AL!6200!3!516451220073!b!!g!!number%20beds&k_clickid=go_cmp-193921164_adg-14393203044_ad-516451220073_kwd-846217698_dev-c_ext-_prd-&gclid=Cj0KCQiAys2MBhDOARIsAFf1D1d4C7oDgf9l_gikrEEVbK2Y7EpcHjg8AvPAmFGam3Qgjgc-XknDyYYaAtNfEALw_wcB')
),
),
Text('Sleep Number is an American manufacturer that makes the Sleep Number and Comfortaire beds, as well as foundations and bedding accessories. The company is based in Minneapolis, Minnesota. In addition to its Minnesota headquarters, Sleep Number has manufacturing and distribution facilities in South Carolina and Utah.',
style: TextStyle(
color: colorStyle("main"),
fontSize: 15.0),
),
],
),
),
),
new Container(
margin: EdgeInsets.all(30.0),
child: new Card(
color: Colors.transparent,
elevation: 400.0,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Image.asset("assets/images/sunset.jpeg",
height: 400,
width: 400,
fit: BoxFit.fill,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: new InkWell(
child: new Text('UMN Duluth Health Services',
style: TextStyle(
color: colorStyle("main"),
fontWeight: FontWeight.bold,
fontSize: 20.0),
),
onTap: () => launch('https://health-services.d.umn.edu/health-education/sleep-education-initiatives')
),
),
Text('Health Education Staff, Interns, and our previous student health advisory committee developed and administered an informal needs assessment to measure student reported barriers to sleep and methods for sleep support that students would use. We learned a lot and are putting that information into practice with a series of initiatives on campus.',
style: TextStyle(
color: colorStyle("main"),
fontSize: 15.0),
),
],
),
),
),
],
),
),
);
}
}
For this set of code, the ones that are underlined in red would be the
units package, dio package, and logger package.
import 'package:flutter/material.dart';
import 'package:units/dreams/utils/dreams_constant.dart';
import 'dart:math';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:dio/dio.dart';
import "package:units/api.dart";
List<dynamic> calculator(double hour, double minute, double sleepHour, double
sleepMinute,
UnitType uniType, UnitType unitTypeTime) {
List result = new List.filled(3, null, growable: false);
double tempHour = 0.0;
double tempMinute = 0.00;
if(uniType == UnitType.BED) {
tempHour = hour + sleepHour;
tempMinute = minute + sleepMinute;
if (tempMinute >= 60) {
tempMinute -= 60;
tempHour += 1;
}
}
if (uniType == UnitType.WAKE) {
tempHour = hour - sleepHour;
tempMinute = minute - sleepMinute;
if(tempMinute < 0){
tempMinute += 60.00;
tempHour -= 1;
}
}
if(tempHour > 12 || tempHour < 0) {
switch(unitTypeTime) {
case UnitType.AM: { unitTypeTime = UnitType.PM; }
break;
case UnitType.PM: { unitTypeTime = UnitType.AM; }
break;
default: {}
break;
}
tempHour %= 12;
}
if(tempHour ==0){
tempHour = 12;
}
//result = tempHour + (tempMinute/100);
result[0] = (tempHour + (tempMinute/100));
result[1] = unitTypeTime;
result[2] = uniType;
return result;
}
bool isEmptyString(String string){
return string == null || string.length == 0;
}
Future<int> loadValue() async{
SharedPreferences preferences = await SharedPreferences.getInstance();
int? data = preferences.getInt('data');
if( data != null ) {
return data;
} else {
return 0;
}
}
void saveValue(int value) async{
SharedPreferences preferences = await SharedPreferences.getInstance();
preferences.setInt('data', value);
}
void setThemeKey(int color) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setInt('theme', color);
}
Future<int?> getThemeKey() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final color = prefs.getInt('theme');
return color;
}
void setTheme(int theme){
switch(theme) {
case 1: { defaultTheme(); }
break;
case 2: { monochromeTheme(); }
break;
case 3: { pinkTheme(); }
break;
case 4: { sherbetTheme(); }
break;
case 5: { thunderTheme(); }
break;
case 6: { redTheme(); }
break;
case 7: { transTheme(); }
break;
case 8: { enbyTheme(); }
break;
default: { defaultTheme(); }
break;
}
}
Color mains = Colors.white60;
Color accent = Colors.cyan;
Color widgets = Colors.blueGrey.shade700;
Color gradient1 = Colors.cyan.shade900;
Color gradient2 = Colors.cyan.shade700;
Color gradient3 = Colors.cyan.shade500;
Color appHeader = Colors.blueGrey.shade900;
Color appBackground = Colors.blueGrey.shade800;
Future<int> defaultTheme() async {
mains = Colors.white60;
accent = Colors.cyan;
widgets = Colors.blueGrey.shade700;
gradient1 = Colors.cyan.shade900;
gradient2 = Colors.cyan.shade700;
gradient3 = Colors.cyan.shade500;
appHeader = Colors.blueGrey.shade900;
appBackground = Colors.blueGrey.shade800;
return 1;
}
Future<int> monochromeTheme() async {
mains = Colors.black;
accent = Colors.grey.shade700;
widgets = Colors.grey;
gradient1 = Colors.grey.shade700;
gradient2 = Colors.grey.shade500;
gradient3 = Colors.grey.shade300;
appHeader = Colors.grey.shade900;
appBackground = Colors.grey.shade800;
return 1;
}
Future<int> pinkTheme() async {
mains = Colors.pink.shade500;
accent = Colors.pink;
widgets = Colors.pink.shade200;
gradient1 = Colors.pinkAccent.shade700;
gradient2 = Colors.pinkAccent.shade400;
gradient3 = Colors.pinkAccent;
appHeader = Colors.pink.shade900;
appBackground = Colors.pink.shade800;
return 1;
}
Future<int> sherbetTheme() async {
mains = Colors.deepOrange;
accent = Colors.green.shade300;
widgets = Colors.yellow.shade100;
gradient1 = Colors.purpleAccent.shade400;
gradient2 = Colors.orangeAccent.shade100;
gradient3 = Colors.cyanAccent;
appHeader = Colors.pink.shade300;
appBackground = Colors.pink.shade100;
return 1;
}
Future<int> thunderTheme() async {
mains = Colors.yellow;
accent = Colors.yellowAccent;
widgets = Colors.grey.shade700;
gradient1 = Colors.cyan.shade500;
gradient2 = Colors.yellow.shade700;
gradient3 = Colors.yellow.shade200;
appHeader = Colors.grey.shade900;
appBackground = Colors.grey.shade800;
return 1;
}
Future<int> redTheme() async {
mains = Colors.red.shade900;
accent = Colors.red.shade900;
widgets = Colors.white70;
gradient1 = Colors.red.shade900;
gradient2 = Colors.red.shade700;
gradient3 = Colors.red.shade500;
appHeader = Colors.grey.shade500;
appBackground = Colors.grey.shade200;
return 1;
}
Future<int> transTheme() async {
mains = Colors.blue;
accent = Colors.pink;
widgets = Colors.white70;
gradient1 = Colors.lightBlue.shade200;
gradient2 = Colors.pinkAccent.shade100;
gradient3 = Colors.white;
appHeader = Colors.blue.shade800;
appBackground = Colors.pinkAccent.shade100;
return 1;
}
Future<int> enbyTheme() async {
mains = Colors.black;
accent = Colors.yellow.shade700;
widgets = Colors.white;
gradient1 = Colors.black;
gradient2 = Colors.yellow;
gradient3 = Colors.white;
appHeader = Colors.purple;
appBackground = Colors.purple.shade200;
return 1;
}
Color colorStyle(String color){
switch(color){
case "main":
return mains;
case "accent":
return accent;
case "widgets":
return widgets;
case "gradient1":
return gradient1;
case "gradient2":
return gradient2;
case "gradient3":
return gradient3;
case "appHeader":
return appHeader;
case "appBackground":
return appBackground;
default:
return Colors.purpleAccent;
}
}
This is the error code that I am getting
Invalid depfile: C:\Users\Mahjur - Coding\Desktop\SweetDreams-X.2.dart_tool\flutter_build\e98d11342ddd14555bbca12c2fd83e4a\kernel_snapshot.d
Invalid depfile: C:\Users\Mahjur - Coding\Desktop\SweetDreams-X.2.dart_tool\flutter_build\e98d11342ddd14555bbca12c2fd83e4a\kernel_snapshot.d
Error: Couldn't resolve the package 'logger' in 'package:logger/logger.dart'.
Error: Couldn't resolve the package 'dio' in 'package:dio/dio.dart'.
lib/dreams/utils/dreams_utils.dart:7:8: Error: Not found: 'package:logger/logger.dart'
import 'package:logger/logger.dart';
^
lib/dreams/utils/dreams_utils.dart:8:8: Error: Not found: 'package:dio/dio.dart'
import 'package:dio/dio.dart';
^
lib/dreams/utils/dreams_utils.dart:9:8: Error: Error when reading 'lib/api.dart': The system cannot find the file specified.
import "package:units/api.dart";
^
Here is my pubspec.yaml
name: units
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
#
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.0.6
# The following adds the Cupertino Icons font to your
application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
firebase_core: ^1.13.1
firebase_auth: ^3.3.11
cloud_firestore: ^3.1.10
modal_progress_hud: ^0.1.3
firebase_messaging: ^11.2.11
firebase_analytics: ^9.1.2
flutter_launcher_icons: ^0.9.2
flutter_local_notifications: ^9.4.0
#flutter_native_timezone: ^1.1.0
rxdart: ^0.27.1
#awesome_notifications: ^0.6.21
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:
- lib/assests/images/
- android/app/src/main/res/drawable/
# -lib/dreams/images/app_icon.png
# 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
run in the command line
flutter clean
then
flutter pub get
if that doesn't help, shut down and restart android studio and the file.
if that doesn't help delete the dependency from the pubspec.yaml run pub get, then re-add the dependency and run pub get, sometimes you have to hit flutter over the head with a hammer.
double check the packages you are having issues with are actually added in the pubspec.yaml and ensure there is not a # infront of them that comments them out

Failed to run model, -67108857, java.lang.NegativeArrayS izeException: -67108857

Has anyone solved this problem while using tflite package in flutter every model i used i get that issue of arrays?
Unhandled Exception: PlatformException(Failed to run model, -67108857, java.lang.NegativeArrayS
izeException: -67108857
How can i solve it.
Here is the basic code i was trying to run but landed into an error.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:tflite/tflite.dart';
import 'package:image_picker/image_picker.dart';
import 'home.dart';
//import 'package:image/image.dart' as img;
void main() => runApp(MyApp());
const String ssd = "SSD MobileNet";
const String yolo = "Tiny YOLOv2";
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Object Detection App',
home: StaticImage(),
);
}
}
class StaticImage extends StatefulWidget {
#override
_StaticImageState createState() => _StaticImageState();
}
class _StaticImageState extends State<StaticImage> {
File _image;
List _recognitions;
bool _busy;
double _imageWidth, _imageHeight;
final picker = ImagePicker();
// this function loads the model
loadTfModel() async {
await Tflite.loadModel(
model: "assets/tflite/model_unquant.tflite",
labels: "assets/tflite/label.txt",
);
}
// this function detects the objects on the image
detectObject(File image) async {
var recognitions = await Tflite.detectObjectOnImage(
path: image.path, // required
model: "SSDMobileNet",
imageMean: 127.5,
imageStd: 127.5,
threshold: 0.4, // defaults to 0.1
numResultsPerClass: 10,// defaults to 5
asynch: true // defaults to true
);
FileImage(image)
.resolve(ImageConfiguration())
.addListener((ImageStreamListener((ImageInfo info, bool _) {
setState(() {
_imageWidth = info.image.width.toDouble();
_imageHeight = info.image.height.toDouble();
});
})));
setState(() {
_recognitions = recognitions;
});
}
#override
void initState() {
super.initState();
_busy = true;
loadTfModel().then((val) {{
setState(() {
_busy = false;
});
}});
}
// display the bounding boxes over the detected objects
List<Widget> renderBoxes(Size screen) {
if (_recognitions == null) return [];
if (_imageWidth == null || _imageHeight == null) return [];
double factorX = screen.width;
double factorY = _imageHeight / _imageHeight * screen.width;
Color blue = Colors.blue;
return _recognitions.map((re) {
return Container(
child: Positioned(
left: re["rect"]["x"] * factorX,
top: re["rect"]["y"] * factorY,
width: re["rect"]["w"] * factorX,
height: re["rect"]["h"] * factorY,
child: ((re["confidenceInClass"] > 0.50))? Container(
decoration: BoxDecoration(
border: Border.all(
color: blue,
width: 3,
)
),
child: Text(
"${re["detectedClass"]} ${(re["confidenceInClass"] * 100).toStringAsFixed(0)}%",
style: TextStyle(
background: Paint()..color = blue,
color: Colors.white,
fontSize: 15,
),
),
) : Container()
),
);
}).toList();
}
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
List<Widget> stackChildren = [];
stackChildren.add(
Positioned(
// using ternary operator
child: _image == null ?
Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Please Select an Image"),
],
),
)
: // if not null then
Container(
child:Image.file(_image)
),
)
);
stackChildren.addAll(renderBoxes(size));
if (_busy) {
stackChildren.add(
Center(
child: CircularProgressIndicator(),
)
);
}
return Scaffold(
appBar: AppBar(
title: Text("Object Detector"),
),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
FloatingActionButton(
heroTag: "Fltbtn2",
child: Icon(Icons.camera_alt),
onPressed: getImageFromCamera,
),
SizedBox(width: 10,),
FloatingActionButton(
heroTag: "Fltbtn1",
child: Icon(Icons.photo),
onPressed: getImageFromGallery,
),
],
),
body: Container(
alignment: Alignment.center,
child:Stack(
children: stackChildren,
),
),
);
}
// gets image from camera and runs detectObject
Future getImageFromCamera() async {
final pickedFile = await picker.getImage(source: ImageSource.camera);
setState(() {
if(pickedFile != null) {
_image = File(pickedFile.path);
} else {
print("No image Selected");
}
});
detectObject(_image);
}
// gets image from gallery and runs detectObject
Future getImageFromGallery() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
if(pickedFile != null) {
_image = File(pickedFile.path);
} else {
print("No image Selected");
}
});
detectObject(_image);
}
}
This is the code i was trying to run
Image for error is here
name: ml_classifier
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.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
tflite: ^1.0.4
image_picker: ^0.6.1+8
image: ^2.1.4
# 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
# The following section is specific to Flutter.
flutter:
# To add assets to your application, add an assets section, like this:
assets:
- assets/tflite/model_unquant.tflite
- assets/tflite/label.txt

how to make a button at the bottom of the drop down list

to create the popup list i used dropdown_search
design example as I would like to see it
when I start searching through the elements of the list, a button for adding should pop up
or the button should be immediately when we start searching for the element
drop-down list
button bottom
I chose all possible methods in the library, but still I can't use it with the addition of a button
all code
https://github.com/dimapichuev2000/test_dropdownbutton
main.dart
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:dropdown_search/dropdown_search.dart';
import 'package:test_dropdownbutton/gym_model.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData().copyWith(
primaryColor: Colors.amber,
colorScheme: ThemeData().colorScheme.copyWith(
primary: Colors.orange,
),
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _multiKey = GlobalKey<DropdownSearchState<String>>();
Widget _customDropDownExample(BuildContext context, GymModel? item) {
if (item == null) {
return const Text(
"Выберите фитнесс центр",
style:
TextStyle(fontSize: 15, color: Color.fromRGBO(33, 33, 33, 0.6)),
);
}
return Container(
child: (item.avatar == "")
? ListTile(
contentPadding: EdgeInsets.all(0),
leading: const CircleAvatar(
radius: 25,
backgroundColor: Colors.white,
backgroundImage: NetworkImage(
'https://img.icons8.com/ios/50/000000/gum-.png'),
),
title: Text(item.gym),
subtitle: Text(
item.location,
),
)
: ListTile(
contentPadding: const EdgeInsets.all(0),
leading: CircleAvatar(
radius: 25,
backgroundImage: NetworkImage(item.avatar ?? ''),
),
title: Text(item.gym),
subtitle: Text(
item.location,
),
),
);
}
Widget _exitPopup(BuildContext context) {
return Container(
decoration: const BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
),
padding: const EdgeInsets.only(top: 2),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
margin: EdgeInsets.all(8),
height: 30,
width: 30,
),
const Text(
"Фитнесс центр",
style: TextStyle(fontSize: 17, fontWeight: FontWeight.w500),
),
IconButton(
icon: Image.asset(
'assets/button_X.png',
width: 25,
height: 25,
fit: BoxFit.fill,
),
iconSize: 25,
onPressed: () {
Navigator.of(context).pop();
},
)
],
),
);
}
Widget _customPopupItemBuilderExample(
BuildContext context, GymModel? item, bool isSelected) {
return Container(
decoration: !isSelected
? null
: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.white,
),
child: ListTile(
selected: isSelected,
title: Text(item?.gym ?? ''),
subtitle: Text(item?.location ?? ''),
leading: (item!.avatar == "")
? const CircleAvatar(
radius: 25,
backgroundColor: Colors.white,
backgroundImage: NetworkImage(
'https://img.icons8.com/ios/100/000000/gum-.png'),
)
: CircleAvatar(
radius: 25,
backgroundImage: NetworkImage(item.avatar ?? ''),
)),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Key value Pair - DropdownButton'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Container(
margin: const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
child: SingleChildScrollView(
child: DropdownSearch<GymModel>(
mode: Mode.BOTTOM_SHEET,
showSearchBox: true,
compareFn: (item, selectedItem) => item?.id == selectedItem?.id,
scrollbarProps:ScrollbarProps(
radius: Radius.circular(20),
thickness: 4,
),
onFind: (String? filter) => getData(filter),
dropdownSearchDecoration: const InputDecoration(
filled: true,
fillColor: Color(0xFFE3E3E4),
hintText: "Выберите фитнесс центр",
border: OutlineInputBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10),
),
borderSide: BorderSide(
width: 0,
style: BorderStyle.none,
),
),
contentPadding: EdgeInsets.fromLTRB(12, 3, 0, 0),
),
popupSafeArea:
const PopupSafeAreaProps(top: true, bottom: true),
// labelText: "Выберите фитнесс центр ",
onChanged: (data) {
print(data);
},
maxHeight: 850,
dropdownBuilder: _customDropDownExample,
popupItemBuilder: _customPopupItemBuilderExample,
dropDownButton: Image.asset('assets/dropButton.png',
color: Color(0xFF79818A)),
popupTitle: _exitPopup(context),
popupShape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
),
),
searchFieldProps: TextFieldProps(
decoration: const InputDecoration(
prefixIcon: Icon(
Icons.search,
),
filled: true,
fillColor: Color(0xFFE3E3E4),
border: OutlineInputBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
bottomLeft: Radius.circular(10),
bottomRight: Radius.circular(10),
),
borderSide: BorderSide(
width: 0,
style: BorderStyle.none,
),
),
contentPadding: EdgeInsets.fromLTRB(12, 12, 8,0),
// labelText: "Поиск",
hintText: "Поиск",
hintStyle: TextStyle(fontSize: 17)),
),
),
),
),
],
),
),
);
}
Future<List<GymModel>> getData(filter) async {
var response = await Dio().get(
"https://my-json-server.typicode.com/dimapichuev2000/JSON_TEST/posts",
queryParameters: {"filter": filter},
);
final data = response.data;
if (data != null) {
return GymModel.fromJsonList(data);
}
return [];
}
}
gym_model.dart
class GymModel {
final String id;
final String location;
final String gym;
final String? avatar;
GymModel(
{required this.id,
required this.location,
required this.gym,
this.avatar});
factory GymModel.fromJson(Map<String, dynamic> json) {
return GymModel(
id: json["id"],
location: json["location"],
gym: json["gym"],
avatar: json["avatar"],
);
}
static List<GymModel> fromJsonList(List list) {
return list.map((item) => GymModel.fromJson(item)).toList();
}
#override
String toString() => gym;
}
pubspec.yaml
name: fitsupp_coach
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.12.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_localizations:
sdk: flutter
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
pinput: ^1.2.2
intl: ^0.17.0
quiver: ^3.0.1+1
firebase_auth: ^3.3.5
firebase_core: ^1.11.0
dropdown_search: ^2.0.1
dio: ^4.0.4
provider: ^6.0.2
percent_indicator: ^4.0.0
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:
- assets/images/
- assets/images/DropDown/
# 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: SF Pro Display
fonts:
- asset: fontsassets/SFProDisplay/SFProDisplay-Light.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Medium.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Black.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Bold.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Heavy.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Regular.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Semibold.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Thin.ttf
- asset: fontsassets/SFProDisplay/SFProDisplay-Ultralight.ttf
style: normal
- family: SF Pro Text
fonts:
- asset: fontsassets/SFProText/SF-Pro-Text-Light.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Medium.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Black.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Bold.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Heavy.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Regular.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Semibold.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Thin.otf
- asset: fontsassets/SFProText/SF-Pro-Text-Ultralight.otf
style: normal
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
flutter_intl:
enabled: true
There are many ways you can do that but the easiest and the most elegant solution in my opinion is the following:
Column(
children: [
Flexible(
child: ListView.builder(
shrinkWrap: true,
itemCount: 5,
itemBuilder: (BuildContext context, int i) {
return Text(i.toString());
},
),
),
ElevatedButton.icon(
onPressed: null,
icon: const Icon(Icons.abc),
label: const Text('next')),
],
);
Start with a Column widget and then add ListView.builder and button of your choosing, I use ElevatedButton.icon, as it's children. Now set the shrinkWrap setting in ListView.builder to true and finally wrap it with Flexible widget.
In your case, you can wrap your Container widget with a ListView.builder widget and if you get viewport.dart error just wrap it with either Flexible or Expanded, depending on how much space you want it to consume. Then you can add logic to check if you are at the last index, in which case you can show your button, this is kinda what the code it will end up looking like:
Flexible(
child: ListView.builder(
shrinkWrap: true,
itemCount: _listSavedOutsideThisWidget.length+1,
itemBuilder: (BuildContext context, int index) {
if (index == _listSavedOutsideThisWidget.length) {
return TextButton.icon(
onPressed: _onPressed(context),
icon: const Icon(Icons.upload_file),
label: const Text('Upload Data'));
}
return Container(
decoration: !isSelected
? null
: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.white,
),
child: ListTile(
selected: isSelected,
title: Text(item?.gym ?? ''),
subtitle: Text(item?.location ?? ''),
leading: (item!.avatar == "")
? const CircleAvatar(
radius: 25,
backgroundColor: Colors.white,
backgroundImage: NetworkImage(
'https://img.icons8.com/ios/100/000000/gum-.png'),
)
: CircleAvatar(
radius: 25,
backgroundImage: NetworkImage(item.avatar ?? ''),
)),
);
},
),
);
For this method to work you will have to create a List<GymModel> _listSavedOutsideThisWidget = [] variable outside the build function and populate it by changing the onFind method under DropdownSearch widget, like such:
onFind: (String? filter) async {
List<GymModel>> filteredList = await gedtData(filter);
setState(() => _listSavedOutsideThisWidget = filteredList);
// return getData(filter);
return filteredList; // if this doesn't work, try uncommenting the above line
}
Hope this helps. Feel free to ask more questions.
OK, this may not be the most elegant solution, but it does the trick.
First create a Model for the button:
class BottomButton {
final String? text;
BottomButton({
this.text,
});
}
Then you are going to want to change all the output types from GymModel? to dynamic:
Widget _customDropDownExample(BuildContext context, dynamic item)
Widget _customPopupItemBuilderExample(
BuildContext context, dynamic item, bool isSelected)
DropdownSearch<dynamic>
Future<List<dynamic>> getData(filter)
Now, in the _customDropDownExample function where you are checking if the item == null add another to see if item is !GymModel:
if (item == null || item is !GymModel) {
return const Text(
"Выберите фитнесс центр",
style: TextStyle(fontSize: 15, color: Color.fromRGBO(33, 33, 33, 0.6)),
);
}
Inside _customPopupItemBuilderExample function check to see if the item is GymModel if so then do exactly what you were doing before and if not then create a button widget of your choice, I used an ElevatedButton for simplicity:
if (item is GymModel) {
return Container(
decoration: !isSelected
? null
: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.white,
),
child: ListTile(
selected: isSelected,
title: Text(item.gym),
subtitle: Text(item.location),
leading: (item.avatar == "")
? const CircleAvatar(
radius: 25,
backgroundColor: Colors.white,
backgroundImage: NetworkImage("https://picsum.photos/200"),
)
: CircleAvatar(
radius: 25,
backgroundImage: NetworkImage(item.avatar ?? ''),
)),
);
} else {
return ElevatedButton(onPressed: () {}, child: Text(item.text));
}
Also write an another function to filter the result and assign it to filterFn attribute in DropDownSearch widget:
bool _filterItems(dynamic item, String? str) {
if (item is GymModel) {
return (item.gym.toLowerCase().contains(str!.toLowerCase()) ||
item.location.toLowerCase().contains(str.toLowerCase()));
}
return (item is BottomButton);
}
Finally inside getData function where you check if the data != null add your button model (BottomButton, in my case) to the list:
Future<List<dynamic>> getData(filter) async {
var response = await Dio().get(
"https://my-json-server.typicode.com/dimapichuev2000/JSON_TEST/posts",
queryParameters: {"filter": filter},
);
final data = response.data;
if (data != null) {
List<dynamic> res = GymModel.fromJsonList(data);
BottomButton button = BottomButton(text: "Good Luck!");
return [...res, button];
}
return [];
}

Unhandled Exception: Bad state: field does not exist within the DocumentSnapshotPlatform (While it does exits on firestore)

I'm writing a code in which I'm trying to login admin. And for that I created an Admin on FireStore ,not with code, but with the options that firestore provide. It's like first I made an admin on firestore then I wrote a code in which I'm trying to login that perticular admin by providing the same admin's id and password inside the app. I suppose it is some kind of key issue but I don't know how to handle this error.
Below is the error when app is used on an Emulator
Below is the error when app is used on Real Android Mobile
And when Click on line #7 it takes me to the file where firestore code is written for admin login.
UPDATE:
And when I click the below line error(app running on actual phone) it takes me to a firestore snapshot file which I don't understand.
FirebaseFirestore console(Here the admin fields are created with the "+" options)
Flutter Doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.2.3, on Microsoft Windows [Version 10.0.19041.450], locale en-PK)
[√] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
[√] Chrome - develop for the web
[√] Android Studio
[√] Connected device (2 available)
• No issues found!
AdminLogin.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:ecom_app/Authentication/AuthnticationScreen.dart';
import 'package:ecom_app/DialogBox/errordialog.dart';
import 'package:ecom_app/Widgets/CustomTextField.dart';
import 'package:flutter/material.dart';
import 'Uploaditems.dart';
class Adminsignin extends StatelessWidget {
const Adminsignin({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
flexibleSpace: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.pink,Colors.lightGreenAccent],
begin: const FractionalOffset(0.0, 0.0),
end: const FractionalOffset(1.0, 0.0),
stops: [0.0,1.0],
tileMode: TileMode.clamp,
)
),
),
title: Text
(
'E-Shop',
style: TextStyle(
fontSize:55.0,color: Colors.white),
),
centerTitle: true,
),
body: AdminSignInPage(),
);
}
}
class AdminSignInPage extends StatefulWidget {
const AdminSignInPage({Key? key}) : super(key: key);
#override
_AdminSignInPageState createState() => _AdminSignInPageState();
}
class _AdminSignInPageState extends State<AdminSignInPage> {
final TextEditingController _adminController =TextEditingController();
final TextEditingController _passwordController =TextEditingController();
final GlobalKey<FormState> _formKey=GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
double _screenwidth=MediaQuery.of(context).size.width,_screenHeight=MediaQuery.of(context).size.height;
return SingleChildScrollView(
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.pink,Colors.lightGreenAccent],
begin: const FractionalOffset(0.0, 0.0),
end: const FractionalOffset(1.0, 0.0),
stops: [0.0,1.0],
tileMode: TileMode.clamp,
)
),
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
Container(
alignment: Alignment.bottomCenter,
child: Image.asset(
'images/welcome.png',
height: 240.0,
width: 240.0,
),
),
Padding(
padding:EdgeInsets.all(8.0),
child: Text('Admin',
style: TextStyle(color: Colors.white38,fontSize: 28.0,fontWeight: FontWeight.bold),
),
),
Form(
key: _formKey,
child: Column(
children: [
customtextfield(
controller: _adminController,
data: Icons.person,
hinttext: 'ID',
isObsecure:false,
),
customtextfield(
controller: _passwordController,
data: Icons.lock,
hinttext: 'Password',
isObsecure:true,
),
SizedBox(
height: 25.0,
),
ElevatedButton(
onPressed: ()=>
_adminController.text.isNotEmpty&&_passwordController.text.isNotEmpty
? loginAdmin ()
:showDialog(
context: context,
builder: (c){
return ErrorDialog(message: 'Please Enter ID and Password');
}
),
style: ElevatedButton.styleFrom(primary: Colors.pink,onPrimary: Colors.yellow),
child:Text("Login"),
),
SizedBox(
height: 50.0,
),
Container(
height: 4.0,
width: _screenwidth*0.8,
color: Colors.pink,
),
SizedBox(
height: 10.0,
),
FlatButton.icon(
onPressed: (){
Navigator.push(context, MaterialPageRoute(builder: (context)=>AuthenticScreen( )));
},
icon: Icon(Icons.admin_panel_settings,color: Colors.pink,),
label: Text('I am not an Admin',style: TextStyle(color: Colors.pink,fontWeight: FontWeight.bold),),
),
SizedBox(
height: 50.0,
),
],
)
),
],
),
),
);
}
loginAdmin (){
FirebaseFirestore.instance.collection('admins').get().then((snapshot){
snapshot.docs.forEach((result){
if(result['id'] != _adminController.text.trim())
{
Scaffold.of(context).showSnackBar(SnackBar(content: Text('ID is not Correct')));
}
else if(result['password' != _passwordController.text.trim()])
{
Scaffold.of(context).showSnackBar(SnackBar(content: Text('Passwod is not Correct')));
}
else
{
Scaffold.of(context).showSnackBar(SnackBar(content: Text('Welcome Admin, ' +result['name'],)));
setState(() {
_adminController.text='';
_passwordController.text='';
});
Route route=MaterialPageRoute(builder: (c)=> UploadPage());
Navigator.pushReplacement(context, route);
}
});
});
}
}
Check all field in firestore are the same in your code.
May be this field (Admin) changed to Admins
The issue is solved. Their were 2 things.
I made a mistake by not creating a required field 'name'. Also you must check that, If you are using small letters in firestore than use small and if your are using capitals, than use capital letters in your code fields as well. Firestore is sensitive to letter case
In newer version of flutter now the command has changed and now it required a data() as well.
This is the updated code that worked for me
if(result['id'] != _adminController.text.trim())
is changed to
if(result.data()['id'] != _adminController.text.trim())
loginAdmin () {
FirebaseFirestore.instance.collection('admins').get().then((snapshot){
snapshot.docs.forEach((result){
if(result.data()['id'] != _adminController.text.trim())
{
Scaffold.of(context).showSnackBar(SnackBar(content: Text('ID is not Correct')));
}
else if(result.data()['password'] != _passwordController.text.trim())
{
Scaffold.of(context).showSnackBar(SnackBar(content: Text('Passwod is not Correct')));
}
else
{
Scaffold.of(context).showSnackBar(SnackBar(content: Text('Welcome Admin, ' +result.data()['name'],)));
setState(() {
_adminController.text='';
_passwordController.text='';
});
Route route=MaterialPageRoute(builder: (c)=> UploadPage());
Navigator.pushReplacement(context, route);
}
});
});

Having a small problem with my flutter app. I'm unable to print location value on the screen. What should be done?

I'm trying to create a flutter weather app. It's my first time creating an app and learning to code. So far it's good, but I have one slight problem. I'm unable to print or show the location on the screen. İt's supposed to be at the very top of the devices screen.
When I run the app on an Emulator, it does show the current location of the device. But when I run the app on a physical device (OnePlus 5 and Galaxy S10), It doesn't show the location.
As you will see below, I'm also unable to print the location into the console.
I have 2 .dart files. Code in both files are provided below.
Other than that everything works perfectly. No errors are being shown.
What am I missing or what have I done wrong. Thanks for the help.
main.dart:
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'GetLocation.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
void main() {
runApp(AuraWeather());
}
class AuraWeather extends StatefulWidget {
#override
_AuraWeatherState createState() => _AuraWeatherState();
}
class _AuraWeatherState extends State<AuraWeather> {
var apiKey = '******************************';
var description;
var city;
var maxTemp;
var minTemp;
var temp;
#override
Widget build(BuildContext context) {
getLocation();
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(displayBackground()),
),
),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaY: 2, sigmaX: 2),
child: Container(
color: Colors.black.withOpacity(0.5),
child: Scaffold(
backgroundColor: Colors.transparent,
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Column(
children: <Widget>[
Container(
child: Center(
child: Text(
'$city',
style: TextStyle(
fontSize: 35,
color: Colors.white,
),
),
),
),
Container(
child: Icon(
FontAwesomeIcons.locationArrow,
color: Colors.white,
),
),
Container(
margin: EdgeInsets.only(top: 80),
child: Text(
'$temp' + '°',
style: TextStyle(
fontSize: 50,
color: Colors.white,
fontWeight: FontWeight.w600),
),
),
],
),
Container(
margin: EdgeInsets.only(top: 30),
child: Icon(
Icons.wb_sunny,
color: Colors.white,
size: 100,
),
),
Container(
child: Center(
child: Text(
'$maxTemp ° | $minTemp °',
style: TextStyle(fontSize: 20, color: Colors.white),
),
),
),
Container(
child: Text(
'$description',
style: TextStyle(fontSize: 20, color: Colors.white),
),
),
Container(
child: FlatButton(
child: Icon(
Icons.refresh,
color: Colors.white,
size: 40,
),
color: Colors.transparent,
onPressed: () {
setState(
() {
getLocation();
},
);
},
),
),
],
),
),
),
),
),
);
}
// display background images based on current time
displayBackground() {
var now = DateTime.now();
final currentTime = DateFormat.jm().format(now);
if (currentTime.contains('AM')) {
return 'images/Blood.png';
} else if (currentTime.contains('PM')) {
return 'images/Sun.png';
}
}
//getLocation
void getLocation() async {
Getlocation getlocation = Getlocation();
await getlocation.getCurrentLocation();
print(getlocation.latitude);
print(getlocation.longitude);
print(getlocation.city);
city = getlocation.city;
getTemp(getlocation.latitude, getlocation.longitude);
}
//Get current temp
Future<void> getTemp(double lat, double lon) async {
http.Response response = await http.get(
'https://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lon&appid=$apiKey&units=metric');
//print(response.body);
var dataDecoded = jsonDecode(response.body);
description = dataDecoded['weather'][0]['description'];
temp = dataDecoded['main']['temp'];
temp = temp.toInt();
maxTemp = dataDecoded['main']['temp_max'];
maxTemp = maxTemp.toInt();
minTemp = dataDecoded['main']['temp_min'];
minTemp = minTemp.toInt();
print(temp);
}
}
GetLocation.dart:
import 'package:geolocator/geolocator.dart';
class Getlocation {
double latitude;
double longitude;
String city;
//Get current location
Future<void> getCurrentLocation() async {
try {
Position position = await Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
latitude = position.latitude;
longitude = position.longitude;
city = await getCityName(position.latitude, position.longitude);
} catch (e) {
print(e);
}
}
//Get city name
Future<String> getCityName(double lat, double lon) async {
List<Placemark> placemark =
await Geolocator().placemarkFromCoordinates(lat, lon);
print('city name is: ${placemark[0].locality}');
return placemark[0].locality;
}
}
Console window:
Performing hot reload...
Syncing files to device ONEPLUS A5000...
Reloaded 0 of 587 libraries in 251ms.
I/flutter (13296): city name is:
I/flutter (13296): 41.0179339
I/flutter (13296): 28.6239036
I/flutter (13296):
I/flutter (13296): 20
Pubspec:
name: com
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
intl: ^0.16.1
geolocator: ^5.3.1
http: ^0.12.0+4
sunrise_sunset: ^1.0.2
font_awesome_flutter: ^8.5.0
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/
# - 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
AndroidManifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.auraweather">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- io.flutter.app.FlutterApplication is an android.app.Application that
calls FlutterMain.startInitialization(this); in its onCreate method.
In most cases you can leave this as-is, but you if you want to provide
additional functionality it is fine to subclass or reimplement
FlutterApplication and put your custom class here. -->
<application
android:name="io.flutter.app.FlutterApplication"
android:label="auraweather"
android:icon="#mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="#style/NormalTheme"
/>
<!-- Displays an Android View that continues showing the launch screen
Drawable until Flutter paints its first frame, then this splash
screen fades out. A splash screen is useful to avoid any visual
gap between the end of Android's launch screen and the painting of
Flutter's first frame. -->
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="#drawable/launch_background"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
its seems good code, but something is absent here.
first: where is your location permission request?
Second : why dont use initState for override
getLocation();
and in final step, u must implement all requirements for Geolocator plugin.
check these steps and update me in comment.