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?
Related
i try to scrape web site to grab some data (Titles) then store it inside a liste of string to use later in my text widget,but the problem is there is no data inside my list why that?
this is my code
// ignore: prefer_const_constructors
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:html/parser.dart';
import 'package:http/http.dart' as http;
import 'package:weatherapp/Test/datapars.dart';
class DataP extends StatelessWidget {
List dataa = [];
void htmlGrab() async {
var uri = Uri.parse('example.com');
var respons = await http.get(uri);
var doc = parse(respons.body);
final className =
doc.getElementsByClassName('WidePostCard_postTitle__SRltQ');
for (final data in className) {
dataa.add(data.text);
}
}
#override
Widget build(BuildContext context) {
print(dataa);
return Container(
alignment: Alignment.center,
child: Text(
'ddddddddddddd',
style: TextStyle(fontSize: 20),
),
);
}
}
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);
});
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
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);
}
I would like to pass a function through the constructor of a class. but when i call it, nothing happening. debug write: func : {_Closure}
import 'package:flutter/material.dart';
void main() {
runApp(Myclass(func: myfunction()));
}
class Myclass extends StatelessWidget {
final Function func;
Myclass({#required this.func});
#override
Widget build(BuildContext context) {
/* some code here */
this.func(); // <----- don't call myfunction() ! :(
}
}
myfunction()
{
/* some code here */
}
Thank you for the help
You don't passing your function in method, just its result. Check this line:
runApp(Myclass(func: myfunction()));
Using brackets you tell your program "do myfunction, return the result and put it in args". just use myfunction without brackets like that:
runApp(Myclass(func: myfunction));
Try this.
class CsCommonButtonWidget extends StatefulWidget {
const CsCommonButtonWidget(
{required this.onPressed,
required this.titleText,
this.titleTextAlign = TextAlign.center});
final Function? onPressed;
final String titleText;
final TextAlign titleTextAlign;
#override
_CsCommonButtonWidgetState createState() => _CsCommonButtonWidgetState();
}
class _CsCommonButtonWidgetState extends State<CsCommonButtonWidget> {
#override
Widget build(BuildContext context) {
return ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.red, padding: const EdgeInsets.all(CsDimens.SPACE16)),
child: Text(widget.titleText,style: TextStyle(fontSize: CsDimens.SPACE14),),
onPressed: () {
widget.onPressed!();
},
);
}
}
Usage
CsCommonButtonWidget(
onPressed: () {
print("Login clicked");
},
titleText: "Login"),