I am a new learner of android app development with Flutter framework. I am trying to load a JSON file from asset and show the data by listview. It's working with development mode (flutter run) but when I build the apk and install it on my android phone the JSON file is not loading and no data showing on my app.
flutter build apk
flutter install
I have tried with this code.
import 'package:flutter/material.dart';
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
import 'dart:convert';
void main() {
runApp(new MaterialApp(
home: new HomePage(),
));
}
class HomePage extends StatefulWidget {
#override
HomePageState createState() => new HomePageState();
}
class HomePageState extends State<HomePage> {
List data;
Future<String> loadZipCodes() async {
var jsonString = await rootBundle.loadString('assets/data/cse.json');
data = JSON.decode(jsonString);
print(data[1]);
return 'success';
}
#override
void initState() {
this.loadZipCodes();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Home'),
),
body: new ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index) {
return new Card(
child: new Container(
padding: new EdgeInsets.all(15.0),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Text(data[index]["sort_term"],style: new TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold)),
new Text(data[index]["long_term"])
])));
},
));
}
}
Please help me to figure out what is the problem going on. Thanks in advance.
give this permission in app>main>AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET">
set internet permission in the above file
Related
I have a screen in flutter SearchFoodItemPage It is a stateful widget in a file named search_food_item_page.dart.
My purpose is to fetch list of items from firebase and display it on this screen.
I want to fetch data from firebase when this screen starts. I want to do all the data fetching in this file.
For that I tried fetching data in build method of the the widget. But we cannot add async modifier to the build method hence it did not work. I would like to know where to build the data source for this purpose.
Below is the code snippet for this screen.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart'; // new
import 'package:firebase_auth/firebase_auth.dart'; // new
class SearchFoodItemPage extends StatefulWidget {
SearchFoodItemPage({Key? key, required this.title}) : super(key: key);
final String title;
#override
_SearchFoodItemPageState createState() => _SearchFoodItemPageState();
}
class _SearchFoodItemPageState extends State<SearchFoodItemPage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
List<String> _adsList = [];
/////////////////////////////////////////////////////////////// code for building data source
print("****************************************************************************");
await FirebaseFirestore.instance
.collection('ads')
.get()
.then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
print(doc["_iname"]);
_adsList.add( doc["_iname"] as String );
});
});
print('${_adsList.length}');
for (final foodname in _adsList) {
print('${foodname.toString()}');
}
///////////////////////////////////////////////////////////////
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// AdvertisementForm(),
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Thanks!
You're looking for a FutureBuilder as shown in the FlutterFire documentation on reading data using get and the example of using a ListView in that same page:
#override
Widget build(BuildContext context) {
return FutureBuilder<QuerySnapshot>(
future: FirebaseFirestore.instance.collection('ads').get(),
builder:
(BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text("Something went wrong");
}
if (snapshot.connectionState == ConnectionState.done) {
return new ListView(
children: snapshot.data.docs.map((DocumentSnapshot document) {
Map<String, dynamic> data = document.data() as Map<String, dynamic>;
return new ListTile(
title: new Text(data['_iname']),
);
}).toList(),
);
}
return Text("loading");
},
);
}
Actually today I decided to make a love calculator and for that I learnt the http call in flutter but now I am stuck at a point and I don't know how to move onwards.
import 'package:AllInOneCalci/Post.dart';
import 'package:AllInOneCalci/customAppBar.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async';
class LoveCalUI extends StatelessWidget {
#override
Widget build(BuildContext context) {
var AppBarHeight = MediaQuery.of(context).size.height;
return Scaffold(
appBar: customAppBar(
height: (AppBarHeight / 3) * 0.4,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(top: 18.0),
child: Text(
'All In One Cali',
style: TextStyle(
color: Colors.black,
fontSize: 35.0,
fontFamily: 'DancingScript',
fontWeight: FontWeight.bold),
),
),
],
),
),
body: CustomFetchData(),
);
}
}
class CustomFetchData extends StatefulWidget {
#override
_CustomFetchDataState createState() => _CustomFetchDataState();
}
class _CustomFetchDataState extends State<CustomFetchData> {
Future<Post> getData() async {
final response =
await http.get('https://love-calculator.p.rapidapi.com/getPercentage?fname=John&sname=Alice');
if (response.statusCode == 200) {
return Post.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load api');
}
}
#override
Widget build(BuildContext context) {
return Column(
children: [
Container(
child: FutureBuilder<Post>(
future: getData(),
builder: (BuildContext context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Text('Please Wait while its loading...'));
} else {
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else {
return Center(
child: Text('${snapshot.data}'),
);
}
}
})),
],
);
}
#override
// ignore: must_call_super
void initState() {
getData();
}
}
This is a lovecalculator class where I am coding all the stuffs. If there is any NEWS website, where the data is fetching from the api call then it will be very easy.
But I want that I enter two names in the text field and the process is now calculated through api i.e the logic is written at the backend and I want to fetch that logic into my code ()given that I HAVE TO ENTER THE NAMES. Can you help me please. I have given that api reference here. If anyone could help me, then it will be very supporting.
api reference- https://rapidapi.com/ajith/api/love-calculator
I assume that you already can use text field controllers and extract text. The thing you needed to include to your request are headers which include important key information.
If you look here, you can find reference for several languages request example (for example I used Swift for reference). Below you can see how to do it in Flutter:
In your pubspec.yaml
http: ^0.12.2
In your .dart file you need to import
import 'dart:convert';
import 'package:http/http.dart' as http;
Also you need to pick a place which would call a function, in my case it was a button from default Flutter starter project:
Map<String, String> requestHeaders = {
'x-rapidapi-host': 'love-calculator.p.rapidapi.com',
'x-rapidapi-key': 'insert your API key from website',
};
void _getNames({String name1, String name2}) async {
final response = await http.get(
'https://love-calculator.p.rapidapi.com/getPercentage?fname=$name1&sname=$name2',
// Send authorization headers to the backend.
headers: requestHeaders,
);
final responseJson = json.decode(response.body);
print(responseJson);
}
I am trying to integrate Braintree Plugin but I am getting error. Can anyone help me?
I have to enable PayPal that's the reason I am using Braintree plugin. But I am confused about how to integrate this plugin with the server. There is nothing mention in the plugin.
import 'package:flutter/material.dart';
import 'package:braintree_payment/braintree_payment.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Barintree Payment',
theme: ThemeData(primaryColor: Colors.teal),
home: Payment(),
);
}
}
class Payment extends StatefulWidget {
#override
_PaymentState createState() => _PaymentState();
}
class _PaymentState extends State<Payment> {
String clientNonce="h0dHBzOi8vcGF5bWVudHMuc2FuZGJveC5icmFpbnRyZWUtYXBpLmNvbJpbnQiOiJlNTc1Mjc3MzZiODkyZGZhYWFjOTIxZTlmYmYzNDNkMzc2ODU5NTIxYTFlZmY2MDhhODBlN2Q5OTE5NWI3bCI6Imh0dHBzOi8vYXBpLnNhbmRib3guYnJhaW50cmVlZ2F0ZXdheS5jb206NDQzL21lcmNoYW50cy8zNDhwazljZ2YzYmd5dzJiL2NsaWVudF9hcGkiLCJhc3NldHNVcmwiOiJodHRwczovL2Fzc2V0cy5icmFpbnRyZWVnYXRld2F5LmNvbSIsImF1dGhVcmwiOiJodHRYTJjfGNyZWF0ZWRfYXQ9MjAxOS0wNS0yMFQwNzoxNDoxNi4zMTg0ODg2MDArMDAwMFx1MDAyNm1lcmNoYW50X2lkPTM0OHBrOWNnZjNiZ3l3MmJcdTAwMjZwdWJsaWNfa2V5PTJuMjQ3ZHY4OWJxOXZtcHIiLCJjb25maWdVcmwiOiJodHRwczovL2FwaS5zYW5kYm94LmJyYWludHJ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kIjp0cnVlLCJtZXJjaGFudEFjY291bnRJZCI6ImFjbWV3aWRnZXRzbHRkc2FuZGJveCIsImN1cnJlbmN5SXNvQ29kZSI6IlVTRCJ9LCJtZXJjaGFudElkIjoiMzQ4cGs5Y2dmM2JneXcyYiIsInZlbm1vIjoib2ZmIn0=";
proceedPayNow() async {
BraintreePayment braintreePayment = new BraintreePayment();
var data = await braintreePayment.showDropIn(
nonce: clientNonce, amount: "5.0", enableGooglePay: true);
print("Payment responce $data");
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Pay"),
),
body: Center(
child: FlatButton(
onPressed: payNow,
color: Colors.teal,
child: Text(
"Proceed to Payment",
style: TextStyle(color: Colors.white),
),
),
),
);
}
}
Error
Response of the payment {message: BraintreeBrowserSwitchActivity missing,
incorrectly configured in AndroidManifest.xml or another app defines the same
browser switch url as this app.
Can anyone help me please how Can I integrate it or any other way to integrate Paypal?
I am trying to make an app which opens up a PPT, PDF or Docx file using the default application on the device by tapping on a button in my application. If there is no default app, it should open the "Open With" menu.
I tried to use open_file. But it didn't work. I also tried a few other methods I saw on StackOverflow, but none of them worked for me.
To open file on Internet you can use package https://pub.dev/packages/url_launcher
code snippet for url_launcher
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
void main() {
runApp(Scaffold(
body: Center(
child: RaisedButton(
onPressed: _launchURL,
child: Text('Open File'),
),
),
));
}
_launchURL() async {
const url = 'https://yoursite/sample.pdf';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
To open file in local path
You can see working demo and full code below
code snippet
final filePath = '/sdcard/Download/sample.pdf';
print('${filePath}');
final message = await OpenFile.open(filePath);
full code
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:open_file/open_file.dart';
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _openResult = 'Unknown';
Future<void> openFile() async {
final filePath = '/sdcard/Download/sample.pdf';
print('${filePath}');
final message = await OpenFile.open(filePath);
setState(() {
_openResult = message;
});
}
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('open result: $_openResult\n'),
FlatButton(
child: Text('Tap to open file'),
onPressed: openFile,
),
],
),
),
),
);
}
}
Emulator SDCard Download directory has a pdf file
working demo
I would like to make an endlessFeed in Fluter but the app terminates without giving me any information why. Basically it happens after I scrolled down about 60 images then it starts to lag a bit and it crashes.
I tested another API but the same there. It uses images with lower resolution so it takes longer to scroll down until it stops working.
So I don't know what happens here. My guess is that there are to many images in the ListView so that the phone can't handle it and crashes.
I've put the whole code below because I don't even know wehere the problem could be. Is there maybe another way to achieve an endlessImageFeed?
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:cached_network_image/cached_network_image.dart';
// my base url
String imageUrl = "http://192.168.2.107:8000";
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'EndlessFeed',
theme: ThemeData(
primaryColor: Colors.white,
),
home: PhotoList(),
);
}
}
class PhotoList extends StatefulWidget {
#override
PhotoListState createState() => PhotoListState();
}
class PhotoListState extends State<PhotoList> {
StreamController<Photo> streamController;
List<Photo> list = [];
#override
void initState() {
super.initState();
streamController = StreamController.broadcast();
streamController.stream.listen((p) => setState(() => list.add(p)));
load(streamController);
}
load(StreamController<Photo> sc) async {
// URL for API
String url = "http://192.168.2.107:8000/api/";
/* ______________________________________________
I also tried another API but it chrashes also (but it takes longer until crash):
String url = "https://jsonplaceholder.typicode.com/photos/";
______________________________________________ */
var client = new http.Client();
var req = new http.Request('get', Uri.parse(url));
var streamedRes = await client.send(req);
streamedRes.stream
.transform(UTF8.decoder)
.transform(json.decoder)
.expand((e) => e)
.map((map) => Photo.fromJsonMap(map))
.pipe(sc);
}
#override
void dispose() {
super.dispose();
streamController?.close();
streamController = null;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("EndlessFeed"),
),
body: Center(
child: ListView.builder(
itemBuilder: (BuildContext context, int index) => _makeElement(index),
),
),
);
}
Widget _makeElement(int index) {
if (index >= list.length) {
return null;
}
return Container(
child: Padding(
padding: EdgeInsets.only(top: 20.0),
child: Column(
children: <Widget>[
child: new Container(
// my base URL + one image
child: new Image(image: new CachedNetworkImageProvider(imageUrl + list[index].mImage))
),
),
],
),
));
}
}
class Photo {
final String mImage;
Photo.fromJsonMap(Map map)
: mImage= map['mImage'];
}