I would like to support Dart snippets in VS Code. I'd also like to do so using something like the Snippet Creator (https://github.com/nikitaKunevich/vscode-snippet-creator) but this doesn't seem to work as 'dart' is not a language option. Is it possible to add 'dart' as an option so that I can use the snippet creator to have snippets in '*.dart' files?
control+shift+p >snippets > dart.json add this code
{
"stateless": {
"prefix": "fless",
"body": [
"import 'package:flutter/material.dart';",
"class $1 extends StatelessWidget {",
"\t#override",
"\tWidget build(BuildContext context) {",
"\t\treturn Container(",
"\t\t\t$2",
"\t\t);",
"\t}",
"}"
]
},
"stateful": {
"prefix": "ffull",
"body": [
"import 'package:flutter/material.dart';",
"class $1 extends StatefulWidget {",
"\t#override",
" \t_$1State createState() => _$1State();",
"}",
"class _$1State extends State<$1> {",
" \t#override",
" \tWidget build(BuildContext context) {",
"\t\treturn Container(",
" \t\t\t$2",
"\t\t);",
"\t}",
"} "
]
}
}
//control+shift+p >snippets > dart.json add this code
Related
I have this list of maps, and i need to get the 'transactions' value:
final assets = [
{
"name": "BRL", "balance": 150.2,
"transactions" : Transaction(from: "someone", amount: 1)
},
{
"name": "US", "balance": 1100.2,
"transactions" : Transaction(from: "someone", amount: 5)
},
];
i tried to do assets[0]['transactions'], but all i got was null or Instance of 'Transaction'
the class:
class Transaction {
final String id = Random().toString();
final String from;
final double amount;
Transaction({
required this.from,
required this.amount,
});
}
im kinda newbie, then pls help me :)
You can use this dartpad example to view this in an app
Assuming you would like to show your data in a list (since this is a list of maps per the question)
class MyWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ListView.builder(
shrinkWrap: true,
itemCount: assets.length,
itemBuilder: (context, index) {
Transaction data = assets[index]['transactions'];
return
ListTile(
leading: Text(data.amount.toString()),
title: Text(data.from.toString()));
});
}
}
I'm a bit at loss here.
return MaterialApp(
title: 'App Title',
theme: ThemeData(brightness: Brightness.dark),
initialRoute: '/',
routes: SOMETHING_HERE,
);
I want to push SOMETHING_HERE from a different file, but I can't seem to push a correct value there.
Other file (attempt):
import '../screens/home.dart';
import '../screens/charts.dart';
class Routes {
factory Routes(context) {
Map<String, Widget Function(BuildContext)> _routes;
_routes = {
'/': (context) => ScreenHome(),
'/charts': (context) => ScreenCharts(),
};
return _routes;
}
}
This doesn't work cause it says:
The argument type 'Routes' can't be assigned to the parameter type 'Map<String, (BuildContext) → Widget>'
OF course I can just pass a Map to this argument but I want to define my routes in a separate file.
Any suggestions on how to accomplish this?
I just had the same problem and found the solution.
You don't need to create a class, just create a var that equals your routes Map
main.dart:
import 'package:flutter/material.dart';
import './custom_routes.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(brightness: Brightness.dark),
initialRoute: '/',
routes: customRoutes,
);
}
}
custom_routes.dart:
import 'package:flutter/material.dart';
import '../screens/home.dart';
import '../screens/charts.dart';
var customRoutes = <String, WidgetBuilder>{
'/': (context) => ScreenHome(),
'/charts': (context) => ScreenCharts(),
};
**
There is another way you can try if you wish
**
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: LoginScreen.id,
routes: route,
);
},
}
Create your route dart file. No need to create a class
var route = <String, WidgetBuilder>{
LoginScreen.id: (_) => const LoginScreen(),
// call the classes
Dashboard.id: (_) => const Dashboard(),
// with value
Dashboard.id: (_) => const Dashboard(value: ''),
};
If you don't use call by id. You can do that as well. Also you can pass values shown example
Just create any function with return of Map<String, WidgetBuilder>, here i will show how to do that with pass data to your routes class:
1- Create new file routes.dart, this full code (i used my custom variables like serverToken, notifierThemeMode) to fully explain the process:
import 'package:rxdart/rxdart.dart';
import 'package:flutter/material.dart';
import 'package:path/to/home_screen.dart';
import 'package:path/to/login_screen.dart';
class AppRoutes{
// get initial route
static getInitialRoute({String? serverToken}){
return serverToken == null
? LoginScreen.routeName
: HomeScreen.routeName;
}
// get all app routes
static Map<String, WidgetBuilder> getRoutes({
required BehaviorSubject<ThemeMode?> notifierThemeMode,
required BehaviorSubject<Locale?> notifierLocale,
}){
return {
HomeScreen.routeName: (BuildContext context) => HomeScreen(
notifierThemeMode: notifierThemeMode,
),
LoginScreen.routeName: (BuildContext context) => LoginScreen(
notifierLocale: notifierLocale,
),
}
}
2- In MaterialApp widget call the previous functions:
MaterialApp(
...
routes: AppRoutes.getRoutes(
notifierThemeMode: _notifierThemeMode,
notifierLocale: _notifierLocale
),
initialRoute: AppRoutes.getInitialRoute(
serverToken: _appServerToken
),
);
I'm Trying to apply BLoC pattern on my code which is simply generate categories to grid View , but some how it's not working although I did the same in this article but without using api instead I used local Json File.
here is the Category_Model
class CategoryModel {
List<_Category> _Categories = [];
CategoryModel.fromJson(Map<String, dynamic> parsedJson) {
print(parsedJson['Categories'].length);
List<_Category> temp = [];
for (int i = 0; i < parsedJson['Categories'].length; i++) {
//_Category is the constructor of _Category Class line number 21
_Category category = _Category(parsedJson['Categories'][i]);
temp.add(category);
}
_Categories = temp;
}
List<_Category> get categories => _Categories;
}
class _Category {
int _id;
String _name;
String _iconPath;
_Category(category) {
_id = category['id'];
_name = category['name'];
_iconPath = category['iconPath'];
}
int get id => _id;
String get name => _name;
String get iconPath => _iconPath;
}
and here where it's comming null
Future<CategoryModel> fetchCategoryList() async {
final jsonCategory = await rootBundle.loadString("assets/CategoryList.json");
final mapJsonCategory = Map.from(jsonDecode(jsonCategory));
return CategoryModel.fromJson(mapJsonCategory);
}
here is the Category_List.dart
import 'package:flutter/material.dart';
import '../blocs/category_bloc.dart';
import '../models/category_model.dart';
class CategoryList extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return CategoryListState();
}
}
class CategoryListState extends State<CategoryList> {
#override
void initState() {
super.initState();
bloc.fetchAllCategoryList();
}
#override
void dispose() {
bloc.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Mazaya'),
),
body: StreamBuilder(
stream: bloc.allCategories,
builder: (context, AsyncSnapshot<CategoryModel> snapshot) {
if (snapshot.hasData) {
return buildList(snapshot);
} else if (snapshot.hasError) {
return Text(snapshot.error.toString());
}
return Center(child: CircularProgressIndicator());
},
),
);
}
Widget buildList(AsyncSnapshot<CategoryModel> snapshot) {
return GridView.builder(
itemCount: snapshot.data.categories.length,
);
}
}
JSON FILE
{
"Categories": [
{
"id": 1,
"name": "Restruants",
"iconPath": " "
},
{
"id": 2,
"name": "Car Rental",
"iconPath": " "
},
{
"id": 3,
"name": "Furniture",
"iconPath": " "
},
{
"id": 4,
"name": "cars",
"iconPath": " "
},
{
"id": 5,
"name": "Maintenance",
"iconPath": " "
},
{
"id": 6,
"name": "Education",
"iconPath": " "
},
{
"id": 7
"name": "Finess",
"iconPath": " "
},
{
"id": 8,
"name": "Electronics",
"iconPath": " "
},
{
"id": 9,
"name": "Medical",
"iconPath": " "
},
{
"id": 10,
"name": "Entirtainment",
"iconPath": " "
}
]
}
I expected the result will lock like the app in this article https://medium.com/flutterpub/architecting-your-flutter-project-bd04e144a8f1
Hi First of all correct your json by adding comma after number 7 like this => "id": 7,
Then change fetchMovieList() method in MovieApiProvider as below where we get file from asset with the help of "DefaultAssetBundle":
Future<ItemModel> fetchMovieList(BuildContext context) async {
// final jsonCategory = await rootBundle.loadString("assets/CategoryList.json");
final jsonCategory = await DefaultAssetBundle
.of(context)
.loadString('assets/CategoryList.json');
print(jsonCategory);
final mapJsonCategory = Map<String, dynamic>.from(jsonDecode(jsonCategory));
print(mapJsonCategory);
return ItemModel.fromJson(mapJsonCategory);
}
Then declare your json file in pubspec.yaml as below:
# 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
assets:
- assets/CategoryList.json
Then change buildList method in your dart file as below:
Widget buildList(AsyncSnapshot<ItemModel> snapshot) {
return GridView.builder(
itemCount: snapshot.data.categories.length,
gridDelegate:
new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemBuilder: (BuildContext context, int index) {
return Text(snapshot.data.categories[index].name);
});
}
It will work :)
I used flutter_i18n plugin (Android Studio) to generate i18n.dart(class S) and S.of(context).locale_msg will return the locale string. The main code is shown below.
Language should be changed programmatically by invoking onLocaleChange(locale) when click the button in HomePage. It works well in Android simulator, but won't change language in iOS simulator. Wonder what's wrong with my code?
class _PaperMoonAppState extends State<PaperMoonApp> {
SpecifiedLocalizationDelegate _localeOverrideDelegate;
void onLocaleChange(Locale locale) {
setState(() {
if (appVars.appConfig.changeLanguage(locale)) {
_localeOverrideDelegate = new SpecifiedLocalizationDelegate(locale);
appVars.saveConfig(); //print save config file...
}
});
}
#override
void initState() {
SpecifiedLocalizationDelegate.onLocaleChange = this.onLocaleChange;
appVars.loadConfig().then((AppConfig _config) {
appVars.appConfig = _config;
setState(() {
_localeOverrideDelegate =
new SpecifiedLocalizationDelegate(appVars.appConfig.getLocale());
});
});
_localeOverrideDelegate =
new SpecifiedLocalizationDelegate(Locale('zh', ''));
super.initState();
}
#override
Widget build(BuildContext context) {
print(_localeOverrideDelegate.overriddenLocale);
return MaterialApp(
debugShowCheckedModeBanner: false,
title: "Paper Moon",
color: Colors.blueAccent,
localizationsDelegates: [
_localeOverrideDelegate,
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate
],
supportedLocales: const <Locale>[
Locale("ja", ""),
Locale("en", ""),
Locale("zh", ""),
],
localeResolutionCallback:
S.delegate.resolution(fallback: _localeOverrideDelegate.overriddenLocale),
home: HomePage(),
// routes: _buildRoutes(),
);
}
}
Custom LocalizationDelegate:
class SpecifiedLocalizationDelegate
extends LocalizationsDelegate<WidgetsLocalizations> {
//class static vars:
//onLocaleChange should be bind to MaterialApp function containing setState().
static LocaleChangeCallback onLocaleChange;
// for instance
final Locale overriddenLocale;
const SpecifiedLocalizationDelegate(this.overriddenLocale);
#override
bool isSupported(Locale locale) => overriddenLocale != null;
#override
Future<WidgetsLocalizations> load(Locale locale) =>
S.delegate.load(overriddenLocale);
#override
bool shouldReload(SpecifiedLocalizationDelegate old) => true;
}
Based on your code, the only thing that seems to be missing is this:
open ios/Runner/Info.plist and add:
<key>CFBundleLocalizations</key>
<array>
<string>ja</string>
<string>en</string>
<string>zh</string>
</array>
As far I as know, by now (march/2019), flutter doesn't yet add automatically the list of supported languages to this file.
I'm using i18n_extensions, but with the same issue...
What worked for me, was use this:
supportedLocales: const <Locale>[
const Locale('en'),
const Locale('pt'),
],
Instead of this:
supportedLocales: const <Locale>[
const Locale('en', 'US'),
const Locale('pt', 'BR'),
],
And then, my i18n.dart. file i've change from this:
extension Localization on String {
static final _t = Translations.from("en_us", {
passwordInput: {
"en_us": "Password",
"pt_br": "Senha",
},
searchingTitle: {
"en_us": "Scanning for devices...",
"pt_br": "Procurando dispositivos...",
},
...
To this:
extension Localization on String {
static final _t = Translations.from("en", {
passwordInput: {
"en": "Password",
"pt": "Senha",
},
searchingTitle: {
"en": "Scanning for devices...",
"pt": "Procurando dispositivos...",
},
It works fine for me.
I am creating a flutter app with blocs.
I followed the code available in Flutter login with blocs
It works as expected,
if my app has no routes defined
class App extends StatelessWidget {
Widget build(BuildContext context) {
return Provider(
child: MaterialApp(
title: 'Log Me In!',
home: Scaffold(
body: LoginScreen(),
),
),
);
}
}
but when I change my app to use routes
class App extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
title: 'Log Me In!',
routes: {
'/':(context) => Provider(
child: Scaffold(
body: LoginScreen(),
),
)
},
);
}
}
bloc code
class Bloc extends Object with Validators {
final _email = BehaviorSubject<String>();
final _password = BehaviorSubject<String>();
// retrieve data from stream
Stream<String> get email => _email.stream.transform(validateEmail);
Stream<String> get password => _password.stream.transform(validatePassword);
Stream<bool> get submitValid => Observable.combineLatest2(email, password, (e, p) => true);
// add data to stream
Function(String) get changeEmail => _email.sink.add;
Function(String) get changePassword => _password.sink.add;
submit() {
final validEmail = _email.value;
final validPassword = _password.value;
print('$validEmail and $validPassword');
}
dispose() {
_email.close();
_password.close();
}
}
Observable.combileLatest2 is not streaming the data (but it streams error though).
Using Rxdart version 0.19.0 and
Flutter 1.0.0 • channel beta •https://github.com/flutter/flutter.git
Framework • revision 5391447fae (6 days ago) • 2018-11-29 19:41:26-0800
Engine • revision 7375a0f414Tools • Dart 2.1.0 (build 2.1.0-dev.9.4 f9ebf21297)
Am I doing something wrong here?
thanks in advance
After lot of trial, I found that when I use routes for the navigation, flutter will build the page multiple times and thats the expected behavior refer here for detailed answer
So when it builds the page multiple times, it was creating multiple Observables on the bloc as it was creating new instance of Bloc every time it creates the Page route.
So when I modify the code
class App extends StatelessWidget {
final login = Provider(
child: Scaffold(
body: LoginScreen(),
),
);
Widget build(BuildContext context) {
return MaterialApp(
title: 'Log Me In!',
routes: {
'/':(context) => login,
},
);
}
}
it worked perfectly.
The other way is to achieve is to create a stateful widget and do the initialization in the init method.