A flutter newbie, I'm trying to get my app to take values from a local json file and render them on-screen.
The logic isn't waiting for the class constructor to populate the relevant string variable before rendering the app on screen.
Here's the code that illustrates my problem.
First, my main.dart file:
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'sampleDataClass.dart';
import 'package:provider/provider.dart';
String assetFilePath = 'assets/basicData.json';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
FlutterError.onError = (details) {
FlutterError.presentError(details);
if (kReleaseMode) exit(1);
};
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => MyAppState(),
child: const MaterialApp(
title: "Sample screen",
home: MyHomePage(),
)
);
}
}
class MyAppState extends ChangeNotifier {
SampleDataClass current = SampleDataClass(assetFilePath);
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
#override
Widget build(BuildContext context) {
var myAppState = context.watch<MyAppState>();
var myAppBasicData = myAppState.current;
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.indigo,
foregroundColor: Colors.amberAccent,
title: const Text("This is the App Bar"),
elevation: 10,
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(children: [
Expanded(
child: Container(
color: Colors.blueGrey,
padding: const EdgeInsets.all(10),
child: (
Text(myAppBasicData.language,
style: const TextStyle(
color: Colors.white,
))))),
]),
]
),
);
}
}
Here is my SampleDataClass.dart file:
import 'dart:core';
import 'dart:convert';
import 'package:flutter/services.dart' show rootBundle;
class SampleDataClass {
String classFilePath = "";
String language = "not populated";
String batteryName = "not populated";
SampleDataClass(filePath) {
rootBundle.loadString(filePath).then((jsonDataString) {
Map classDataMap = jsonDecode(jsonDataString);
language = classDataMap['language'];
print(language);
batteryName = classDataMap['batteryName'];
print(batteryName);
});
}
Map<String, dynamic> toJson() => {
'language': language,
'batteryName': batteryName,
};
}
And here's my pubspec.yaml file:
name: samples
description: A new Flutter project.
environment:
sdk: '>=2.18.6 <3.0.0'
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
provider: ^4.1.1
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
flutter:
uses-material-design: true
assets:
- assets/basicData.json
Finally, my basicData.json file looks like this:
{
"language": "English",
"batteryName": "Exercise 32"
}
The print statements in the sampleDataClass class work fine but as you can see if you run the code (from the command line using "flutter run --no-sound-null-safety"), the app renders the initial values of the variables before the class constructor assigns the json values to them.
What I expected was the class constructor to complete writing the relevant json values to the class members before handing back the class instance to the build widget in main.dart to render the app on-screen.
I realise that this is a very elementary question, but it is a key pending learning task for me!
Thank you all very much in advance!
it looks like rootBundle is an async function, you have to wait till it finishes then you notify the UI to render with new data,
How to handle this :
you should have 3 states loading state , error state , loaded state ,
create an init(path) function in SampleDataClass class that returns SampleDataClass instance.
Also, in the init() function at the beginning you have to change the state to loading state then when you get the data you set the state to loaded state, then notify listeners this will help the screen to know which state the page is in.
in the screen , call didChangeDependencies() and inside it, call your Provider => init function ( current = contecxt.read<YPUR_PROVIDER>().init(path); )
therefore the current object is being initialized, the page is showing a loader, and once the initialization is done, the provider will notify the page and it will change the loading view to the loaded view (your current view).
Another Tip::
your app will close whenever there is an error, it is not a good practice, since flutter will through non-fatal exception
FlutterError.onError = (details) {
FlutterError.presentError(details);
if (kReleaseMode) exit(1);
There is a choice of two excellent solutions to my problem with very little effort and no need for any change management (yet).
Indeed, so similar is the problem described that I probably should have found it before I posted this query here. As a newbie in this discipline, I clearly didn't conduct my search with the appropriate key words; for that I apologise!
Thanks very much to everyone for your patience.
The two solution options (which even I was able to follow) can be found here:
Calling an async method from a constructor in Dart
I have a new project in Flutter working on an existing Firestore database.
I cannot seem to get the collection to surface in a list view (or even debugging). Firestore access seems Ok as I can use the Auth module Ok.
If I use the debugger and step into the collection get function, I can see the data is being returned, but the .then function is not being triggered. Am new to dart so am having trouble trying to figure out why the data is not being bubbled up to the .then()
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class InviteView extends StatelessWidget {
InviteView({Key? key}) : super(key: key);
List<String> ids = [];
#override
Widget build(BuildContext context) {
return Expanded(
child: FutureBuilder(
future: _getPlayers(),
builder: (context, snapshot) {
return ListView.builder(
itemCount: ids.length,
itemBuilder: (cxt, idx) {
return ListTile(
title: Text(ids[idx]),
);
},
);
},
),
);
}
Future<void> _getPlayers () async {
const source = Source.server;
await FirebaseFirestore.instance.collection('players').get(const GetOptions(source: source)).then(
(snapshot) => snapshot.docs.map((document) {
print(document.reference.id);
ids.add(document.reference.id);
}),
onError: (e) => print (e.toString())
);
}
}
Output from flutter doctor
[√] Flutter (Channel stable, 3.0.1, on Microsoft Windows [Version 10.0.22000.675], locale en-AU)
[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[√] Chrome - develop for the web
[X] Visual Studio - develop for Windows
X Visual Studio not installed; this is necessary for Windows development.
Download at https://visualstudio.microsoft.com/downloads/.
Please install the "Desktop development with C++" workload, including all of its default components
[√] Android Studio (version 2021.1)
[√] Android Studio (version 2021.2)
[√] Android Studio (version 4.1)
[√] VS Code (version 1.65.2)
[√] VS Code, 64-bit edition (version 1.32.3)
[√] Connected device (3 available)
[√] HTTP Host Availability
using cloud_firestore: ^3.1.17
Does this help:
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class InviteView extends StatelessWidget {
InviteView({Key? key}) : super(key: key);
List<String> ids = [];
#override
Widget build(BuildContext context) {
return Expanded(
child: FutureBuilder<Widget>(
future: _getPlayers(),
builder: (context, snapshot) {
if (!snapshot.hasData) return const Text('Oh no!');
return snapshot.data!;
},
),
);
}
Future<ListView> _getPlayers() async {
var snap = await FirebaseFirestore.instance.collection('players').get();
return ListView(
children: snap.docs
.map((doc) => ListTile(
title: Text(doc.reference.id),
))
.toList());
}
}
I'm having issues just using google_mobile_ads, when I try the method in the flutter tutorial I don't know how to make it work in my main
main
import 'package:android_alarm_manager/android_alarm_manager.dart';
import 'package:behend/admob_service.dart';
import 'package:behend/provider/alarm_manager.dart';
import 'package:behend/provider/alarm_provider.dart';
import 'package:behend/provider/setting_provider.dart';
import 'package:behend/provider/stats_provider.dart';
import 'package:behend/screen/Tooltips/intro.dart';
import 'package:behend/screen/alarm_appear_screen.dart';
import 'package:behend/utils/app_preference_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_statusbarcolor/flutter_statusbarcolor.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'generated/l10n.dart';
import 'admob_service.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
///para los ads =v
final initFuture = MobileAds.instance.initialize();
final adState = AdState(initFuture);
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(statusBarIconBrightness: Brightness.dark));
await AndroidAlarmManager.initialize();
SharedPreferences.getInstance().then((value) {
AppPreferenceUtil(pref: value);
runApp(MultiProvider(
providers: [
Provider.value(
value: adState,
builder: (context, child)),
ChangeNotifierProvider(
create: (_) => AlarmManager(),
),
ChangeNotifierProvider(
create: (_) => SettingProvider(),
),
ChangeNotifierProvider(
create: (_) => AlarmProvider.full(),
),
ChangeNotifierProvider(
create: (_) => StatsProvider(),
)
],
child: MyApp(),
));
});
//runApp(MyApp());
}
Future<void> alarm() async {
print("launching alarm entry point____----___");
WidgetsFlutterBinding.ensureInitialized();
await AndroidAlarmManager.initialize();
SharedPreferences.getInstance().then((value) {
AppPreferenceUtil(pref: value);
runApp(MultiProvider(providers: [
ChangeNotifierProvider(
create: (_) => AlarmManager(),
),
ChangeNotifierProvider(
create: (_) => AlarmProvider.minimal(),
)
], child: MyApp2()));
});
//runApp(MyApp());
}
class MyApp2 extends StatefulWidget {
#override
_MyApp2State createState() => _MyApp2State();
}
class _MyApp2State extends State<MyApp2> {
#override
void initState() {
FlutterStatusbarcolor.setStatusBarWhiteForeground(true);
Provider.of<AlarmManager>(context, listen: false).init(context);
super.initState();
}
#override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
),
child: MaterialApp(
title: 'Behend',
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
S.delegate,
],
supportedLocales:
///[
/// const Locale('en', ''),
///const Locale('es', ''),
///],
S.delegate.supportedLocales,
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.teal,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: Consumer<AlarmManager>(
builder: (context, provider, child) {
return AlarmAppearScreen(provider.currentAlarmId);
},
),
),
);
}
}
class MyApp extends StatelessWidget {
/*static final FirebaseAnalytics analytics = FirebaseAnalytics();
static final FirebaseAnalyticsObserver observer =
FirebaseAnalyticsObserver(analytics: analytics);
// This widget is the root of your application.*/
#override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
// uncomment this and open this function
//updateScoreCard();
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
),
child: MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
S.delegate,
],
supportedLocales:
///[
///const Locale('en', ''),
///const Locale('es', ''),
///],
S.delegate.supportedLocales,
title: 'Behend',
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,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
//home: EasySortScreen(),
// home: SwitchExample(),
// home: HomeScreen(), --
home: Intro(),
navigatorObservers: <NavigatorObserver>[/*observer*/],
),
);
}
adstate
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'dart:io';
class AdState {
Future<InitializationStatus> initialization;
AdState(this.initialization);
static String get bannerAdUnitId => Platform.isAndroid
///El primer id es para android
? 'ca-app-pub-3940256099942544/6300978111'
///El segundo id es para IOS
: 'ca-app-pub-3940256099942544/6300978111';
}
yaml
name: behend
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.5.39+29
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
google_mobile_ads: ^0.11.0+3
dart_random_choice: ^0.0.2
curved_navigation_bar:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
cupertino_icons: ^0.1.3
provider: ^4.1.2
percent_indicator: "^2.1.1"
package_info: ^0.4.0+16
fl_chart: 0.9.4
shared_preferences: ^0.5.7+3
intl: ^0.17.0
vibration: ^1.4.0
showcaseview: ^0.1.5
fluttertoast: ^3.1.0
android_alarm_manager:
path: ./android_alarm_manager-0.4.5_11
#parece que no funciona(deprecated) o pisa el nuevo package de google_mobile_ads
#(tira error con el package de google ads(si se quita no lo lo tira))
#firebase_analytics:
# path: ./firebase_analytics-5_0_16
flutter_swiper: 1.1.6
flutter_tindercard: 0.1.8
url_launcher: 5.4.10
flutter_reorderable_list: ^0.1.4
flutter_statusbarcolor: 0.2.3
after_layout: ^1.0.7+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:
- assets/
- assets/images/
- assets/images/intro-slider/
- assets/images/Tooltips/
- assets/icons/
- assets/icons/2.0x/
- assets/icons/3.0x/
# 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: Circular
fonts:
- asset: assets/fonts/CircularStd-Black.ttf
- asset: assets/fonts/CircularStd-Bold.ttf
- family: Roboto
fonts:
- asset: assets/fonts/Roboto-Bold.ttf
- asset: assets/fonts/Roboto-Regular.ttf
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
flutter_intl:
enabled: true
main_locale: en
class_name: S
Since I cannot pass context in that list in my main I tried some other method that in found in Youtube
main
import 'package:android_alarm_manager/android_alarm_manager.dart';
import 'package:behend/admob_service.dart';
import 'package:behend/provider/alarm_manager.dart';
import 'package:behend/provider/alarm_provider.dart';
import 'package:behend/provider/setting_provider.dart';
import 'package:behend/provider/stats_provider.dart';
import 'package:behend/screen/Tooltips/intro.dart';
import 'package:behend/screen/alarm_appear_screen.dart';
import 'package:behend/utils/app_preference_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_statusbarcolor/flutter_statusbarcolor.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'generated/l10n.dart';
import 'admob_service.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
AdMobService.initialize();
/*
///para los ads =v
final initFuture = MobileAds.instance.initialize();
final adState = AdState(initFuture);
*/
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(statusBarIconBrightness: Brightness.dark));
await AndroidAlarmManager.initialize();
SharedPreferences.getInstance().then((value) {
AppPreferenceUtil(pref: value);
runApp(MultiProvider(
providers: [
/*Provider.value(
value: adState,
builder: (context, child)),*/
ChangeNotifierProvider(
create: (_) => AlarmManager(),
),
ChangeNotifierProvider(
create: (_) => SettingProvider(),
),
ChangeNotifierProvider(
create: (_) => AlarmProvider.full(),
),
ChangeNotifierProvider(
create: (_) => StatsProvider(),
)
],
child: MyApp(),
));
});
//runApp(MyApp());
}
Future<void> alarm() async {
print("launching alarm entry point____----___");
WidgetsFlutterBinding.ensureInitialized();
await AndroidAlarmManager.initialize();
SharedPreferences.getInstance().then((value) {
AppPreferenceUtil(pref: value);
runApp(MultiProvider(providers: [
ChangeNotifierProvider(
create: (_) => AlarmManager(),
),
ChangeNotifierProvider(
create: (_) => AlarmProvider.minimal(),
)
], child: MyApp2()));
});
//runApp(MyApp());
}
class MyApp2 extends StatefulWidget {
#override
_MyApp2State createState() => _MyApp2State();
}
class _MyApp2State extends State<MyApp2> {
#override
void initState() {
FlutterStatusbarcolor.setStatusBarWhiteForeground(true);
Provider.of<AlarmManager>(context, listen: false).init(context);
super.initState();
}
#override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
),
child: MaterialApp(
title: 'Behend',
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
S.delegate,
],
supportedLocales:
///[
/// const Locale('en', ''),
///const Locale('es', ''),
///],
S.delegate.supportedLocales,
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.teal,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: Consumer<AlarmManager>(
builder: (context, provider, child) {
return AlarmAppearScreen(provider.currentAlarmId);
},
),
),
);
}
}
class MyApp extends StatelessWidget {
/*static final FirebaseAnalytics analytics = FirebaseAnalytics();
static final FirebaseAnalyticsObserver observer =
FirebaseAnalyticsObserver(analytics: analytics);
// This widget is the root of your application.*/
#override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
// uncomment this and open this function
//updateScoreCard();
return AnnotatedRegion<SystemUiOverlayStyle>(
value: SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
),
child: MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
S.delegate,
],
supportedLocales:
///[
///const Locale('en', ''),
///const Locale('es', ''),
///],
S.delegate.supportedLocales,
title: 'Behend',
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,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
//home: EasySortScreen(),
// home: SwitchExample(),
// home: HomeScreen(), --
home: Intro(),
navigatorObservers: <NavigatorObserver>[/*observer*/],
),
);
}
adState
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'dart:io';
/*
class AdState {
Future<InitializationStatus> initialization;
AdState(this.initialization);
static String get bannerAdUnitId => Platform.isAndroid
///El primer id es para android
? 'ca-app-pub-3940256099942544/6300978111'
///El segundo id es para IOS
: 'ca-app-pub-3940256099942544/6300978111';
}
*/
class AdMobService {
static String get bannerAdUnitId => Platform.isAndroid
///El primer id es para android
? 'ca-app-pub-3940256099942544/6300978111'
///El segundo id es para IOS
: 'ca-app-pub-3940256099942544/6300978111';
static initialize () {
if (MobileAds.instance == null){
MobileAds.instance.initialize();
}
}
static BannerAd createBannerAd() {
BannerAd ad = new BannerAd(
adUnitId: bannerAdUnitId,
size: AdSize.banner,
request: AdRequest(),
listener: AdListener(
onAdLoaded: (Ad ad) => print("Ad loaded"),
onAdFailedToLoad: (Ad ad, LoadAdError error) {
ad.dispose();
},
onAdOpened: (Ad ad) => print("ad opened"),
onAdClosed: (Ad ad) => print("ad closed")
)
);
return ad;
}
}
Here it run but it gives me this error (only happens when I have google_mobile_ads package activated)
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:processDebugResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
> Android resource linking failed
C:\Users\negre\.gradle\caches\transforms-2\files-2.1\6860be4bd435a3ae0d9b52a862c3efa5\play-services-ads-lite-19.7.0\AndroidManifest.xml:27:5-43:15: AAPT: error: unexpected element <queries> found in <manifest>.
* 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 18s
The build failed likely due to AndroidX incompatibilities in a plugin. The tool is about to try using Jetifier to solve the incompatibility.
Building plugin android_alarm_manager...
Running Gradle task 'assembleAarRelease'...
√ Built build\app\outputs\repo.
Building plugin flutter_statusbarcolor...
Running Gradle task 'assembleAarRelease'...
√ Built build\app\outputs\repo.
Building plugin fluttertoast...
Running Gradle task 'assembleAarRelease'...
√ Built build\app\outputs\repo.
Building plugin google_mobile_ads...
Running Gradle task 'assembleAarRelease'...
FAILURE: Build failed with an exception.
* Where:
Build file 'C:\Users\negre\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\google_mobile_ads-0.11.0+3\android\build.gradle' line: 22
* What went wrong:
A problem occurred evaluating root project 'google_mobile_ads'.
> Failed to apply plugin [id 'com.android.internal.version-check']
> Minimum supported Gradle version is 6.5. Current version is 5.6.4. If using the gradle wrapper, try editing the distributionUrl in C:\Users\negre\AppData\Local\Pub\Cache\hosted\pub.dartlang.org\google_mobile_ads-0.11.0+3\android\gradle\wrapper\gradle-wrapper.properties to gradle-6.5-all.zip
* 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 1s
Exception: The plugin google_mobile_ads could not be built due to the issue above.
android/build.gradle
open build.gradle file.
Check if the Android Gradle Plugin 4.1 or higher. If it's less than 4.1 then change the Gradle Plugin as like the following code
dependencies {
classpath 'com.android.tools.build:gradle:4.1.0'
...
}
android/gradle/wrapper/gradle-wrapper.properties
open gradle-wrapper.properties file. Change the distributionUrl to the following line.
distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip
then run the flutter clean command
at last, restart the IDE and build the app.
This is how I solve this problem. Hope this will solve your problem too.
I'm developing a Flutter application that needs to make http requests. I installed the http package as usual, but when it came time to test the app in a real device, the http requests are hanging, I never get a response or status code. I decided then to start a new application just to mess around with http package, but still I got the same issue.
This is what I get while debugging in Android Emulator (I get a response almost immediately) and this is what I get on a real device (hanging forever).
Possible solutions I have already tried: built signed and unsigned apk, ran flutter clean before building apk, built apk using --no-shrink flag, changed the version of http package in pubspec.yaml, and none of these seemed to solve the issue.
I am using the latest stable version of Flutter SDK (v1.17.5), Android Studio for coding, and Ubuntu 20.04 as Operating System.
Here is my dart code:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class AuthScreen extends StatefulWidget {
#override
_AuthScreenState createState() => _AuthScreenState();
}
class _AuthScreenState extends State<AuthScreen> {
final TextEditingController _urlController = TextEditingController();
String _status = 'Waiting for request';
void _submit() async {
setState(() {
_status = 'Waiting for response...';
});
var response = await http.get(_urlController.text);
if (response.statusCode == 200) {
setState(() {
_status = response.body.substring(0, 40) + ' [...]';
});
} else {
_status = 'Something went wrong';
}
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextFormField(
controller: _urlController,
),
FlatButton(
child: Text('Send request'),
onPressed: _submit,
),
Text(_status)
],
),
),
);
}
}
Here is my pubspec.yaml, in case it's useful:
name: testingHttpPackage
description: A new Flutter application.
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
http: ^0.12.1
cupertino_icons: ^0.1.3
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
Did you mention internet permission in AndroidManifest.xml file?
In android/app/src/main/, there is AndroidManifest.xml file, put the below line after manifest tag i.e. after the first tag.
<uses-permission android:name="android.permission.INTERNET" />
So I'm new to flutter and dart.I've made multiple android apps and I am pretty familiar with coding but I just can't get to know flutter. I use Android Studio as Ide and when I try to compile my code , on the assembleDebug part, This error is thrown:
c:\b\s\w\ir\k\src\third_party\dart\runtime\vm\zone.cc: 54: error: Out
of memory.
version=2.4.0 (Wed Jun 19 11:53:45 2019 +0200) on "windows_x64"
thread=1336, isolate=main(0000029506C2CDE0)
pc 0x00007ff7b33d2b1b fp 0x000000d10cbfb0a0 Unknown symbol
-- End of DumpStackTrace
For now, I haven't done anything to fix the problem because I don't know why
main.dart
import 'package:flutter/material.dart';
import 'constants.dart';
import 'package:flutter_svg/flutter_svg.dart';
void main() {
runApp(UnitConverterApp());
}
//on create
class UnitConverterApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Distivity Todolist',
theme: Constants.getTheme(),
home: CategoryRoute(),
);
}
}
class CategoryRoute extends StatefulWidget {
const CategoryRoute();
#override
_CategoryRouteState createState() => _CategoryRouteState();
}
class _CategoryRouteState extends State<CategoryRoute> {
/// Function to call when a [Category] is tapped.
void _onCategoryTap() {
setState(() {
});
}
#override
Widget build(BuildContext context) {
return Center(
child: InkWell(
onTap: () => _onCategoryTap(),
child: SvgPicture.asset(
Constants.add,
semanticsLabel: 'ad'
),
)
);
}
}
constants.dart
import 'package:flutter/material.dart';
class Constants{
static ThemeData getTheme(){
return ThemeData(
primaryColor: colorSwatch,
);
}
static const primaryColor = 0xff4FB484;
static ColorSwatch colorSwatch = ColorSwatch(primaryColor, const<String,Color>{
"primary_color": Color(primaryColor),
"primary_dark":Color(0xff306D50),
"black_16": Color(0xff161616),
"black_20":Color(0xff202020),
"the_blackest":Color(0xff000000),
"color_white":Color(0xffF7F7F7),
"the_whitest":Color(0xffffffff)
});
static const String add = 'assets/add.svg';
}
pubspec.yaml
name: distivity_todolist
description: A new Flutter application.
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
cupertino_icons: ^0.1.2
dev_dependencies:
flutter_svg: 0.13.1
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/add.svg