Snapshot.data not showing data occasionally - flutter

I have a FutureBuilder widget and when Flutter communicates with Firebase, it doesn't show the data. But, whenever I remove two fields I recently added out of the 6, it works and show the data. The fields to be removed are incomeTotal and expenseTotal
Code
Read data function
Stream<List<CardDetails>> readCards() => FirebaseFirestore.instance
.collection('cards')
.snapshots()
.map((snapshot) => snapshot.docs
.map((doc) => CardDetails.fromJson(doc.data()))
.toList());
Load data onto widget
StreamBuilder<List<CardDetails>>(
stream: readCards(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return const Text("error");
} else if (snapshot.hasData &&
snapshot.data!.isEmpty) {
return Container(
margin: const EdgeInsets.all(10),
width: double.infinity,
decoration: BoxDecoration(
color:
const Color.fromARGB(50, 0, 0, 0),
borderRadius:
BorderRadius.circular(20)),
child: Transform.scale(
scale: 1.5,
child: Lottie.asset(
"lib/images/space_animation.json")),
);
} else {
final cards = snapshot.data!;
if (cardIdOfficial == '') {
WidgetsBinding.instance
.addPostFrameCallback((_) {
setState(() {
cardIdOfficial = snapshot
.data![_pageViewController
.initialPage]
.id;
});
});
}
return PageView(
padEnds: false,
controller: _pageViewController,
onPageChanged: (value) => {
setState(() {
cardIdOfficial =
snapshot.data![value].id;
})
},
physics: const ClampingScrollPhysics(),
children:
cards.map(buildCards).toList());
}
}),
Model
class CardDetails {
final String id;
final String title;
final double balance;
final int cardDigits;
final int incomeTotal;
final int expenseTotal;
CardDetails({
required this.id,
required this.title,
required this.balance,
required this.cardDigits,
required this.incomeTotal,
required this.expenseTotal,
});
Map<String, dynamic> toJson() => {
'id': id,
'title': title,
'balance': balance,
'cardDigits': cardDigits,
'incomeTotal': incomeTotal,
'expenseTotal': expenseTotal,
};
static CardDetails fromJson(Map<String, dynamic> json) => CardDetails(
id: json['id'],
title: json['title'],
balance: json['balance'],
cardDigits: json['cardDigits'],
incomeTotal: json['incomeTotal'],
expenseTotal: json['expenseTotal']);
}
Everything was fine until I added those two fields, when I remove them everything looks fine. What I also did was change the variable name to just income instead of incomeTotal and ran it again, it worked but then this happened again twice.
Flutter doctor
[✓] Flutter (Channel stable, 3.7.3, on macOS 11.6.3 20G415 darwin-arm64, locale en-US)
[!] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
✗ cmdline-tools component is missing
Run `path/to/sdkmanager --install "cmdline-tools;latest"`
See https://developer.android.com/studio/command-line for more details.
✗ Android license status unknown.
Run `flutter doctor --android-licenses` to accept the SDK licenses.
See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.
[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.2)
[✓] IntelliJ IDEA Community Edition (version 2022.1.3)
[✓] VS Code (version 1.74.2)
[✓] VS Code (version 1.64.2)
[✓] Connected device (3 available)
[✓] HTTP Host Availability
Flutter dependencies
dependencies:
- cloud_firestore 4.3.1 [cloud_firestore_platform_interface cloud_firestore_web collection firebase_core firebase_core_platform_interface flutter meta]
- cupertino_icons 1.0.5
- custom_refresh_indicator 2.0.1 [flutter]
- firebase_core 2.4.1 [firebase_core_platform_interface firebase_core_web flutter meta]
- fluentui_icons 1.0.0 [flutter]
- fluentui_system_icons 1.1.190 [flutter]
- flutter 0.0.0 [characters collection js material_color_utilities meta vector_math sky_engine]
- flutter_slidable 2.0.0 [flutter]
- gap 2.0.1 [flutter]
- google_fonts 3.0.1 [flutter http path_provider crypto]
- google_nav_bar 5.0.6 [flutter]
- grouped_list 5.1.2 [flutter]
- intl 0.18.0 [clock meta path]
- lottie 2.2.0 [archive flutter path vector_math]
- metaballs 1.4.2 [flutter]
- provider 6.0.5 [collection flutter nested]
- sizer 2.0.15 [universal_io flutter]
- smooth_page_indicator 1.0.0+2 [flutter]
What happens
(https://i.stack.imgur.com/Wmaks.png)
What happens when I remove the two fields, what needs to happen (https://i.stack.imgur.com/YcPCY.png)

Your code looks fine, as far as I can tell. One possible issue I can think of:
Are you sure that every document within the cards collection in your Firestore database has those fields present and are integer values?
If one of those values wasn’t present on a document (or was of the wrong type), your deserialization (fromJson) would blow up.
In the past I’ve had trouble with this because it’s not always obvious that an error is being thrown - it’s sometimes swallowed within the internals of the stream.

Related

FirebaseException ([cloud_firestore/unavailable] The service is currently unavailable , and how to solve it

i created a simple app using flutter and firebase it all work well but when i click on profile icon from the navigationbar the app froze
Profile page code:
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:yumor/models/progress.dart';
import 'package:yumor/models/user_model.dart';
class profile extends StatefulWidget {
const profile({Key? key,required this.userProfile}) : super(key: key);
final String? userProfile;
#override
State<profile> createState() => _profileState();
}
class _profileState extends State<profile> {
final userRef = FirebaseFirestore.instance.collection('users');
buildprofileheader(){
return FutureBuilder(future:userRef.doc(widget.userProfile).get(),
builder: ((context, snapshot) {
if(!snapshot.hasData){
return CircularProgress();
}
UserModel user=UserModel.fromMap(Map);
return Padding(padding:EdgeInsets.all(16.0),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.account_circle, size: 90,)
],
),
Container(
alignment: Alignment.center,
padding: EdgeInsets.all(12.0),
child: Text(
user.Username as String,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize:16.0,
),
),
),
],
),
);
}),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
"Profile",
),
),
body: ListView(children: <Widget>[
// buildprofileHeader(),
]));
}
}
navigation Bar source code
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:yumor/models/user_model.dart';
import 'package:yumor/pages/Home_page.dart';
import 'package:yumor/pages/profile.dart';
import 'package:yumor/pages/search.dart';
import 'package:yumor/pages/upload.dart';
class BottomBar extends StatefulWidget {
const BottomBar({Key? key}) : super(key: key);
#override
State<BottomBar> createState() => _BottomBarState();
}
class _BottomBarState extends State<BottomBar> {
List pages = [
home_page(),
search(),
upload(),
profile(userProfile:FirebaseAuth.instance.currentUser!.uid),
];
// this current index means that this index depends on which one you click form 0 to 4
int currentIndex = 0;
void onTap(int index) {
// currentindex equale to index to take value
setState(() {
currentIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: pages[currentIndex],
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
selectedFontSize: 0,
unselectedFontSize: 0,
onTap: onTap,
currentIndex: currentIndex,
backgroundColor: Colors.white,
selectedItemColor: Colors.black87,
unselectedItemColor: Colors.grey.shade600.withOpacity(0.6),
elevation: 0,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home_outlined), label: 'home'),
BottomNavigationBarItem(icon: Icon(Icons.search), label: 'search'),
BottomNavigationBarItem(
icon: Icon(Icons.add_box_outlined), label: 'add'),
BottomNavigationBarItem(
icon: Icon(Icons.person_outline_rounded), label: 'profile'),
]),
);
}
}
firebase user creation code
import 'package:flutter/foundation.dart';
class UserModel {
String? uid;
String? Username;
String? email;
String? photoUrl;
UserModel(
{this.uid, this.email, this.Username, this.photoUrl});
// receving data from the server
factory UserModel.fromMap(Map) {
return UserModel(
uid: Map['userId'],
Username: Map['Username'],
email: Map['email'],
photoUrl: Map['photoUrl'],
);
}
// /// sending data to firestore
Map<String, dynamic> toMap() {
return {
'userId': uid,
'Username': Username,
'email': email,
'photoUrl': photoUrl,
};
}
}
error_patch.dart
#patch
#pragma("vm:external-name", "Error_throwWithStackTrace")
external static Never _throw(Object error, StackTrace stackTrace);
}
NOTE
flutter doctor -v
[
[√] Flutter (Channel stable, 3.3.5, on Microsoft Windows [Version 10.0.19044.2130], locale en-US)
• Flutter version 3.3.5 on channel stable at C:\Dart\flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision d9111f6402 (8 days ago), 2022-10-19 12:27:13 -0700
• Engine revision 3ad69d7be3
• Dart version 2.18.2
• DevTools version 2.15.0
Checking Android licenses is taking an unexpectedly long time...[√] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
• Android SDK at C:\Users\Abdou\AppData\Local\Android\Sdk
• Platform android-33, build-tools 33.0.0
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 11.0.12+7-b1504.28-7817840)
• All Android licenses accepted.
[X] Chrome - develop for the web (Cannot find Chrome executable at .\Google\Chrome\Application\chrome.exe)
! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.
[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.2)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin can be installed from:
https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 11.0.12+7-b1504.28-7817840)
[√] VS Code, 64-bit edition (version 1.72.2)
• VS Code at C:\Program Files\Microsoft VS Code
• Flutter extension version 3.50.0
[√] Connected device (3 available)
• Android SDK built for x86 (mobile) • emulator-5554 • android-x86 • Android 7.0 (API 24) (emulator)
• Windows (desktop) • windows • windows-x64 • Microsoft Windows [Version 10.0.19044.2130]
• Edge (web) • edge • web-javascript • Microsoft Edge 106.0.1370.52
[√] HTTP Host Availability
• All required HTTP hosts are available ]
my pubspec.yaml
name: yumor
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.16.1 <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:
cached_network_image: ^3.2.0
cloud_firestore: ^3.1.10
cupertino_icons: ^1.0.2
email_validator: ^2.0.1
firebase_auth: ^3.3.9
firebase_core: ^1.13.1
firebase_storage: ^10.2.15
flutter:
sdk: flutter
flutter_native_splash: ^2.2.9
flutter_svg: ^1.0.3
fluttertoast: ^8.0.9
get: ^4.6.5
image_picker: ^0.8.5
dev_dependencies:
flutter_lints: ^2.0.1
flutter_test:
sdk: flutter
flutter_native_splash:
background_image: assets/splashcreen.png
image: assets/start_logo.png
# 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/yumor-logo.png
- assets/search_page.svg
- assets/upload_page.svg
- assets/user.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
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:yumor/models/progress.dart';
import 'package:yumor/models/user_model.dart';
class profile extends StatefulWidget {
const profile({Key? key,required this.userProfile}) : super(key: key);
final String? userProfile;
#override
State<profile> createState() => _profileState();
}
class _profileState extends State<profile> {
final userRef = FirebaseFirestore.instance.collection('users');
final doc = await docRef.doc(docId).get();
if (doc.exists) {
data = doc.data();
}
buildprofileheader(){
return FutureBuilder( return FutureBuilder(future:doc,
builder: ((context, snapshot) {
if(!snapshot.hasData){
return CircularProgress();
}
UserModel user=UserModel.fromMap(Map);
return Padding(padding:EdgeInsets.all(16.0),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.account_circle, size: 90,)
],
),
Container(
alignment: Alignment.center,
padding: EdgeInsets.all(12.0),
child: Text(
user.Username as String,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize:16.0,
),
),
),
],
),
);
}),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
"Profile",
),
),
body: ListView(children: <Widget>[
// buildprofileHeader(),
]));
}
}

Cannot pass `arguments` through `onGenerateRoute()` in `null-safety` version of flutter

What am I trying to do?
As usual, I am trying to sending data from one screen to another onGenerateRoute() but I screen does not accept arguments type and showing error The argument type 'Object?' can't be assigned to the parameter type 'Map<String, dynamic>'.
I also tried to change the argument type Object? on the receiver screen but now I am not able to extract data from Object to Map<String, dynamic>. I think both are the same data type but the null-safety version is treated differently. I think this is a bug.
I have seen flutter official documentation for navigate-with-arguments and when I switched to null-safety in Interactive example section then it also showing error. See this screenshot or try it yourself.
It's working properly in the non-null-safety version of flutter
Here's the snippet
RouteGenerator Class
class RouteGenerator {
static Route<dynamic> generateRoute(RouteSettings settings) {
// Getting arguments passed while calling Navigator.pushNamed
final args = settings.arguments;
switch (settings.name) {
case HomeScreen.routeName:
return MaterialPageRoute(
builder: (context) => HomeScreen(),
);
case LoginScreen.routeName:
return MaterialPageRoute(
builder: (context) => LoginScreen(),
);
case VerifyFirebaseOtpScreen.routeName:
return MaterialPageRoute(
builder: (context) => VerifyFirebaseOtpScreen(data: args), // Here is the error: The argument type 'Object?' can't be assigned to the parameter type 'Map<String, dynamic>'.
);
case AboutScreen.routeName:
return MaterialPageRoute(
builder: (context) => AboutScreen(),
);
default:
return MaterialPageRoute(
builder: (context) => Scaffold(
body: SafeArea(
child: Center(
child: Text('No route defined for ${settings.name}'),
),
),
),
);
}
}
}
VerifyFirebaseOtpScreen
class VerifyFirebaseOtpScreen extends StatelessWidget {
static const String routeName = '/verify_firebase_otp_screen';
final Map<String, dynamic> data;
const VerifyFirebaseOtpScreen({
Key? key,
required this.data,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
FocusScope.of(context).unfocus();
},
child: Scaffold(
body: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(8.0),
child: Container(
width: double.infinity,
child: VerifyFirebaseOtpScreenDataSection(
mobile: '${data['mobile']}',
),
),
),
),
),
);
}
}
Logs
abhishekkumar#Abhisheks-MacBook-Air ~ % flutter doctor -v
[✓] Flutter (Channel beta, 2.1.0-12.2.pre, on macOS 11.2.3 20D91 darwin-x64, locale en-IN)
• Flutter version 2.1.0-12.2.pre at /Users/abhishekkumar/flutter
• Framework revision 5bedb7b1d5 (13 days ago), 2021-03-17 17:06:30 -0700
• Engine revision 711ab3fda0
• Dart version 2.13.0 (build 2.13.0-116.0.dev)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
• Android SDK at /Users/abhishekkumar/Library/Android/sdk
• Platform android-30, build-tools 30.0.2
• ANDROID_HOME = /Users/abhishekkumar/Library/Android/sdk
• Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
• All Android licenses accepted.
[✓] Xcode - develop for iOS and macOS
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 12.4, Build version 12D4e
• CocoaPods version 1.10.1
[✓] Chrome - develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
[✓] Android Studio (version 4.1)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
🔨 https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
[✓] VS Code (version 1.51.1)
• VS Code at /Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.17.0
[✓] Connected device (3 available)
• iPhone SE (1st generation) (mobile) • 035FA189-09FF-46B5-96AC-C34E8D068C21 • ios • com.apple.CoreSimulator.SimRuntime.iOS-14-4 (simulator)
• macOS (desktop) • macos • darwin-x64 • macOS 11.2.3 20D91 darwin-x64
• Chrome (web) • chrome • web-javascript • Google Chrome 89.0.4389.90
• No issues found!
Answer in short
Use typecast operator as
so above question's answer will be like final args = settings.arguments as Map<String, dynamic>;
Answer explanation
I also filed this question as an issue on GitHub and thanks to goderbauer (A Flutter Team Member) who identify correctly this issue and closed it by giving an appropriate solution.
goderbauer says
In your example settings.arguments is typed as Object? and you're passing it to VerifyFirebaseOtpScreen.data which is typed as Map<String, dynamic>. Prior to null-safety this was legal and is called an implicit downcast. But with null safety Dart has removed implicit downcast altogether (you can read more about that here https://dart.dev/null-safety/understanding-null-safety, just search for "implicit downcast" on the page). So now, if you're sure that settings.arguments is in deed of type Map<String, dynamic> you need to do an explicit cast, something like: settings.arguments as Map<String, dynamic>.
He also said
(The example on the page will have to be updated as well once we migrate them to null safety)
dart.dev explanation and example
Referred documentation page Understanding null-safety & using-nullable-types explanation also covering this.
Their below example is explain enough
// Without null safety:
requireStringNotObject(String definitelyString) {
print(definitelyString.length);
}
main() {
Object maybeString = 'it is';
requireStringNotObject(maybeString);
}
// Using null safety:
requireStringNotObject(String definitelyString) {
print(definitelyString.length);
}
main() {
Object maybeString = 'it is';
requireStringNotObject(maybeString as String);
}

testDeviceId's are not working in google-mobile-ads flutter

I was trying to set my test device id with the requestConfiguration. For checking whether setup for testdevice is successful, I filtered logcat in android studio with setTestDeviceIds but it's showing me the following log
2021-03-31 04:17:36.907 27185-27185/? I/Ads: Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("xxxxxxxxxxxxxxxxxxx")) to get test ads on this device.
So setting up for test device are not working and I can't test with real ads. As I'm passing testDeviceId's this log was supposed to not appear. You can see I'm passing testDeviceId's for both in RequestConfiguration and bannerAd.
Steps to reproduce
Here is my main.dart file
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:provider/provider.dart';
import 'package:us/global/theme/app_themes.dart';
import 'package:us/utils/ad_helper.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
MobileAds.instance.initialize().then((InitializationStatus status) {
print('Initialization done: ${status.adapterStatuses}');
MobileAds.instance
.updateRequestConfiguration(RequestConfiguration(
testDeviceIds: AdHelper.allTestDevices));
});
runApp(
MyApp()
);
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider<ThemeChanger>(
create: (_) => ThemeChanger(),
child: new MaterialAppWithTheme(),
);
}
}
class MaterialAppWithTheme extends StatelessWidget {
#override
Widget build(BuildContext context) {
final theme = Provider.of<ThemeChanger>(context);
return MaterialApp(
title: 'Const',
debugShowCheckedModeBanner: false,
theme: theme.getDarkTheme ? ThemeData.dark():ThemeData.light(),
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
static final AdRequest request = AdRequest(
testDevices: AdHelper.allTestDevices,
);
BannerAd _bannerAdd;
bool _isBannerAdLoaded = false;
Future<InitializationStatus> _initGoogleMobileAds() {
// TODO: Initialize Google Mobile Ads SDK
return MobileAds.instance.initialize();
}
#override
void initState() {
super.initState();
_bannerAdd = BannerAd(
adUnitId: AdHelper.homePageBannerAd,
size: AdSize.banner,
request: request,
listener: AdListener(
onAdLoaded: (_) { // Future<SharedPrefData> _setDarkMode(bool darkMode) async{
// SharedPreferences prefs = await SharedPreferences.getInstance();
// log.i('Current dark mode $darkMode.');
// await prefs.setBool('darkmode', darkMode);
// log.i('Dark mode toggled successfully');
// return await getPersistedData();
// }
setState(() {
_isBannerAdLoaded = true;
});
},
onAdFailedToLoad: (ad, error) {
// Releases an ad resource when it fails to load
ad.dispose();
print('Ad load failed (code=${error.code} message=${error.message})');
},
),
);
_bannerAdd.load();
}
#override
Widget build(BuildContext context) {
//this gonna give us total height and with of our device
return Scaffold(
// bottomNavigationBar: BottomNavBar(),
body: Stack(
children: <Widget>[
SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
this._isBannerAdLoaded? Container(
margin: EdgeInsets.only(bottom: 35),
height: 72.0,
alignment: Alignment.center,
child: AdWidget(ad: _bannerAdd),
):Text('')
],
),
),
)
],
),
);
}
}
Here is my adhelper.dart file
import 'dart:io';
class AdHelper{
static String TEST_BANNER_AD = "ca-app-pub-3940256099942544/6300978111";
static String get homePageBannerAd{
if(Platform.isAndroid){
return TEST_BANNER_AD;
}
else if(Platform.isIOS){
return TEST_BANNER_AD;
}
else
throw new UnsupportedError("Platform is not supported..");
}
static List<String> get allTestDevices{
String MY_REDMI_NOTE_9="xxxxxxxxxxx";
return [MY_REDMI_NOTE_9];
}
}
Flutter doctor
Run flutter doctor and paste the output below:
Click To Expand
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.0.1, on Linux, locale en_US.UTF-8)
[!] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
✗ Android license status unknown.
Run `flutter doctor --android-licenses` to accept the SDK licenses.
See https://flutter.dev/docs/get-started/install/linux#android-setup for more details.
[✓] Chrome - develop for the web
[✓] Android Studio (version 3.5)
[✓] IntelliJ IDEA Ultimate Edition (version 2020.2)
[✓] VS Code (version 1.54.3)
[✓] Connected device (2 available)
! Doctor found issues in 1 category.
Flutter dependencies
Run flutter pub deps -- --style=compact and paste the output below:
Click To Expand
Dart SDK 2.12.0
Flutter SDK 2.0.1
us_constitution 1.0.0+1
dependencies:
- dynamic_text_highlighting 2.2.0 [flutter]
- flutter 0.0.0 [characters collection meta typed_data vector_math sky_engine]
- flutter_svg 0.19.3 [flutter meta path_drawing vector_math xml]
- flutter_xlider 3.4.0 [flutter]
- google_mobile_ads 0.11.0+4 [meta flutter]
- logger 1.0.0
- path_provider 2.0.1 [flutter path_provider_platform_interface path_provider_macos path_provider_linux path_provider_windows]
- provider 5.0.0 [collection flutter nested]
- shared_preferences 2.0.5 [meta flutter shared_preferences_platform_interface shared_preferences_linux shared_preferences_macos shared_preferences_web shared_preferences_windows]
- sqflite 1.3.2+4 [flutter sqflite_common path]
- url_launcher 6.0.3 [flutter url_launcher_platform_interface url_launcher_linux url_launcher_macos url_launcher_windows url_launcher_web]
dev dependencies:
- flutter_test 0.0.0 [flutter test_api path fake_async clock stack_trace vector_math async boolean_selector characters charcode collection matcher meta source_span stream_channel string_scanner term_glyph typed_data]
transitive dependencies:
- async 2.5.0 [collection]
- boolean_selector 2.1.0 [source_span string_scanner]
- characters 1.1.0
- charcode 1.2.0
- clock 1.1.0
- collection 1.15.0
- convert 2.1.1 [charcode typed_data]
- fake_async 1.2.0 [clock collection]
- ffi 1.0.0
- file 6.1.0 [meta path]
- flutter_web_plugins 0.0.0 [flutter js characters collection meta typed_data vector_math]
- js 0.6.3
- matcher 0.12.10 [stack_trace]
- meta 1.3.0
- nested 1.0.0 [flutter]
- path 1.8.0
- path_drawing 0.4.1+1 [vector_math meta path_parsing flutter]
- path_parsing 0.1.4 [vector_math meta]
- path_provider_linux 2.0.0 [path xdg_directories path_provider_platform_interface flutter]
- path_provider_macos 2.0.0 [flutter]
- path_provider_platform_interface 2.0.0 [flutter meta platform plugin_platform_interface]
- path_provider_windows 2.0.0 [path_provider_platform_interface meta path flutter ffi win32]
- petitparser 3.1.0 [meta]
- platform 3.0.0
- plugin_platform_interface 1.0.3 [meta]
- process 4.1.0 [file path platform]
- shared_preferences_linux 2.0.0 [flutter file meta path path_provider_linux shared_preferences_platform_interface]
- shared_preferences_macos 2.0.0 [shared_preferences_platform_interface flutter]
- shared_preferences_platform_interface 2.0.0 [flutter]
- shared_preferences_web 2.0.0 [shared_preferences_platform_interface flutter flutter_web_plugins meta]
- shared_preferences_windows 2.0.0 [shared_preferences_platform_interface flutter file meta path path_provider_platform_interface path_provider_windows]
- sky_engine 0.0.99
- source_span 1.8.0 [charcode collection path term_glyph]
- sqflite_common 1.0.3+1 [synchronized path meta]
- stack_trace 1.10.0 [path]
- stream_channel 2.1.0 [async]
- string_scanner 1.1.0 [charcode source_span]
- synchronized 2.2.0+2
- term_glyph 1.2.0
- test_api 0.2.19 [async boolean_selector collection meta path source_span stack_trace stream_channel string_scanner term_glyph matcher]
- typed_data 1.3.0 [collection]
- url_launcher_linux 2.0.0 [flutter]
- url_launcher_macos 2.0.0 [flutter]
- url_launcher_platform_interface 2.0.1 [flutter plugin_platform_interface]
- url_launcher_web 2.0.0 [url_launcher_platform_interface meta flutter flutter_web_plugins]
- url_launcher_windows 2.0.0 [flutter]
- vector_math 2.1.0
- win32 2.0.0 [ffi]
- xdg_directories 0.2.0 [meta path process]
- xml 4.5.1 [collection convert meta petitparser]
In my case this works
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await MobileAds.instance.initialize().then((InitializationStatus status) {
print('Initialization done: ${status.adapterStatuses}');
MobileAds.instance.updateRequestConfiguration(
RequestConfiguration(
tagForChildDirectedTreatment:
TagForChildDirectedTreatment.unspecified,
testDeviceIds: <String>["list of test device ids seprated by ,(comas)"]),
);
});
runApp(MyApp());
}
you can do it like this
void main() async {
WidgetsFlutterBinding.ensureInitialized();
MobileAds.instance.initialize();
// thing to add
RequestConfiguration configuration = RequestConfiguration(testDeviceIds: ['E46609DD331AF2754D38B3DCE3ED011B']);
MobileAds.instance.updateRequestConfiguration(configuration);
runApp(const MyApp());
}

flutter SelectableLinkify - links not working

I'm using the flutter_linkify package, running on iOS.
I've got it working fine using the Linkify widget.
BUT when I use SelectableLinkify: links still show using the link style (blue underline) BUT links no longer load when clicked.
Any ideas on what might be wrong / how to debug?
Thank you!
code to replicate:
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_linkify/flutter_linkify.dart';
class TestingScreen extends StatefulWidget {
#override
_TestingScreenState createState() => _TestingScreenState();
}
class _TestingScreenState extends State<TestingScreen> {
_launchURL(String url) async {
if (await canLaunch(url)) {
await launch(url, forceWebView: true);
} else {
throw 'Could not launch $url';
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Center(
child: SelectableLinkify(
onOpen: (link) {
_launchURL(link.url);
},
text:
'I have an awesome website https://google.com',
),
),
),
);
}
}
Flutter Doctor output (note I'm not using VS Code so shouldn't impact this project!)
[✓] Flutter (Channel stable, v1.17.0, on Mac OS X 10.15.4 19E287, locale en-AU)
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
[✓] Xcode - develop for iOS and macOS (Xcode 11.3)
[✓] Android Studio (version 3.5)
[!] VS Code (version 1.40.2)
✗ Flutter extension not installed; install from
https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
[✓] Connected device (2 available)
! Doctor found issues in 1 category.

How to fix 'Safari cannot open the page...' error when signing in to google in flutter google sign in

The app just begin and I do the sign in first. It was both working on android and ios, but then later in fews day I resume to work on the app, the sign in only work on android.
On iOS, when I use google sign in, and it open a page to accounts.google.com i supposed, then it should ask for the email and password, but it didn't. It only say
Safari cannot open the page because it could not establish a secure connection to the server.
The output of flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel master, v1.5.9-pre.56, on Mac OS X 10.14.4 18E226, locale en-KH)
[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✓] iOS toolchain - develop for iOS devices (Xcode 10.2.1)
[!] Android Studio (version 3.2)
✗ Flutter plugin not installed; this adds Flutter specific functionality.
✗ Dart plugin not installed; this adds Dart specific functionality.
[✓] VS Code (version 1.33.1)
[✓] Connected device (1 available)
! Doctor found issues in 1 category.
The pubspec.yml
name: xxx
description: xxx
version: 0.0.1
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
google_sign_in: ^4.0.1+3
rxdart: ^0.21.0
corsac_jwt: ^0.1.2
graphql_flutter: ^1.0.0
qr_flutter: ^2.0.0
cupertino_icons: ^0.1.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/google.png
Here is the login_screen.dart
import 'package:flutter/material.dart' as flutter_material;
import 'package:flutter/cupertino.dart' show CupertinoButton;
import '../blocs/bloc_provider.dart' show BlocProvider;
import '../blocs/login_bloc.dart' show LoginBloc;
const String _loginInText = 'Sign In';
const String _googleIconPath = 'assets/google.png';
const double _iconWidth = 39.0;
const double _iconHeight = 39.0;
const double _sizedBoxWidth = 10.0;
const double _signInFontSize = 23.0;
class LoginScreen extends flutter_material.StatelessWidget {
#override
flutter_material.Widget build(flutter_material.BuildContext context) {
final LoginBloc loginBloc = BlocProvider.of<LoginBloc>(context);
return flutter_material.Scaffold(
body: flutter_material.Center(
child: CupertinoButton(
// splashColor: flutter_material.Colors.transparent,
child: flutter_material.Row(
mainAxisSize: flutter_material.MainAxisSize.min,
crossAxisAlignment: flutter_material.CrossAxisAlignment.center,
children: const <flutter_material.Widget>[
const flutter_material.Image(
image: flutter_material.AssetImage(_googleIconPath),
width: _iconWidth,
height: _iconHeight,
),
const flutter_material.SizedBox(width: _sizedBoxWidth, height: 0.0),
const flutter_material.Text(
_loginInText,
style: flutter_material.TextStyle(
fontSize: _signInFontSize,
),
),
],
),
onPressed: loginBloc.signIn,
),
),
);
}
}
the logic_bloc.dart
import 'package:google_sign_in/google_sign_in.dart'
show GoogleSignIn, GoogleSignInAccount, GoogleSignInAuthentication;
import 'package:rxdart/rxdart.dart' as rxdart;
import './bloc_provider.dart' show BlocBase;
class LoginBloc extends BlocBase {
final GoogleSignIn _gSignIn = GoogleSignIn(scopes: ['openid']);
final rxdart.PublishSubject<GoogleSignInAuthentication> _googleSignIn =
rxdart.PublishSubject<GoogleSignInAuthentication>();
rxdart.Observable<GoogleSignInAuthentication> get loginStream => this._googleSignIn.stream;
void signIn() async {
final GoogleSignInAccount account = await this._gSignIn.signIn();
if (account != null) {
this._googleSignIn.sink.add(await account.authentication);
}
}
void signOut() async {
await this._gSignIn.signOut();
this._googleSignIn.sink.add(null);
}
#override
void dispose() async {
await this._googleSignIn.drain();
this._googleSignIn.close();
}
}
So below are the actual result:
UPDATE 1: I also tested on example of the package. It also show cannot connect to the page
In the iOS Simulator
Settings > Developer > Allow HTTP Services (turn on);
Restart Xcode and simulator.