I have been using Geocoder-0.1.2, from starting, and it did not cause me any problem. I have just upgraded my flutter and while running my project, I get this error:
Compiler message:
file:///Users/alok/flutter/.pub-cache/hosted/pub.dartlang.org/geocoder-0.1.2/lib/services/d
istant_google.dart:38:56: Error: The argument type 'Utf8Decoder' can't be assigned to the
parameter type 'StreamTransformer<Uint8List, dynamic>'.
- 'Utf8Decoder' is from 'dart:convert'.
- 'StreamTransformer' is from 'dart:async'.
- 'Uint8List' is from 'dart:typed_data'.
Try changing the type of the parameter, or casting the argument to
'StreamTransformer<Uint8List, dynamic>'.
final responseBody = await response.transform(utf8.decoder).join();
^
Compiler failed on /Users/alok/MyProjects/newmonkapp/lib/main.dart
Error launching application on iPhone 7.
Since the error shows it is in the main.dart, there is no code related to that, I have doubled checked it. Here you go.
main.dart
import 'package:flutter/material.dart';
void main() => runApp(NewMonkApp());
class NewMonkApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
print("in the main builder");
return MaterialApp(
title: 'XYZ',
debugShowCheckedModeBanner: false,
theme: ThemeData(
backgroundColor: Color.fromRGBO(249, 249, 251, 1),
fontFamily: 'SF Pro',
primaryColor: Color.fromRGBO(253, 92, 99, 1),
textTheme: TextTheme(
headline: TextStyle(
fontSize: 34.0, fontWeight: FontWeight.bold,
color: Color.fromRGBO(64, 72, 82, 1)
)
)
),
initialRoute: "/",
routes: {
"/": (context) => InitPage(),
// "/": (context) => SearchFilterPage()
}
);
}
}
And it exits the application. Don't know what the problem is, and how should I fix this. I have tried to google it, seems like couldn't find a better solution for this. Any help would be appreciated.
Flutter Doctor results:
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel master, v1.8.1-pre.44, on Mac OS X 10.14.5 18F132, locale en-US)
[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✓] Xcode - develop for iOS and macOS (Xcode 10.2.1)
[✓] iOS tools - develop for iOS devices
[✓] Chrome - develop for the web
[!] Android Studio (version 3.4)
✗ Flutter plugin not installed; this adds Flutter specific functionality.
✗ Dart plugin not installed; this adds Dart specific functionality.
[✓] Connected device (3 available)
! Doctor found issues in 1 category.
Any help would be appreciated. Thanks :)
change this line final response = await request. close().
to
final response = await request.close().then((response){ response.cast>().transform(utf8.decoder).listen((content) { return content; }); });
This worked for me😘
Inside flutter plugins, geocoder and file name distant_google.dart
Related
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.
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);
}
Hi I have spent a couple of days on trying to figure out why my user looses there "session" on my app when I close the app. How do I keep them signed in or what might cause this?
I am running the app on my google pixel 5 using the simulator option on android studio.
yaml file:
firebase_core: ^0.4.0+9
firebase_auth: ^0.14.0+9
cloud_firestore: ^0.13.6
firebase_storage: 3.1.6
firebase_messaging: 6.0.16
firebase_crashlytics: 0.1.4+1
This is what I can see in my logs (Not helpful much):
D/FlutterLocationService(32338): Unbinding from location service.
D/FlutterLocationService(32338): Destroying service.
D/FlutterLocationService(32338): Creating service.
D/FlutterLocationService(32338): Binding to location service.
flutter doctor -v:
(base) darrendupreez#Darrens-MacBook-Pro unavine_app % flutter doctor
-v [✓] Flutter (Channel dev, 1.26.0-12.0.pre, on macOS 11.1 20C69 darwin-x64, locale en-CA)
• Flutter version 1.26.0-12.0.pre at /Applications/flutter
• Framework revision a706cd2112 (2 weeks ago), 2021-01-14 18:20:26 -0500
• Engine revision effb529ece
• Dart version 2.12.0 (build 2.12.0-224.0.dev)
[✓] Android toolchain - develop for Android devices (Android SDK
version 30.0.3)
• Android SDK at /Users/darrendupreez/Library/Android/sdk
• Platform android-30, build-tools 30.0.3
• Java binary at: /Users/darrendupreez/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/201.7042882/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
[✓] Android Studio (version 4.1)
• Android Studio at /Users/darrendupreez/Library/Application Support/JetBrains/Toolbox/apps/AndroidStudio/ch-0/201.7042882/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)
[✓] Connected device (1 available)
• Pixel 5 (mobile) • 0C161FDD4000DT • android-arm64 • Android 11 (API 30)
• No issues found!
Providers and AuthCreditental should work here is an example for google login with firebase
main.dart
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return Provider(
create: (context) => AuthBloc(),
child: MaterialApp(
title: 'Your App',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: MaterialColor(0xff360A36, color),
accentColor: Colors.limeAccent,
),
//darkTheme: ThemeData.dark(),
home: LogInPage(),
),
);
}
}
auth_bloc.dart
class AuthBloc {
final authService = AuthService();
final googleSignin = GoogleSignIn(scopes: ['email']);
Stream<User> get currentUser => authService.currentUser;
loginGoogle() async {
try {
final GoogleSignInAccount googleUser = await googleSignin.signIn();
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
idToken: googleAuth.idToken, accessToken: googleAuth.accessToken);
//Firebase Sign in
final result = await authService.signInWithCredential(credential);
print('${result.user.displayName}');
} catch (error) {
print(error);
}
}
logout() {
authService.logout();
googleSignin.signOut();
}
sign in button
SignInButton(
Buttons.Google,
text: "Sign in with Google",
onPressed: () => authBloc.loginGoogle(),
),
Also you can watch this tutorial for using credentials and providers
https://www.youtube.com/watch?v=_uYO2ht5Nl4&list=PL19w2HZFNl2BsftambzhFE7tVrqGEVwzy&index=1&t=1924s
You can use shared_preferences: ^0.5.12+4 to save the session.Just check whether it is null or not. And when you need you can update the data with new login.
Sample:
SharedPreferences prefs = await SharedPreferences.getInstance(); int counter = (prefs.getInt('counter') ?? 0) + 1; print('Pressed $counter times.');
Firebase auth automatically manage the auth state for your project but you have to access that auth state in your project to keep user data in the application.
You can use the authStateChange function to make it work.
Stream<User> get currentUser => _auth.authStateChanges();
And the user state in your main function using the Provider Package. Also wrap your `MaterialApp()' function by the following code:
MultiProvider(
providers: [
StreamProvider<User>.value(
value: Auth().currentUser,
)
],
child: GetMaterialApp()
)
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.
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.