I'm coming from JavaScript where every other line is console.log('Logged!')
. How is this done in Flutter? The Flutter docs show there is a log()
feature. I tried to make a button log to the console when clicked but it didn't work.
I'll show the code snippet first, then the error message, then the full code.
import 'dart:developer';
ElevatedButton(
style: style,
onPressed: () => {
log('Clicked!');
},
child: const Text('My Button'),
),
The error message:
lib/main.dart:45:27: Error: Expected '}' before this.
log('Logged!');
^
And my full code:
import 'package:flutter/material.dart';
import 'dart:developer';
void main() => runApp(const HelloWorld());
class HelloWorld extends StatelessWidget {
const HelloWorld({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
const String appTitle = 'MyApp';
return MaterialApp(
title: appTitle,
home: Scaffold(
appBar: AppBar(title: const Text(appTitle)),
body: const FullNameField(),
),
);
}
}
class FullNameField extends StatelessWidget {
const FullNameField({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final ButtonStyle style = ElevatedButton.styleFrom(textStyle: const TextStyle(fontSize: 20));
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
// alignment: Alignment.center,
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16),
child: TextFormField(
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'Enter your username',
),
),
),
ElevatedButton(
style: style,
onPressed: () => {
log('Clicked!');
},
child: const Text('My Button'),
),
],
);
}
}
Thanks!
CodePudding user response:
You can use debugPrint
Prints a message to the console, which you can access using the "flutter" tool's "logs" command ("flutter logs").
onPressed: () => {
debugPrint("Logged!"),
},
Also, you can use print()
method, which I is not recommended.
CodePudding user response:
The problem was a semi-colon at the end of log('Clicked!');
. When I changed the semi-colon to a comma it worked. I'm coming from JavaScript. :-)
ElevatedButton(
style: style,
onPressed: () => {
log('Clicked!'),
},
child: const Text('Get Fortune'),
),
And debugPrint('Clicked!'),
and print('Clicked!'),
also work.
--
I just figured out that the arrow function has to be followed by commas but without the arrow function you use semi-colons.
onPressed: () {
log('Clicked!');
},
vs.
onPressed: () => {
log('Clicked!'),
},