I have this code:
void main() {
print('Hello!');
runApp(
MaterialApp(
home: Container(color: Colors.greenAccent)
)
);
}
When I reformat this code it becomes:
void main() {print('Hello!');runApp(MaterialApp(home:Container(color:Colors.greenAccent)));
}
I would like have:
void main() {
print('Hello!');
runApp(
MaterialApp(
home: Container(color: Colors.greenAccent)
)
);
}
How can I reformat like that ?
Add trailing commas like on this example: https://flutter.dev/docs/development/tools/formatting
So your code would become:
void main() {
print('Hello!');
runApp(
MaterialApp(
home: Container(color: Colors.greenAccent), , // <----- comma
), // <----- comma
);
}
Related
Which one is the equivalent of this Provider code to Riverpod?
runApp(MultiProvider(
providers: [ChangeNotifierProvider(create: (context) => UserProvider())],
child: const MyApp()));
I tried this, but it doesn't work:
runApp(const ProviderScope(
child: MyApp()));
And also this piece of code:
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Pomodoro timer',
theme: ThemeData(
unselectedWidgetColor: Colors.white,
textTheme: GoogleFonts.nunitoTextTheme(Theme.of(context).textTheme),
useMaterial3: true,
colorScheme:
const ColorScheme.light(primary: ColorsToAPP.selectText)),
home:
Provider.of<UserProvider>(context).user.token.isNotEmpty
? const StackePages()
: const Profile()
);
}
How to “translate” this to RiverPod?:
home:
Provider.of<UserProvider>(context).user.token.isNotEmpty
? const StackePages()
: const Profile()
);
Thanks
i am making an app that contains a button which when pressed will open a website that streams video . i have used flutter inappwebview plugin and i want to use content blockers too in my code.after searching i got some codes but i am getting errors that says some part in my code isnt define.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
final Uri _url = Uri.parse('https://zoro.to');
Future<void> _launchUrl() async {
if (!await launchUrl(_url)) {
throw Exception('Could not launch $_url');
}
}
// Future main() async {
// WidgetsFlutterBinding.ensureInitialized();
//
// if (Platform.isAndroid) {
// await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);
// }
//
// runApp(new animflix());
// }
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
if (!kIsWeb &&
kDebugMode &&
defaultTargetPlatform == TargetPlatform.android) {
await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(
kDebugMode);
}
runApp(const MaterialApp(home: animflix()));
}
// void main() {
// runApp(const animflix());
// }
class animflix extends StatelessWidget {
const animflix({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'anime',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: anime(),
);
}
}
class anime extends StatefulWidget {
const anime({Key? key}) : super(key: key);
#override
State<anime> createState() => _animeState();
}
class _animeState extends State<anime> {
final GlobalKey webViewKey = GlobalKey();
final adUrlFilters = [
".*.doubleclick.net/.*",
".*.ads.pubmatic.com/.*",
".*.googlesyndication.com/.*",
".*.google-analytics.com/.*",
".*.adservice.google.*/.*",
".*.adbrite.com/.*",
".*.exponential.com/.*",
".*.quantserve.com/.*",
".*.scorecardresearch.com/.*",
".*.zedo.com/.*",
".*.adsafeprotected.com/.*",
".*.teads.tv/.*",
".*.outbrain.com/.*"
];
final List<ContentBlocker> contentBlockers = [];
var contentBlockerEnabled = true;
InAppWebViewController? webViewController;
#override
void initState() {
super.initState();
// for each ad URL filter, add a Content Blocker to block its loading
for (final adUrlFilter in adUrlFilters) {
contentBlockers.add(ContentBlocker(
trigger: ContentBlockerTrigger(
urlFilter: adUrlFilter,
),
action: ContentBlockerAction(
type: ContentBlockerActionType.BLOCK,
)));
}
// apply the "display: none" style to some HTML elements
contentBlockers.add(ContentBlocker(
trigger: ContentBlockerTrigger(
urlFilter: ".*",
),
action: ContentBlockerAction(
type: ContentBlockerActionType.CSS_DISPLAY_NONE,
selector: ".banner, .banners, .ads, .ad, .advert")));
}
adblock() async {
contentBlockerEnabled = !contentBlockerEnabled;
if (contentBlockerEnabled) {
await webViewController?.setSettings(
settings: InAppWebViewSettings(contentBlockers: contentBlockers));
} else {
await webViewController?.setSettings(
settings: InAppWebViewSettings(contentBlockers: []));
}
webViewController?.reload();
setState(() {});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.pink,
),
home: Scaffold(
appBar: AppBar(title: Text("Anime market")),
body: Center(
child: Column(
children: <Widget>[
Container(
child: ElevatedButton(
onPressed: () {
setState(() {
InAppWebView(
key: webViewKey,
initialUrlRequest: URLRequest(
url: Uri.parse('https://www.tomshardware.com/')),
initialData: InAppWebViewSettings(
contentBlockers: contentBlockers),
onWebViewCreated: (controller) {
webViewController = controller;
},
);
});
},
child: Text("sflix"),
),
)
],
)),
),
);
}
}
"InAppWebviewSettings" throughs an error which says it isnt defined.
I am new to flutter so here is my code where its printing one centre text but I need a button under the text.
import 'package:flutter/material.dart';
void main()
{
runApp(MaterialApp(
title: 'Hello Flutter',
home: HomeWidget(),
));
}
class HomeWidget extends StatelessWidget
{
#override
Widget build(BuildContext context)
{
return Material(
child: Container(child: Center(child: Text('Hello World Of Flutter Development'),),),
// Need Button Here beneath Text
);
} //Widget
} //End of Class
use - Column Widget.
Learn more about drawing Layouts:
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
title: 'Hello Flutter',
home: HomeWidget(),
));
}
class HomeWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[
Center(
child: Text('Hello World Of Flutter Development'),
),
RaisedButton(onPressed: (){},child: Text('Button'),) // Button under Text
]),
);
} //Widget
}
Use Column Widget
Column(
children: [
Text('Hello World Of Flutter Development'),
FlatButton(onPressed:() {}, child:Text('name on button')),
],
)
I am building a demo app to test using localization strings.
I get the following error:
I/flutter (21588): The following NoSuchMethodError was thrown building MainApp(dirty):
I/flutter (21588): The getter 'title' was called on null.
I/flutter (21588): Receiver: null
I/flutter (21588): Tried calling: title
I am not sure why I am getting this error. I have followed the indications on flutter documentation.
I have following Localization Class:
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'dart:async';
import 'package:bet_master/l10n/messages_all.dart';
class AppLocalizations {
static Future<AppLocalizations> load(Locale locale) {
final String name =
locale.countryCode.isEmpty ? locale.languageCode : locale.toString();
final localeName = Intl.canonicalizedLocale(name);
return initializeMessages(localeName).then((bool _) {
Intl.defaultLocale = localeName;
return AppLocalizations();
});
}
static AppLocalizations of(BuildContext context) {
return Localizations.of<AppLocalizations>(context, AppLocalizations);
}
String get title {
return Intl.message(
'Bet Master',
name: 'title',
desc: 'App Title'
);
}
String get search {
return Intl.message(
'Search',
name: 'search',
desc : ''
);
}
}
class AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
const AppLocalizationsDelegate();
#override
bool isSupported(Locale locale) {
return ['en', 'es', 'fr'].contains(locale.languageCode);
}
#override
Future<AppLocalizations> load(Locale locale) {
return AppLocalizations.load(locale);
}
#override
bool shouldReload(AppLocalizationsDelegate old) {
return false;
}
}
For the Home Widget I am only setting the title
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:bet_master/localization/localizations.dart';
void main() {
runApp(MainApp());
}
class MainApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
localizationsDelegates: [
const AppLocalizationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate
],
supportedLocales: [
const Locale('en', ''),
const Locale('es', ''),
const Locale('fr', ''),
],
home: Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context).title),
),
),
);
}
}
At the end the issue seems related to Localization not being available, I moved the "home" code to another widget and solved the issue.
Widget build(BuildContext context) {
return new MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
_appLocalizationsDelegate,
],
supportedLocales: [
Locale('en'),
Locale('es'),
],
locale: _appLocalizationsDelegate.overridenLocale,
onGenerateTitle: (BuildContext context) => AppLocalizations.of(context).title,
home: Home()
);
}
}
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context).title),
),
body: Column(children: <Widget>[
Text('hola'),
],)
);
}
}
I need to research still why is this needed, but at least it works now.
I had the same error, but my problem was that I was using two nested
MaterialApp() widgets.
It was causing that this line retuns null:
return Localizations.of<AppLocalizations>(context, AppLocalizations);
I replaced the nested MarerialApp(The child) widget with a Scaffold and It worked.
Hope It helps someone!
Did anyone successfully implemented WebSocket using json_rpc_2 package?https://pub.dartlang.org/packages/json_rpc_2
I try to present live data, e.g. a ticker, from this API: https://api.hitbtc.com/
Actually, I managed to solve the problem. Here's the code:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:json_rpc_2/json_rpc_2.dart' as json_rpc;
import 'package:web_socket_channel/io.dart';
class SymbolDetails extends StatelessWidget {
final String symbolId;
SymbolDetails({this.symbolId});
#override
Widget build(BuildContext context) {
var _api = IOWebSocketChannel.connect('wss://api.hitbtc.com/api/2/ws');
var client = json_rpc.Client(_api.cast());
client.sendNotification(
'subscribeTicker',
{'symbol': '$symbolId'},
);
return Scaffold(
appBar: AppBar(
title: Text('$symbolId details'),
),
body: StreamBuilder(
stream: _api.stream,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.none) {
return Center(
child: Text('Please check your internet connection'),
);
} else if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
}
String _snapshotData = snapshot.data;
Map _response = json.decode(_snapshotData);
return ListView(
children: [
ListTile(
title: Text('Ask price:'),
trailing: Text(
'${_response['params']['ask']}',
style: TextStyle(fontWeight: FontWeight.bold),
),
),
ListTile(
title: Text('Bid price:'),
trailing: Text(
'${_response['params']['bid']}',
style: TextStyle(fontWeight: FontWeight.bold),
),
),
],
);
},
),
);
}
}
I came up with a more fleshed-out example that runs on MongoDB. It is also null-safe. Here is the API I came up with:
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_web_socket/shelf_web_socket.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:mongo_dart/mongo_dart.dart' as mongo;
void main() async {
final handler = webSocketHandler((WebSocketChannel socket){
final server = Server(socket.cast<String>());
server.registerMethod('hello', () async{
mongo.Db db = mongo.Db('mongodb://127.0.0.1:27017/obj1');
await db.open();
var list = await db.collection('Person').find(null).toList();
// await db.close();
return list;
});
server.listen();
});
final server = await shelf_io.serve(handler, '127.0.0.1', 4042);
print('Serving at ws://${server.address.host}:${server.port}');
}
Here is the Flutter client:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:json_rpc_2/json_rpc_2.dart' as json_rpc;
import 'package:web_socket_channel/io.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
const MyHomePage({super.key, required this.title});
#override
Widget build(BuildContext context) {
var api = IOWebSocketChannel.connect(Uri.parse('ws://127.0.0.1:4042'));
var client = json_rpc.Client(api.cast());
client.sendRequest(
'hello',
);
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: StreamBuilder(
stream: api.stream,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.none) {
return const Center(
child: Text('Please check your internet connection'),
);
} else if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
}
String snapshotData = snapshot.data;
Map<String,dynamic> raw = json.decode(snapshotData);List items = raw['result'];
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text('${items[index]["first_name"].toString()} ${items[index]["last_name"].toString()}'),
);
},
);
},
),
);
}
}
When all goes well, the end result is a formatted list of names.