¿How to read local json files in flutter? - json

I've read many posts where someone explains how to do it, but in my case, it's not working and I'm not sure why, I've added the right folder to the pubspec.yaml and everything, this is my code
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:flutter/cupertino.dart';
import 'package:workout_time/Widgets/routines_widget.dart';
void main() => runApp(WorkoutTime());
class WorkoutTime extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Great App',
home: Scaffold(
body: RoutinesWidget(),
),
);
}
}
class RoutinesWidget extends StatefulWidget {
#override
_RoutinesWidgetState createState() => _RoutinesWidgetState();
}
class _RoutinesWidgetState extends State<RoutinesWidget> {
#override
Widget build(BuildContext context) {
return Center(
child: FutureBuilder(
future: rootBundle.loadString("assets/data.json"),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
var myData = jsonDecode(snapshot.data.toString());
return Center(
child: Text(myData == null ? "Nothing here" : myData),
);
},
),
);
}
}
when I run it, I get the CircularProgressIndicator widget, meaning that the snapshot has no data. Can anyone help me?
Edit: here is the part in the pubspec.yaml where I import the folder:
assets:
- assets/
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg

Code - pubspec.yaml
assets:
- assets/json/
Code - In a Class
static Map<dynamic, dynamic> jsonData;
loadJson() async {
String jsonContent = await rootBundle.loadString("assets/json/data.json");
jsonData = json.decode(jsonContent);
}

Related

Flutter: Expected a value of type 'Map<String, dynamic>', but got one of type 'List<dynamic>'

I am new to flutter, having the background of React and React Native.
I am trying to fetch data from jsonplaceholder and want to return the json body on the screen, through a List. I have an ImageModel class for moedling the data on screen.
This is my ImageModel class
class ImageModel {
int id;
String url;
String title;
// Model class constructor
ImageModel({this.id, this.url, this.title});
ImageModel.fromJson(Map<String, dynamic> parsedJson) {
id = parsedJson['id'];
url = parsedJson['url'];
title = parsedJson['title'];
}
}
My ImageList component is as:
import 'package:flutter/material.dart';
import '../models/image_model.dart';
class ImageList extends StatelessWidget {
final List<ImageModel> images;
ImageList(this.images);
#override
Widget build(context) {
return ListView.builder(
itemCount: images.length,
itemBuilder: (context, int index) {
return Text(images[index].url);
},
);
}
}
and my app component which renders all the data to main screen.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'models/image_model.dart';
import 'widgets/image_list.dart';
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return MyAppState();
}
}
class MyAppState extends State<MyApp> {
int counter = 0;
List<ImageModel> images = [];
fetchImage() async {
var response = await http
.get(Uri.parse('https://jsonplaceholder.typicode.com/photos'));
var imagemodel = ImageModel.fromJson(jsonDecode(response.body));
setState(() {
images.add(imagemodel);
});
}
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: ImageList(images),
appBar: AppBar(
title: Text("Let's See some Images!"),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: fetchImage,
),
),
debugShowCheckedModeBanner: false,
);
}
}
and main.dart file
import 'package:flutter/material.dart';
import 'src/app.dart';
void main() {
runApp(MyApp());
}
The debug console i get after pressing the ActionButton
Error: Expected a value of type 'Map<String, dynamic>', but got one of type 'List<dynamic>'
at Object.throw_ [as throw] (http://localhost:58266/dart_sdk.js:5333:11)
at Object.castError (http://localhost:58266/dart_sdk.js:5304:15)
at Object.cast [as as] (http://localhost:58266/dart_sdk.js:5620:17)
at dart.LegacyType.new.as (http://localhost:58266/dart_sdk.js:7218:60)
at app$.MyAppState.new.fetchImage (http://localhost:58266/packages/stephen_flutter/src/app.dart.lib.js:290:88)
at fetchImage.next (<anonymous>)
at http://localhost:58266/dart_sdk.js:39031:33
at _RootZone.runUnary (http://localhost:58266/dart_sdk.js:38888:58)
at _FutureListener.thenAwait.handleValue (http://localhost:58266/dart_sdk.js:33874:29)
at handleValueCallback (http://localhost:58266/dart_sdk.js:34434:49)
at Function._propagateToListeners (http://localhost:58266/dart_sdk.js:34472:17)
at _Future.new.[_completeWithValue] (http://localhost:58266/dart_sdk.js:34314:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:58266/dart_sdk.js:34337:35)
at Object._microtaskLoop (http://localhost:58266/dart_sdk.js:39175:13)
at _startMicrotaskLoop (http://localhost:58266/dart_sdk.js:39181:13)
at http://localhost:58266/dart_sdk.js:34688:9
After clicking the floatingActionButton i am directed to this file and at cursor moves to line 58
And why the execution stops as the Debug Control show (which i have underlined),
Please click this link to see the screenshot
Anyone would love to help?
I think the problem is with fetchImage method. In JSON response you get a list of objects and in this method you are trying to create a single object from that list.
So you would need to convert that json into a list of ImageModels. You can achieve it using map method.
final decodedJson = jsonDecode(response.body) ;
final imageModels = decodedJson.map((image) => ImageModel.fromJson(image)).toList();
Then, when you want to add them to a list, use addAll method:
setState(() {
images.addAll(imageModels);
});

Flutter for Linux: display HTML asset file in the app

Is there currently in flutter any way to display/load an HTML file from the assets folder in an application for linux? I have been researching for a while but to no avail. I have no code example, since all the approaches I have found are targeted for android and iOS. If anyone knows of an accessible way or a workaround, thank you in advance.
For Linux (desktop) looks like the flutter_html package works too (even if it is still not indicated at pub.dev). So what I did it's the following: I loaded the file from the rootBundle, that is, from my assets folder and parsed it to a Document object. After that, I just got the outerHtml String and passed it as a parameter to an Html Widget from the flutter_html package, as mentioned.
So if you want to give this a try, make sure you have your assets folder correctly set and store the HTML file in it. I took an example HTML file from: https://filesamples.com/formats/html.
After that, make sure you set your dependencies at pubspec.yaml (choose the versions that fit you best):
dependencies:
flutter:
sdk: flutter
html: any # Add this
flutter_html: ^1.3.0 # Add this
Still at pubspec.yaml: set the reference to your assets folder.
flutter:
uses-material-design: true
assets: # Add this
- assets/ # Add this
Then place this code in your main.dart and run it:
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:html/parser.dart' show parse;
import 'package:html/dom.dart' as dom;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Load on Linux for desktop'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
void initState() {
getHtml();
super.initState();
}
Future<dom.Document> getHtml() async {
return parse(await rootBundle.loadString('assets/sample1.html'));
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder<dom.Document>(
future: getHtml(),
builder:
(BuildContext context, AsyncSnapshot<dom.Document> snapshot) {
if (snapshot.hasData) {
return Html(data: snapshot.data.outerHtml);
} else {
return Center(
child: Text("Loading"),
);
}
}),
);
}
}
If needed, these are my OS details.
NAME="Ubuntu" VERSION="18.04.5 LTS (Bionic Beaver)" ID=ubuntu
ID_LIKE=debian PRETTY_NAME="Ubuntu 18.04.5 LTS" VERSION_ID="18.04"

Calling a widget with a function as a parameter in Flutter

I am trying to call a custom widget that has a function as a parameter, however I got no clue what parameter I could assign to it. I have tested all the ideas I came up with but with no success. The idea for this, I have gained from a tutorial, however I have done some things differently, as I have different requirements.
This is my code:
import 'package:flutter/material.dart';
class NewTransaction extends StatelessWidget {
final Function addTx;
const NewTransaction({Key? key, required this.addTx}) : super(key: key);
#override
Widget build(BuildContext context) {
return Text('I cant solve this problem');
}
}
========================================================================
import 'package:flutter/material.dart';
import 'package:function_parameter_problem/new_transaction.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
NewTransaction(
addTx:
addTx), // What parameter can/should I pass here? It is crucial for my project
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Edit: Okay, but let's say that the NewTransaction() function returnes a scaffold with appbar, etc and I have to call it again, however in the following scenario:
_wykonajZapytanie() { //function called onPressed in the main window
Navigator.push(
context,
MaterialPageRoute(builder: (context) => NewTransaction()),
); /*I have to put a parameter here, but I just want to display another window, I don't know why, but I just can't get any ideas*/
}
IMPORTANT TO NOTICE In the original project, if it comes to the first example I have provided, I do not call NewTransaction(addTx...) in the main class, but in the UserTransaction class.
tldr I need to assemble an expandable list in the main class - which can be done the way below from what I know, but also I need to call this function in the the main class on the onPressed of a button to display all of the textfields, etc.
import 'package:flutter/material.dart';
import './new_transaction.dart';
import './transaction_list.dart';
import '../models/transaction.dart';
class UserTransaction extends StatefulWidget {
#override
_UserTransactionState createState() => _UserTransactionState();
}
class _UserTransactionState extends State<UserTransaction> {
final List<Transaction> _userTransactions = [
Transaction(
id: 1,
date: DateTime.now(),
numTel: 911911911,
// scoring: 'Link wygasł',
user: 'Polizei pau pau'),
Transaction(
id: 2,
date: DateTime.now(),
numTel: 911911911,
// scoring: 'Link wygasł',
user: 'Tha police')
];
void _addNewTransaction(int txNumTel, /* String txScoring,*/ String txUser) {
final newTx = Transaction(
numTel: txNumTel,
/*scoring: txScoring,*/
user: 'PLZ WORK',
date: DateTime.now(),
id: 3,
);
setState(() {
_userTransactions.add(newTx);
});
}
#override
Widget build(BuildContext context) {
return Column(children: <Widget>[
NewTransaction(_addNewTransaction),
]);
}
}
import 'package:flutter/material.dart';
class NewTransaction extends StatelessWidget {
final VoidCallback function;
//if nothing returns
//else typedef CustomFunc = Function(int param); (replace int with your data type)
const NewTransaction({Key? key, required this.function}) : super(key: key);
#override
Widget build(BuildContext context) {
return InkWell(
child: Text('I cant solve this problem'),
onTap:function,
//if custom
//onTap: (){
// function(params);
//}
);
}
}
Call like below...
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
NewTransaction(
function: (){
//todo
},
//if custome function: (params){ todo },
)
],
),
),
If I understood your question correctly, this is the way you can pass a function with parameters:
import 'package:flutter/material.dart';
class NewTransaction extends StatelessWidget {
final Function() addTx;
const NewTransaction({Key? key, required this.addTx}) : super(key: key);
#override
Widget build(BuildContext context) {
return Text('I cant solve this problem');
}
}
When passing this Function, make sure to pass it like this: NewTransaction(addTx: () => addTx());. If you pass it like this: NewTransaction(addTx: addTx()); the function gets called instantly.
When you sayFunction addTx it means any function can be passed.
If Function() addTx it means function with no parameter.
If Function(int) addTx it means function with one required positional parameter integer.
If void Function() addTx it means function with no parameter and return type should be void.
In flutter you can also use
VoidCallback which is basically void Function() written like this
final VoidCallback addTd.
.
or can use ValueChanged<T> which is basically void Function(T value)
More info at:
https://dart.dev/guides/language/language-tour#functions

Flutter how to format http get value

Hi good day i have a value enum in my mysql pending and done i want to display in my flutter app the the first letter is capitalize like Pending or if if it is done Done
Text('Status:\t' + x.status,
style: TextStyle(
fontSize: 25.0,
fontWeight: FontWeight.bold,
color: x.status == 'pending'
? Colors.red
: Colors.green)),
Check out this example that I have created.
import 'package:flutter/material.dart';
import 'capitalize.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: SampleApp(),
debugShowCheckedModeBanner: false,
);
}
}
class SampleApp extends StatefulWidget {
#override
_SampleAppState createState() => _SampleAppState();
}
class _SampleAppState extends State<SampleApp> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Your heading'),
),
body: Container(
child: Column(
children: <Widget>[
Text("someString".capitalize())
],
)));
}
}
This is the dart file: capitalize.dart
extension StringExtension on String {
String capitalize() {
return "${this[0].toUpperCase()}${this.substring(1)}";
}
}
for the extension to work you should have sdk at minimum at 2.7.0 in pubspec.yaml
environment:
sdk: ">=2.7.0 <3.0.0"
even if you face any problem for undefined class extension then check the below link
Flutter extension-methods not working, it says "undefined class" and "requires the extension-methods language feature"

How should I call loaded Localization json data in second dart file?

I have a 3 JSON files under lib/resources/lang/. I also have demo_localizations.dart (based on: https://github.com/anilcancakir/flutter-internationalization) file under lib/. I also have a second_page.dart under lib/drawer. When I call second_page.dart I don’t get any localization on the second page.
The en, ru, and tr JSON file example:
{ "greetings": "Hello world", "secondPageTitle": "Second Page" }
{ "greetings": "Привет мир", "secondPageTitle": "Вторая страница"}
{ "greetings": “Merhaba Dünya”, "secondPageTitle": “Sayfa İki“}
This is the part of the main page localisation as:
new Text(DemoLocalizations.of(context).trans('greetings’)),
And this is my second_page.dart code:
import 'package:flutter/material.dart';
import '../demo_localizations.dart';
class SecondPage extends StatefulWidget {
#override
_SecondPageState createState() => new _SecondPageState();
}
class _SecondPageState extends State<SecondPage> {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Second Page'),
),
body: new Center(
// TODO: This part is not working
child: new Text(DemoLocalizations.of(context).trans('secondPageTitle')),
// TODO: This is working without using DemoLocalizations
//child:new Text('Second Page'),
),
);
}
}
And this is my demo_localizations.dart code:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
class DemoLocalizations {
DemoLocalizations(this.locale);
final Locale locale;
static DemoLocalizations of(BuildContext context) {
return Localizations.of<DemoLocalizations>(context, DemoLocalizations);
}
Map<String, dynamic> _sentences;
Future<bool> load() async {
String data = await rootBundle.loadString('resources/lang/${this.locale.languageCode}.json');
this._sentences = json.decode(data);
return true;
}
String trans(String key) {
return this._sentences[key];
}
}
class DemoLocalizationsDelegate extends LocalizationsDelegate<DemoLocalizations> {
const DemoLocalizationsDelegate();
#override
bool isSupported(Locale locale) => ['tr', 'en', 'ru'].contains(locale.languageCode);
#override
Future<DemoLocalizations> load(Locale locale) async {
DemoLocalizations localizations = new DemoLocalizations(locale);
await localizations.load();
print("Load ${locale.languageCode}");
return localizations;
}
#override
bool shouldReload(DemoLocalizationsDelegate old) => false;
}
How should I call loaded Localization JSON data in the second dart file?