Dart http package is not working in built apk - flutter

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

Related

pub.dev - my package not showing platforms correctly (web missing)

I developed a flutter package multi_image_picker_view:
https://pub.dev/packages/multi_image_picker_view
This package depends on file_picker and flutter_reorderable_grid_view, they both support the Web. But in my package, web option is not visible in pub.dev. Even this package works fine on the web.
👉Help me to figure out why WEB is not showing on pub.dev.
📜My pubspec.yaml
name: multi_image_picker_view
description: A complete widget that can easily pick multiple images from a device and display them in UI. Also picked image can be re-ordered and removed easily.
version: 0.0.6
homepage: https://github.com/shubham-gupta-16/multi_image_picker_view
repository: https://github.com/shubham-gupta-16/multi_image_picker_view
issue_tracker: https://github.com/shubham-gupta-16/multi_image_picker_view/issues
environment:
sdk: ">=2.17.1 <3.0.0"
flutter: ">=1.17.0"
dependencies:
flutter:
sdk: flutter
flutter_reorderable_grid_view: ^3.1.3
file_picker: ^5.0.1
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
flutter:
assets:
- packages/multi_image_picker_view/assets/close-48.png
👨‍💻Commands I used to publish
flutter pub publish
🗃️My Matchine Info
Flutter Version: 3.0.1
Channel: Stable
Dart Version: 2.17.1
IDE: Android Studio Chipmunk | 2021.2.1 Patch 1
🚀You can find the complete code Github:
https://github.com/shubham-gupta-16/multi_image_picker_view
Thank you in advance.
Conditional import required
The reason why this package is not showing Web on pub.dev is that it uses dart.io without conditional import.
To fix this, I separated the file where it is used. One for web and one for non-web platforms. Then import them by using conditions based on the running platform.
web_preview.dart
import 'package:flutter/material.dart';
import '../image_file.dart';
class ImagePreview extends StatelessWidget {
final ImageFile file;
const ImagePreview({Key? key, required this.file}) : super(key: key);
#override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(4),
child: Image.memory(
file.bytes!,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) {
return const Center(child: Text('No Preview'));
},
),
);
}
}
non_web_preview.dart
import 'dart:io'; // here I imported dart:io
import 'package:flutter/material.dart';
import '../image_file.dart';
class ImagePreview extends StatelessWidget {
final ImageFile file;
const ImagePreview({Key? key, required this.file}) : super(key: key);
#override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(4),
child: Image.file(
File(file.path!), // Now I can use File class
fit: BoxFit.cover,
),
);
}
}
my_package_file.dart
...
import 'non_web_preview.dart' if (dart.library.html) 'web_preview.dart'; // conditional import
class MyPackageFile extends StatelessWidget {
...
#override
Widget build(BuildContext context) {
return ImagePreview(file: imageFile); // Using ImagePreview class
}
}

How to disable appbar on splashscreen

Hi how do i disable appbar from loading during splash screen flutter? I tried adding it into scaffold only but still the same.
import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:connectivity/connectivity.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:double_back_to_close_app/double_back_to_close_app.dart';
import 'package:onesignal_flutter/onesignal_flutter.dart';
Future main() async {
runApp(new MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _outputText = "";
#override
void initState() {
super.initState();
initOneSignal();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: IndexedStack(
index: 0,
children: <Widget>[
InAppWebViewPage(),
Container(
child: Text(_outputText),
)
],
));
}
Future<void> initOneSignal() async {
await OneSignal.shared
.init("xxxxxxxxxxxxxxxxxxxxxxxxxxx", iOSSettings: null);
OneSignal.shared
.setInFocusDisplayType(OSNotificationDisplayType.notification);
OneSignal.shared
.setNotificationReceivedHandler((OSNotification notification) {
this.setState(() {
_outputText =
"Received notification: \n${notification.jsonRepresentation().replaceAll("\\n", "\n")}";
});
});
}
}
class InAppWebViewPage extends StatefulWidget {
#override
_InAppWebViewPageState createState() => new _InAppWebViewPageState();
}
class _InAppWebViewPageState extends State<InAppWebViewPage> {
InAppWebViewController webView;
int _page = 2;
bool _loadError = false;
StreamSubscription<ConnectivityResult> subscription;
#override
initState() {
super.initState();
subscription = Connectivity()
.onConnectivityChanged
.listen((ConnectivityResult result) {
if (result != ConnectivityResult.none && webView != null) {
print("reload");
_loadError = false;
webView.reload();
}
});
}
#override
dispose() {
super.dispose();
subscription.cancel();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: IndexedStack(
index: _page,
children: <Widget>[
Container(
child: InAppWebView(
initialUrl: "www.google.com",
initialHeaders: {},
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
userAgent: Platform.isIOS
? 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_1_2 like Mac OS X) AppleWebKit/605.1.15' +
' (KHTML, like Gecko) Version/13.0.1 Mobile/15E148 Safari/604.1'
: 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Mobile Safari/537.36',
clearCache: false,
debuggingEnabled: true,
),
),
onWebViewCreated: (InAppWebViewController controller) {
webView = controller;
},
onLoadStart: (InAppWebViewController controller, String url) {},
onLoadStop: (InAppWebViewController controller, String url) {
print(url);
setState(() {
if (!_loadError) {
_page = 0;
} else {
_page = 1;
}
});
},
onLoadError: (InAppWebViewController controller, String url,
int code, String message) async {
print("error $url: $code, $message");
_loadError = true;
},
onLoadHttpError: (InAppWebViewController controller, String url,
int statusCode, String description) async {
print("HTTP error $url: $statusCode, $description");
},
),
),
(Platform.isAndroid)
? Container(
child: Text("My custom error message"),
)
: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/splash.png'),
fit: BoxFit.fitWidth,
),
)),
Container(
color: Colors.transparent,
decoration: BoxDecoration(
image: DecorationImage(
image: ExactAssetImage('assets/images/splash.png'),
fit: BoxFit.fitWidth,
),
),
),
],
),
);
}
}
I already tried searching for a few answer but i cant seem to find the one related to flutter. Do you guys know where should i put the appbar so it wont show on splash screen? Thank in advance!
Below is my pubspec.yaml as requested :
name: testing_app
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: "none" # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+2
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
flutter_inappwebview: ^3.4.0
connectivity: ^2.0.2
double_back_to_close_app: ^2.0.1
onesignal_flutter: ^2.0.0
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter_launcher_icons: "^0.8.0"
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- assets/images/
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
flutter_icons:
android: "launcher_icon"
ios: true
image_path: "assets/images/icon.png"

When assembleDebug Out of Memory error is thrown

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

Unable to change the suggestions of AutoCompleteTextField

Problem Description -
I am writing a search widget which is an AutoCompletTextField. It takes the queryString entered by the user and fetches related suggestions from the internet and then attaches those suggestions to the AutoCompleteTextField. Everything till fetching the suggestions from the internet is working just fine. The suggestions are not popping up when I call the setState() method of the widget. The suggestions don't pop up even after the call to setState(). Please help.
Code -
`import 'package:flutter/material.dart';
import 'miscellaneous_widgets.dart';
import 'models/AppContextData.dart';
import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'workers/MCAutoSuggestionsGetter.dart';`
class CompanySearchBox extends StatefulWidget {
#override
_CompanySearchBoxState createState() => _CompanySearchBoxState();
}
class _CompanySearchBoxState extends State<CompanySearchBox> {
GlobalKey<AutoCompleteTextFieldState<String>> key =
GlobalKey<AutoCompleteTextFieldState<String>>();
List<String> lstSuggestions = List<String>();
TextEditingController companySearchBoxController = TextEditingController();
#override
Widget build(BuildContext context) {
AutoCompleteTextField<String> myCompanySearchBox;
TextEditingController CompanyNameController = TextEditingController();
myCompanySearchBox = AutoCompleteTextField<String>(
key: key,
clearOnSubmit: false,
style: TextFieldStyle.get(),
decoration: InputDecoration(
labelText: "Search companies here.",
//border: OutlineInputBorder(),
suffixIcon: Icon(Icons.search),
),
submitOnSuggestionTap: true,
suggestions: lstSuggestions,
textChanged: (queryString){
if(queryString.length >= 3)
queryCompanyNames(queryString);
},
itemBuilder: (context,item){
return Center(
heightFactor: 1,
child: Column(
children: <Widget>[
ListTile(
contentPadding: EdgeInsets.all(2.0),
title: Text(
item,
style: TextRegularStyle.get()),
),
Divider(color: Colors.blueGrey,)
],)
);
},
itemFilter: (item,queryString ){
if(item.toLowerCase().startsWith(queryString.toLowerCase()))
return true;
},
itemSorter: (item1, item2){
return item1.toLowerCase().compareTo(item2.toLowerCase());
},
itemSubmitted: (SelectedItem){
//Not doing here anything as of now.
},
);
//myCompanySearchBox.textField.controller = CompanyNameController,
return myCompanySearchBox;
}
queryCompanyNames(String queryString) async
{
/*Calling the MCAutoSuggestionsGetter which fetches the suggestions from the internet. This step is working fine. We are getting a List<String> in "Suggestions" variable below. But when setState() is called, the previous "lstSuggestions" should be cleared and new "Suggestions" should be added. And these newly added suggestions should be displayed. But I am unable to achieve this.*/
MCAutoSuggestionsGetter.fetchSuggestions(queryString).then((Suggestions){
setState((){
lstSuggestions.clear();
lstSuggestions.addAll(Suggestions);
});
});
}
}
My pubspec.yaml -
name: dev1_stock_meter
description: A new Flutter application.
version: 1.0.0+1
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
firebase_core: ^0.2.5+1
firebase_auth: ^0.7.0
fluttertoast: ^3.0.4
autocomplete_textfield: ^1.6.4
html: ^0.13.3+3
http: ^0.12.0
date_format: ^1.0.6
cupertino_icons: ^0.1.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- images/logo.jpg
fonts:
- family: GoogleSans
fonts:
- asset: fonts/GoogleSans-Regular.ttf
weight: 300
- asset: fonts/GoogleSans-Bold.ttf
weight: 400
Expected Behaviour:
The expected behaviour is when the user types a string that is more than 3 characters long, the suggestions should be fetched from internet and these suggestions should be attached to the AutoCompletTextField and the suggestions should be displayed.

How to get build and version number of Flutter app

I am currently developing an application which is currently in beta mode. Due to this, I would like to show them what version they are on. For example, "v1.0b10 - iOS". So far, I have got this code: Text("Build: V1.0b10 - " + (Platform.isIOS ? "iOS" : "Android")). How would I be able to get the build version and number within flutter?
You can use package_info_plus.
The versions are extracted from:
Android:
build.gradle, versionCode and versionName
iOS:
Info.plist, CFBundleVersion
Usage
Add the dependency
Add this to your package's pubspec.yaml file:
dependencies:
package_info_plus: ^1.0.6
Import the file into your dart file:
import 'package:package_info_plus/package_info_plus.dart';
if your method is marked as async:
PackageInfo packageInfo = await PackageInfo.fromPlatform();
String appName = packageInfo.appName;
String packageName = packageInfo.packageName;
String version = packageInfo.version;
String buildNumber = packageInfo.buildNumber;
If you don't want to use await/async:
PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
String appName = packageInfo.appName;
String packageName = packageInfo.packageName;
String version = packageInfo.version;
String buildNumber = packageInfo.buildNumber;
});
Note: This answer has been updated to reflect the fact that the package_info plugin is deprecated and redirects to package_info_plus.
Version name and build number
At development time, you can easily find the version name and build number of a Flutter or Dart project by inspecting pubspec.yaml. Here is an example:
version: 1.1.0+2
This is case the version name is 1.1.0 and the build number is 2.
However, if you want to get these values at runtime, you should use a plugin.
Add the dependency
In pubspec.yaml add the package_info_plus package.
dependencies:
package_info_plus: ^1.0.2
Update the version number to the current one.
Import the package
In the file that you need it, add the following import.
import 'package:package_info_plus/package_info_plus.dart';
Get the version name and code
In your code you can get the app version name and code like this:
PackageInfo packageInfo = await PackageInfo.fromPlatform();
String version = packageInfo.version;
String code = packageInfo.buildNumber;
See also
How to set build and version number of Flutter app
How to get build and version number of Flutter Web app
install package_info_plus, then you can use it directly with future builder in your widget tree:
FutureBuilder<PackageInfo>(
future: PackageInfo.fromPlatform(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.done:
return Align(
alignment: Alignment.bottomCenter,
child: Text(
'Version: ${snapshot.data!.version}',),
);
default:
return const SizedBox();
}
},
),
RE the multiple references to package_info, please note that this package has been deprecated and the recommended replacement is the Flutter Community Plus Plugins version, package_info_plus.
You can try new_version plugin. Using this plugin you can get installed App Version, Playstore App Version and app url which can redirect to playstore.
New Version Plugin
void versionCheck() async {
final NewVersion newVersion = NewVersion(context: context);
VersionStatus versionStatus = await newVersion.getVersionStatus();
if (versionStatus != null && versionStatus.canUpdate) {
await ConfirmDialog(
context: context,
title: 'Update Available',
body: Text('A new version, ${versionStatus.storeVersion}, is available.'),
acceptButton: 'Update Now',
cancelButton: 'Update Later'
).then((ConfirmAction res) async {
if (res == ConfirmAction.CONFIRM && await canLaunch(versionStatus.appStoreLink)) {
await launch(versionStatus.appStoreLink, forceWebView: false);
}
});
}
}
Custom Alert Dialog Box
enum ConfirmAction{ CONFIRM, CANCEL }
Future<ConfirmAction> ConfirmDialog({
BuildContext context,
String title,
Widget body,
String acceptButton,
String cancelButton
})
=> showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) => AlertDialog(
title: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 4,
children: <Widget>[
Text(title)
],
),
content: Wrap(
runSpacing: 10,
children: <Widget>[
body,
],
),
actions: <Widget>[
FlatButton(
padding: EdgeInsets.all(6),
child: Text(acceptButton ?? 'Confirm'),
onPressed: (){
Navigator.of(context, rootNavigator: true).pop(ConfirmAction.CONFIRM);
}
),
FlatButton(
padding: EdgeInsets.all(6),
child: Text(cancelButton ?? 'Cancel'),
onPressed: (){
Navigator.of(context, rootNavigator: true).pop(ConfirmAction.CANCEL);
}
),
],
)
);
For using it from command line or CLI, you need a pure Dart code.
I used the following script:
// ignore_for_file: avoid_print
import 'dart:io';
import 'package:path/path.dart';
import 'package:yaml/yaml.dart';
String pathToYaml = join(dirname(Platform.script.toFilePath()), '../pubspec.yaml');
Future<YamlMap> loadPubspec() async => loadYaml(await File(pathToYaml).readAsString());
void main() async {
var pubspec = await loadPubspec();
print(pubspec['version'].toString().split('+')[0]);
}
You can run it from the project root folder:
dart run scripts/get_version_name.dart
In Flutter mobile applications the version number is in pubspec.yaml file. like below:
version: 1.0.0+1
To get the version name and code, add the package_info dependency into pubspec.yaml file, like below:
dependencies:
package_info: ^0.4.0+16
And
import 'package:package_info/package_info.dart'; // import the package_info
Future<void> _initPackageInfo() async {
final _packageInfo = await PackageInfo.fromPlatform();
setState(() {
String AppName = _packageInfo.appName;
String PackageName = _packageInfo.packageName;
String AppVersion = _packageInfo.version;
String BuildNumber = _packageInfo.buildNumber;
String BuildSignature = _packageInfo.buildSignature;
});
}